🚨 Latest Research:Tanstack npm Packages Compromised in Ongoing Mini Shai-Hulud Supply-Chain Attack.Learn More
Socket
Book a DemoSign in
Socket

@adonisjs/http-server

Package Overview
Dependencies
Maintainers
3
Versions
169
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@adonisjs/http-server - npm Package Compare versions

Comparing version
8.0.0-next.19
to
8.0.0
build/define_config-D-kQXU0e.js

Sorry, the diff of this file is too big to display

+1
export {};
import { parseRoute } from "./src/helpers.js";
import { createRequire } from "node:module";
import { InvalidArgumentsException, RuntimeException } from "@poppinss/utils/exception";
import { debuglog } from "node:util";
import string from "@poppinss/utils/string";
import { moduleCaller, moduleImporter } from "@adonisjs/fold";
import Cache from "tmp-cache";
import Macroable from "@poppinss/macroable";
import is from "@sindresorhus/is";
import Middleware from "@poppinss/middleware";
import diagnostics_channel from "node:diagnostics_channel";
import StringBuilder from "@poppinss/utils/string_builder";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
return target;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __require = /* @__PURE__ */ createRequire(import.meta.url);
var debug_default = debuglog("adonisjs:http");
function canWriteResponseBody(value, ctx) {
return value !== void 0 && !ctx.response.hasLazyBody && value !== ctx.response;
}
function useReturnValue(ctx) {
return function(value) {
if (canWriteResponseBody(value, ctx)) ctx.response.send(value);
};
}
var tracing_channels_exports = /* @__PURE__ */ __exportAll({
httpExceptionHandler: () => httpExceptionHandler,
httpMiddleware: () => httpMiddleware,
httpRequest: () => httpRequest,
httpResponseSerializer: () => httpResponseSerializer,
httpRouteHandler: () => httpRouteHandler
});
const httpRequest = diagnostics_channel.tracingChannel("adonisjs.http.request");
const httpMiddleware = diagnostics_channel.tracingChannel("adonisjs.http.middleware");
const httpExceptionHandler = diagnostics_channel.tracingChannel("adonisjs.http.exception.handler");
const httpRouteHandler = diagnostics_channel.tracingChannel("adonisjs.http.route.handler");
const httpResponseSerializer = diagnostics_channel.tracingChannel("adonisjs.http.response.serializer");
function execute(route, resolver, ctx, errorResponder) {
return route.middleware.runner().errorHandler((error) => errorResponder(error, ctx)).finalHandler(() => {
if (typeof route.handler === "function") return httpRouteHandler.tracePromise(($ctx) => Promise.resolve(route.handler($ctx)), httpRouteHandler.hasSubscribers ? { route } : void 0, void 0, ctx).then(useReturnValue(ctx));
return httpRouteHandler.tracePromise(route.handler.handle, httpRouteHandler.hasSubscribers ? { route } : void 0, void 0, resolver, ctx).then(useReturnValue(ctx));
}).run(async (middleware, next) => {
if (typeof middleware === "function") return httpMiddleware.tracePromise(middleware, httpMiddleware.hasSubscribers ? { middleware } : void 0, void 0, ctx, next);
return httpMiddleware.tracePromise(middleware.handle, httpMiddleware.hasSubscribers ? { middleware } : void 0, void 0, resolver, ctx, next, middleware.args);
});
}
var Route = class extends Macroable {
#pattern;
#methods;
#name;
#isDeleted = false;
#handler;
#globalMatchers;
#app;
#routerMiddleware;
#routeDomain = "root";
#matchers = {};
#prefixes = [];
#middleware = [];
constructor(app, routerMiddleware, options) {
super();
this.#app = app;
this.#routerMiddleware = routerMiddleware;
this.#pattern = options.pattern;
this.#methods = options.methods;
this.#globalMatchers = options.globalMatchers;
const { handler, routeName } = this.#resolveRouteHandle(options.handler);
this.#handler = handler;
this.#name = routeName;
}
#resolveRouteHandle(handler) {
if (typeof handler === "string") {
const parts = handler.split(".");
const method = parts.length === 1 ? "handle" : parts.pop();
const moduleRefId = parts.join(".");
const controllerName = new StringBuilder(moduleRefId.split("/").pop()).removeSuffix("controller").snakeCase();
return {
handler: {
method,
reference: handler,
importExpression: moduleRefId,
...moduleImporter(() => this.#app.import(moduleRefId), method).toHandleMethod(),
name: handler
},
routeName: method === "handle" ? controllerName.toString() : `${controllerName}.${string.snakeCase(method)}`
};
}
if (Array.isArray(handler)) {
const controller = handler[0];
const method = handler[1] ?? "handle";
if (is.class(controller)) {
const controllerName = new StringBuilder(controller.name).removeSuffix("controller").snakeCase();
return {
handler: {
method,
reference: handler,
importExpression: null,
...moduleCaller(controller, method).toHandleMethod()
},
routeName: method === "handle" ? controllerName.toString() : `${controllerName}.${string.snakeCase(method)}`
};
}
const controllerName = controller.name ? new StringBuilder(controller.name).removeSuffix("controller").snakeCase() : void 0;
return {
handler: {
method,
reference: handler,
importExpression: String(controller),
...moduleImporter(controller, method).toHandleMethod()
},
routeName: controllerName ? method === "handle" ? controllerName.toString() : `${controllerName}.${string.snakeCase(method)}` : void 0
};
}
return { handler };
}
#getMatchers() {
return {
...this.#globalMatchers,
...this.#matchers
};
}
#computePattern() {
const pattern = dropSlash(this.#pattern);
const prefix = this.#prefixes.slice().reverse().map((one) => dropSlash(one)).join("");
return prefix ? `${prefix}${pattern === "/" ? "" : pattern}` : pattern;
}
getHandler() {
return this.#handler;
}
where(param, matcher) {
if (this.#matchers[param]) return this;
if (typeof matcher === "string") this.#matchers[param] = { match: new RegExp(matcher) };
else if (is.regExp(matcher)) this.#matchers[param] = { match: matcher };
else this.#matchers[param] = matcher;
return this;
}
prefix(prefix) {
this.#prefixes.push(prefix);
return this;
}
domain(domain, overwrite = false) {
if (this.#routeDomain === "root" || overwrite) this.#routeDomain = domain;
return this;
}
use(middleware) {
this.#middleware.push(Array.isArray(middleware) ? middleware : [middleware]);
return this;
}
middleware(middleware) {
return this.use(middleware);
}
as(name, prepend = false) {
if (prepend) {
if (!this.#name) throw new RuntimeException(`Routes inside a group must have names before calling "router.group.as"`);
this.#name = `${name}.${this.#name}`;
return this;
}
this.#name = name;
return this;
}
isDeleted() {
return this.#isDeleted;
}
markAsDeleted() {
this.#isDeleted = true;
}
getName() {
return this.#name;
}
getPattern() {
return this.#pattern;
}
setPattern(pattern) {
this.#pattern = pattern;
return this;
}
getMiddleware() {
return this.#middleware;
}
#getMiddlewareForStore() {
const middleware = new Middleware();
this.#routerMiddleware.forEach((one) => {
debug_default("adding global middleware to route %s, %O", this.#pattern, one);
middleware.add(one);
});
this.#middleware.flat().forEach((one) => {
debug_default("adding named middleware to route %s, %O", this.#pattern, one);
middleware.add(one);
});
middleware.freeze();
return middleware;
}
toJSON() {
const pattern = this.#computePattern();
const matchers = this.#getMatchers();
return {
domain: this.#routeDomain,
pattern,
matchers,
tokens: parseRoute(pattern, matchers),
meta: {},
name: this.#name,
handler: this.#handler,
methods: this.#methods,
middleware: this.#getMiddlewareForStore(),
execute
};
}
};
var BriskRoute = class extends Macroable {
#pattern;
#globalMatchers;
#app;
#routerMiddleware;
route = null;
constructor(app, routerMiddleware, options) {
super();
this.#app = app;
this.#routerMiddleware = routerMiddleware;
this.#pattern = options.pattern;
this.#globalMatchers = options.globalMatchers;
}
setHandler(handler) {
this.route = new Route(this.#app, this.#routerMiddleware, {
pattern: this.#pattern,
globalMatchers: this.#globalMatchers,
methods: ["GET", "HEAD"],
handler
});
return this.route;
}
redirect(...args) {
const [identifier, params, options] = args;
function redirectsToRoute(ctx) {
const redirector = ctx.response.redirect();
if (options?.status) redirector.status(options.status);
return redirector.toRoute(identifier, params || ctx.params, options);
}
Object.defineProperty(redirectsToRoute, "listArgs", {
value: identifier,
writable: false
});
return this.setHandler(redirectsToRoute);
}
redirectToPath(url, options) {
function redirectsToPath(ctx) {
const redirector = ctx.response.redirect();
if (options?.status) redirector.status(options.status);
return redirector.toPath(url);
}
Object.defineProperty(redirectsToPath, "listArgs", {
value: url,
writable: false
});
return this.setHandler(redirectsToPath);
}
};
var RouteResource = class extends Macroable {
#resource;
#controller;
#shallow = false;
#globalMatchers;
#app;
#routerMiddleware;
#params = {};
#routesBaseName;
routes = [];
constructor(app, routerMiddleware, options) {
super();
this.#validateResourceName(options.resource);
this.#app = app;
this.#shallow = options.shallow;
this.#routerMiddleware = routerMiddleware;
this.#controller = options.controller;
this.#globalMatchers = options.globalMatchers;
this.#resource = this.#normalizeResourceName(options.resource);
this.#routesBaseName = this.#getRoutesBaseName();
this.#buildRoutes();
}
#normalizeResourceName(resource) {
return resource.replace(/^\//, "").replace(/\/$/, "");
}
#validateResourceName(resource) {
if (!resource || resource === "/") throw new RuntimeException(`Invalid resource name "${resource}"`);
}
#getRoutesBaseName() {
return this.#resource.split(".").map((token) => string.snakeCase(token)).join(".");
}
#createRoute(pattern, methods, action) {
const route = new Route(this.#app, this.#routerMiddleware, {
pattern,
methods,
handler: typeof this.#controller === "string" ? `${this.#controller}.${action}` : [this.#controller, action],
globalMatchers: this.#globalMatchers
});
route.as(`${this.#routesBaseName}.${action}`);
this.routes.push(route);
}
#getResourceId(resource) {
return `${string.snakeCase(string.singular(resource))}_id`;
}
#buildRoutes() {
const resources = this.#resource.split(".");
const mainResource = resources.pop();
this.#params[mainResource] = ":id";
const baseURI = `${resources.map((resource) => {
const paramName = `:${this.#getResourceId(resource)}`;
this.#params[resource] = paramName;
return `${resource}/${paramName}`;
}).join("/")}/${mainResource}`;
this.#createRoute(baseURI, ["GET", "HEAD"], "index");
this.#createRoute(`${baseURI}/create`, ["GET", "HEAD"], "create");
this.#createRoute(baseURI, ["POST"], "store");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["GET", "HEAD"], "show");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id/edit`, ["GET", "HEAD"], "edit");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["PUT", "PATCH"], "update");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["DELETE"], "destroy");
}
#filter(names, inverse) {
const actions = Array.isArray(names) ? names : [names];
return this.routes.filter((route) => {
const match = actions.find((name) => route.getName().endsWith(name));
return inverse ? !match : match;
});
}
only(names) {
this.#filter(names, true).forEach((route) => route.markAsDeleted());
return this;
}
except(names) {
this.#filter(names, false).forEach((route) => route.markAsDeleted());
return this;
}
apiOnly() {
return this.except(["create", "edit"]);
}
where(key, matcher) {
this.routes.forEach((route) => {
route.where(key, matcher);
});
return this;
}
tap(actions, callback) {
if (typeof actions === "function") {
this.routes.forEach((route) => {
if (!route.isDeleted()) actions(route);
});
return this;
}
this.#filter(actions, false).forEach((route) => {
if (!route.isDeleted()) callback(route);
});
return this;
}
params(resources) {
Object.keys(resources).forEach((resource) => {
const param = resources[resource];
const existingParam = this.#params[resource];
this.#params[resource] = `:${param}`;
this.routes.forEach((route) => {
route.setPattern(route.getPattern().replace(`${resource}/${existingParam}`, `${resource}/:${param}`));
});
});
return this;
}
use(actions, middleware) {
if (actions === "*") this.tap((route) => route.use(middleware));
else this.tap(actions, (route) => route.use(middleware));
return this;
}
middleware(actions, middleware) {
return this.use(actions, middleware);
}
as(name, normalizeName = true) {
name = normalizeName ? string.snakeCase(name) : name;
this.routes.forEach((route) => {
route.as(route.getName().replace(this.#routesBaseName, name), false);
});
this.#routesBaseName = name;
return this;
}
};
var RouteGroup = class RouteGroup extends Macroable {
#middleware = [];
constructor(routes) {
super();
this.routes = routes;
}
#shareMiddlewareStackWithRoutes(route) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#shareMiddlewareStackWithRoutes(child));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.getMiddleware().unshift(this.#middleware));
return;
}
if (route instanceof BriskRoute) {
route.route.getMiddleware().unshift(this.#middleware);
return;
}
route.getMiddleware().unshift(this.#middleware);
}
#updateRouteName(route, name) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#updateRouteName(child, name));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.as(name, true));
return;
}
if (route instanceof BriskRoute) {
route.route.as(name, true);
return;
}
route.as(name, true);
}
#setRoutePrefix(route, prefix) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#setRoutePrefix(child, prefix));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.prefix(prefix));
return;
}
if (route instanceof BriskRoute) {
route.route.prefix(prefix);
return;
}
route.prefix(prefix);
}
#updateRouteDomain(route, domain) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#updateRouteDomain(child, domain));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.domain(domain));
return;
}
if (route instanceof BriskRoute) {
route.route.domain(domain, false);
return;
}
route.domain(domain, false);
}
#updateRouteMatchers(route, param, matcher) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#updateRouteMatchers(child, param, matcher));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.where(param, matcher));
return;
}
if (route instanceof BriskRoute) {
route.route.where(param, matcher);
return;
}
route.where(param, matcher);
}
where(param, matcher) {
this.routes.forEach((route) => this.#updateRouteMatchers(route, param, matcher));
return this;
}
prefix(prefix) {
this.routes.forEach((route) => this.#setRoutePrefix(route, prefix));
return this;
}
domain(domain) {
this.routes.forEach((route) => this.#updateRouteDomain(route, domain));
return this;
}
as(name) {
this.routes.forEach((route) => this.#updateRouteName(route, name));
return this;
}
use(middleware) {
if (!this.#middleware.length) this.routes.forEach((route) => this.#shareMiddlewareStackWithRoutes(route));
if (Array.isArray(middleware)) for (let one of middleware) this.#middleware.push(one);
else this.#middleware.push(middleware);
return this;
}
middleware(middleware) {
return this.use(middleware);
}
};
const proxyCache = new Cache({ max: 200 });
function dropSlash(input) {
if (input === "/") return "/";
return `/${input.replace(/^\//, "").replace(/\/$/, "")}`;
}
function toRoutesJSON(routes) {
return routes.reduce((list, route) => {
if (route instanceof RouteGroup) {
list = list.concat(toRoutesJSON(route.routes));
return list;
}
if (route instanceof RouteResource) {
list = list.concat(toRoutesJSON(route.routes));
return list;
}
if (route instanceof BriskRoute) {
if (route.route && !route.route.isDeleted()) list.push(route.route.toJSON());
return list;
}
if (!route.isDeleted()) list.push(route.toJSON());
return list;
}, []);
}
function trustProxy(remoteAddress, proxyFn) {
if (proxyCache.has(remoteAddress)) return proxyCache.get(remoteAddress);
const result = proxyFn(remoteAddress, 0);
proxyCache.set(remoteAddress, result);
return result;
}
function parseRange(range, value) {
const parts = range.split("..");
const min = Number(parts[0]);
const max = Number(parts[1]);
if (parts.length === 1 && !Number.isNaN(min)) return { [min]: value };
if (Number.isNaN(min) || Number.isNaN(max)) return {};
if (min === max) return { [min]: value };
if (max < min) throw new InvalidArgumentsException(`Invalid range "${range}"`);
return [...Array(max - min + 1).keys()].reduce((result, step) => {
result[min + step] = value;
return result;
}, {});
}
function decodeComponentChar(highCharCode, lowCharCode) {
if (highCharCode === 50) {
if (lowCharCode === 53) return "%";
if (lowCharCode === 51) return "#";
if (lowCharCode === 52) return "$";
if (lowCharCode === 54) return "&";
if (lowCharCode === 66) return "+";
if (lowCharCode === 98) return "+";
if (lowCharCode === 67) return ",";
if (lowCharCode === 99) return ",";
if (lowCharCode === 70) return "/";
if (lowCharCode === 102) return "/";
return null;
}
if (highCharCode === 51) {
if (lowCharCode === 65) return ":";
if (lowCharCode === 97) return ":";
if (lowCharCode === 66) return ";";
if (lowCharCode === 98) return ";";
if (lowCharCode === 68) return "=";
if (lowCharCode === 100) return "=";
if (lowCharCode === 70) return "?";
if (lowCharCode === 102) return "?";
return null;
}
if (highCharCode === 52 && lowCharCode === 48) return "@";
return null;
}
function safeDecodeURI(path, useSemicolonDelimiter) {
let shouldDecode = false;
let shouldDecodeParam = false;
let querystring = "";
for (let i = 1; i < path.length; i++) {
const charCode = path.charCodeAt(i);
if (charCode === 37) {
const highCharCode = path.charCodeAt(i + 1);
const lowCharCode = path.charCodeAt(i + 2);
if (decodeComponentChar(highCharCode, lowCharCode) === null) shouldDecode = true;
else {
shouldDecodeParam = true;
if (highCharCode === 50 && lowCharCode === 53) {
shouldDecode = true;
path = path.slice(0, i + 1) + "25" + path.slice(i + 1);
i += 2;
}
i += 2;
}
} else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
querystring = path.slice(i + 1);
path = path.slice(0, i);
break;
}
}
return {
pathname: shouldDecode ? decodeURI(path) : path,
query: querystring,
shouldDecodeParam
};
}
export { __exportAll as _, RouteGroup as a, Route as c, httpRequest as d, httpResponseSerializer as f, __commonJSMin as g, debug_default as h, trustProxy as i, httpExceptionHandler as l, canWriteResponseBody as m, safeDecodeURI as n, RouteResource as o, tracing_channels_exports as p, toRoutesJSON as r, BriskRoute as s, parseRange as t, httpMiddleware as u, __require as v, __toESM as y };
+4
-3

@@ -1,5 +0,6 @@

import { s as parseRoute } from "../helpers-BIq3lNz1.js";
import { _ as Qs, c as HttpRequest, i as HttpResponse, n as Server, r as HttpContext, s as Router, t as defineConfig } from "../define_config-Cg6Nym29.js";
import "../utils-BjSHKI3s.js";
import { _ as Qs, c as HttpRequest, i as HttpResponse, n as Server, r as HttpContext, s as Router, t as defineConfig } from "../define_config-D-kQXU0e.js";
import { t as createURL } from "../helpers-C_2HouOe.js";
import "../url_builder-piNQy-CF.js";
import { parseRoute } from "../src/helpers.js";
import "../types-AUwURgIL.js";
import { Container } from "@adonisjs/fold";

@@ -6,0 +7,0 @@ import { Socket } from "node:net";

@@ -1,5 +0,5 @@

import { C as canWriteResponseBody, S as tracing_channels_exports, _ as Route, g as BriskRoute, h as RouteResource, m as RouteGroup, u as parseRange } from "./helpers-BIq3lNz1.js";
import { _ as Qs, a as CookieSerializer, c as HttpRequest, d as Redirect, f as E_CANNOT_LOOKUP_ROUTE, g as errors_exports, h as E_ROUTE_NOT_FOUND, i as HttpResponse, l as CookieParser, m as E_HTTP_REQUEST_ABORTED, n as Server, o as ResponseStatus, p as E_HTTP_EXCEPTION, r as HttpContext, s as Router, t as defineConfig, u as CookieClient } from "./define_config-Cg6Nym29.js";
import { a as RouteGroup, c as Route, m as canWriteResponseBody, o as RouteResource, p as tracing_channels_exports, s as BriskRoute, t as parseRange } from "./utils-BjSHKI3s.js";
import { _ as Qs, a as CookieSerializer, c as HttpRequest, d as Redirect, f as E_CANNOT_LOOKUP_ROUTE, g as errors_exports, h as E_ROUTE_NOT_FOUND, i as HttpResponse, l as CookieParser, m as E_HTTP_REQUEST_ABORTED, n as Server, o as ResponseStatus, p as E_HTTP_EXCEPTION, r as HttpContext, s as Router, t as defineConfig, u as CookieClient } from "./define_config-D-kQXU0e.js";
import "./helpers-C_2HouOe.js";
import "./url_builder-piNQy-CF.js";
import "./types-AUwURgIL.js";
import Macroable from "@poppinss/macroable";

@@ -124,3 +124,2 @@ import is from "@sindresorhus/is";

case "json": return this.renderErrorAsJSON(error, ctx);
case "html":
default: return this.renderErrorAsHTML(error, ctx);

@@ -137,3 +136,2 @@ }

case "json": return this.renderValidationErrorAsJSON(error, ctx);
case "html":
default: return this.renderValidationErrorAsHTML(error, ctx);

@@ -140,0 +138,0 @@ }

import { n as findRoute, t as createURL } from "../../helpers-C_2HouOe.js";
import { t as createUrlBuilder } from "../../url_builder-piNQy-CF.js";
import "../../types-AUwURgIL.js";
function createUrlBuilder(routesLoader, searchParamsStringifier) {
let domainsList;
let domainsRoutes;
function createUrlForRoute(identifier, params, options, method) {
if (!domainsRoutes) {
domainsRoutes = typeof routesLoader === "function" ? routesLoader() : routesLoader;
if (!domainsRoutes || typeof domainsRoutes !== "object") throw new Error(`Cannot construct routes. Expected the value to be an object, instead received ${typeof domainsRoutes}`);
if (!domainsList) domainsList = Object.keys(domainsRoutes).filter((domain) => domain !== "root");
}
const domain = domainsList.find((name) => identifier.startsWith(`${name}@`));
const routeIdentifier = domain ? identifier.replace(new RegExp(`^${domain}@`), "") : identifier;
const route = findRoute(domainsRoutes, routeIdentifier, domain, method, true);
if (!route) {
if (method) throw new Error(`Cannot lookup route "${routeIdentifier}" for method "${method}"`);
throw new Error(`Cannot lookup route "${routeIdentifier}"`);
}
return createURL(route.name ?? route.pattern, route.tokens, searchParamsStringifier, params, options);
}
const urlFor = function route(...[identifier, params, options]) {
return createUrlForRoute(identifier, params, options);
};
urlFor.get = function urlForMethodGet(...[identifier, params, options]) {
const method = "GET";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.post = function urlForMethodPost(...[identifier, params, options]) {
const method = "POST";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.put = function urlForMethodPut(...[identifier, params, options]) {
const method = "PUT";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.patch = function urlForMethodPatch(...[identifier, params, options]) {
const method = "PATCH";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.delete = function urlForMethodDelete(...[identifier, params, options]) {
const method = "DELETE";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.method = function urlForCustomMethod(method, ...[identifier, params, options]) {
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
return urlFor;
}
export { createURL, createUrlBuilder, findRoute };

@@ -1,3 +0,76 @@

import { a as middlewareInfo, c as routeInfo, i as matchRoute, l as serializeCookie, n as createSignedURL, o as mime, r as encodeUrl, s as parseRoute, t as appendQueryString } from "../helpers-BIq3lNz1.js";
import { n as safeDecodeURI } from "../utils-BjSHKI3s.js";
import { t as createURL } from "../helpers-C_2HouOe.js";
import { serialize } from "cookie-es";
import matchit from "@poppinss/matchit";
import string from "@poppinss/utils/string";
import { parseBindingReference } from "@adonisjs/fold";
import encodeUrl from "encodeurl";
import mime from "mime-types";
function parseRoute(pattern, matchers) {
return matchit.parse(pattern, matchers);
}
function createSignedURL(identifier, tokens, searchParamsStringifier, encryption, params, options) {
const signature = encryption.getMessageVerifier().sign(createURL(identifier, tokens, searchParamsStringifier, params, {
...options,
prefixUrl: void 0
}), options?.expiresIn, options?.purpose);
return createURL(identifier, tokens, searchParamsStringifier, params, {
...options,
qs: {
...options?.qs,
signature
}
});
}
function matchRoute(url, patterns) {
const tokensBucket = patterns.map((pattern) => parseRoute(pattern));
const match = matchit.match(url, tokensBucket);
if (!match.length) return null;
return matchit.exec(url, match);
}
function serializeCookie(key, value, options) {
let expires;
let maxAge;
if (options) {
expires = typeof options.expires === "function" ? options.expires() : options.expires;
maxAge = options.maxAge ? string.seconds.parse(options.maxAge) : void 0;
}
return serialize(key, value, {
...options,
maxAge,
expires
});
}
async function middlewareInfo(middleware) {
if (typeof middleware === "function") return {
type: "closure",
name: middleware.name || "closure"
};
if ("args" in middleware) return {
type: "named",
name: middleware.name,
args: middleware.args,
...await parseBindingReference([middleware.reference])
};
return {
type: "global",
name: middleware.name,
...await parseBindingReference([middleware.reference])
};
}
async function routeInfo(route) {
return "reference" in route.handler ? {
type: "controller",
...await parseBindingReference(route.handler.reference)
} : {
type: "closure",
name: route.handler.name || "closure",
args: "listArgs" in route.handler ? String(route.handler.listArgs) : void 0
};
}
function appendQueryString(uri, queryString, qsParser) {
const { query, pathname } = safeDecodeURI(uri, false);
const mergedQueryString = qsParser.stringify(Object.assign(qsParser.parse(query), queryString));
return mergedQueryString ? `${pathname}?${mergedQueryString}` : pathname;
}
export { appendQueryString, createSignedURL, createURL, encodeUrl, matchRoute, middlewareInfo, mime, parseRoute, routeInfo, serializeCookie };
{
"name": "@adonisjs/http-server",
"version": "8.0.0-next.19",
"version": "8.0.0",
"description": "AdonisJS HTTP server with support packed with Routing and Cookies",

@@ -24,3 +24,3 @@ "main": "build/index.js",

"pretest": "npm run lint",
"test": "cross-env NODE_DEBUG=adonisjs:http c8 npm run quick:test",
"test": "cross-env NODE_DEBUG=adonisjs:http npm run quick:test",
"typecheck": "tsc --noEmit",

@@ -47,9 +47,9 @@ "precompile": "npm run lint",

"devDependencies": {
"@adonisjs/application": "^9.0.0-next.14",
"@adonisjs/eslint-config": "^3.0.0-next.1",
"@adonisjs/events": "^10.1.0-next.4",
"@adonisjs/fold": "^11.0.0-next.4",
"@adonisjs/logger": "^7.1.0-next.3",
"@adonisjs/application": "^9.0.0",
"@adonisjs/eslint-config": "^3.0.0",
"@adonisjs/events": "^10.1.0",
"@adonisjs/fold": "^11.0.0",
"@adonisjs/logger": "^7.1.0",
"@adonisjs/prettier-config": "^1.4.5",
"@adonisjs/tsconfig": "^2.0.0-next.3",
"@adonisjs/tsconfig": "^2.0.0",
"@boringnode/encryption": "^1.0.0",

@@ -60,6 +60,6 @@ "@fastify/middie": "^9.1.0",

"@japa/file-system": "^3.0.0",
"@japa/runner": "^5.0.0",
"@japa/runner": "^5.3.0",
"@japa/snapshot": "^2.0.10",
"@poppinss/ts-exec": "^1.4.1",
"@release-it/conventional-changelog": "^10.0.4",
"@poppinss/ts-exec": "^1.4.4",
"@release-it/conventional-changelog": "^10.0.5",
"@types/accepts": "^1.3.7",

@@ -73,3 +73,3 @@ "@types/content-disposition": "^0.5.9",

"@types/mime-types": "^3.0.1",
"@types/node": "^25.0.3",
"@types/node": "^25.3.0",
"@types/on-finished": "^2.3.5",

@@ -81,9 +81,9 @@ "@types/pem": "^1.14.4",

"@types/vary": "^1.1.3",
"@vinejs/vine": "^4.2.0",
"@vinejs/vine": "^4.3.0",
"accepts": "^1.3.8",
"autocannon": "^8.0.0",
"c8": "^10.1.3",
"c8": "^11.0.0",
"cross-env": "^10.1.0",
"eslint": "^9.39.2",
"fastify": "^5.6.2",
"eslint": "^10.0.2",
"fastify": "^5.7.4",
"fs-extra": "^11.3.3",

@@ -93,10 +93,10 @@ "get-port": "^7.1.0",

"pem": "^1.14.8",
"prettier": "^3.7.4",
"prettier": "^3.8.1",
"reflect-metadata": "^0.2.2",
"release-it": "^19.2.3",
"release-it": "^19.2.4",
"supertest": "^7.2.2",
"tsdown": "^0.18.4",
"typedoc": "^0.28.15",
"tsdown": "^0.20.3",
"typedoc": "^0.28.17",
"typescript": "^5.9.3",
"youch": "^4.1.0-beta.13"
"youch": "^4.1.0"
},

@@ -108,3 +108,3 @@ "dependencies": {

"@poppinss/qs": "^6.15.0",
"@poppinss/utils": "^7.0.0-next.4",
"@poppinss/utils": "^7.0.0",
"@sindresorhus/is": "^7.2.0",

@@ -125,8 +125,8 @@ "content-disposition": "^1.0.1",

"peerDependencies": {
"@adonisjs/application": "^9.0.0-next.14",
"@adonisjs/events": "^10.1.0-next.4",
"@adonisjs/fold": "^11.0.0-next.4",
"@adonisjs/logger": "^7.1.0-next.3",
"@adonisjs/application": "^9.0.0-next.14 || ^9.0.0",
"@adonisjs/events": "^10.1.0-next.4 || ^10.1.0",
"@adonisjs/fold": "^11.0.0-next.4 || ^11.0.0",
"@adonisjs/logger": "^7.1.0-next.3 || ^7.1.0",
"@boringnode/encryption": "^0.2.0 || ^1.0.0",
"youch": "^4.1.0-beta.13"
"youch": "^4.1.0-beta.13 || ^4.1.0"
},

@@ -195,2 +195,7 @@ "peerDependenciesMeta": {

],
"noExternal": [
"accepts",
"negotiator"
],
"inlineOnly": false,
"outDir": "./build",

@@ -197,0 +202,0 @@ "clean": true,

Sorry, the diff of this file is too big to display

import { t as createURL } from "./helpers-C_2HouOe.js";
import { createRequire } from "node:module";
import { InvalidArgumentsException, RuntimeException } from "@poppinss/utils/exception";
import { debuglog } from "node:util";
import { serialize } from "cookie-es";
import matchit from "@poppinss/matchit";
import string from "@poppinss/utils/string";
import { moduleCaller, moduleImporter, parseBindingReference } from "@adonisjs/fold";
import Cache from "tmp-cache";
import Macroable from "@poppinss/macroable";
import is from "@sindresorhus/is";
import Middleware from "@poppinss/middleware";
import diagnostics_channel from "node:diagnostics_channel";
import StringBuilder from "@poppinss/utils/string_builder";
import encodeUrl from "encodeurl";
import mime from "mime-types";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __exportAll = (all, symbols) => {
let target = {};
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
if (symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
return target;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __require = /* @__PURE__ */ createRequire(import.meta.url);
var debug_default = debuglog("adonisjs:http");
function canWriteResponseBody(value, ctx) {
return value !== void 0 && !ctx.response.hasLazyBody && value !== ctx.response;
}
function useReturnValue(ctx) {
return function(value) {
if (canWriteResponseBody(value, ctx)) ctx.response.send(value);
};
}
var tracing_channels_exports = /* @__PURE__ */ __exportAll({
httpExceptionHandler: () => httpExceptionHandler,
httpMiddleware: () => httpMiddleware,
httpRequest: () => httpRequest,
httpResponseSerializer: () => httpResponseSerializer,
httpRouteHandler: () => httpRouteHandler
});
const httpRequest = diagnostics_channel.tracingChannel("adonisjs.http.request");
const httpMiddleware = diagnostics_channel.tracingChannel("adonisjs.http.middleware");
const httpExceptionHandler = diagnostics_channel.tracingChannel("adonisjs.http.exception.handler");
const httpRouteHandler = diagnostics_channel.tracingChannel("adonisjs.http.route.handler");
const httpResponseSerializer = diagnostics_channel.tracingChannel("adonisjs.http.response.serializer");
function execute(route, resolver, ctx, errorResponder) {
return route.middleware.runner().errorHandler((error) => errorResponder(error, ctx)).finalHandler(() => {
if (typeof route.handler === "function") return httpRouteHandler.tracePromise(($ctx) => Promise.resolve(route.handler($ctx)), httpRouteHandler.hasSubscribers ? { route } : void 0, void 0, ctx).then(useReturnValue(ctx));
return httpRouteHandler.tracePromise(route.handler.handle, httpRouteHandler.hasSubscribers ? { route } : void 0, void 0, resolver, ctx).then(useReturnValue(ctx));
}).run(async (middleware, next) => {
if (typeof middleware === "function") return httpMiddleware.tracePromise(middleware, httpMiddleware.hasSubscribers ? { middleware } : void 0, void 0, ctx, next);
return httpMiddleware.tracePromise(middleware.handle, httpMiddleware.hasSubscribers ? { middleware } : void 0, void 0, resolver, ctx, next, middleware.args);
});
}
var Route = class extends Macroable {
#pattern;
#methods;
#name;
#isDeleted = false;
#handler;
#globalMatchers;
#app;
#routerMiddleware;
#routeDomain = "root";
#matchers = {};
#prefixes = [];
#middleware = [];
constructor(app, routerMiddleware, options) {
super();
this.#app = app;
this.#routerMiddleware = routerMiddleware;
this.#pattern = options.pattern;
this.#methods = options.methods;
this.#globalMatchers = options.globalMatchers;
const { handler, routeName } = this.#resolveRouteHandle(options.handler);
this.#handler = handler;
this.#name = routeName;
}
#resolveRouteHandle(handler) {
if (typeof handler === "string") {
const parts = handler.split(".");
const method = parts.length === 1 ? "handle" : parts.pop();
const moduleRefId = parts.join(".");
const controllerName = new StringBuilder(moduleRefId.split("/").pop()).removeSuffix("controller").snakeCase();
return {
handler: {
method,
reference: handler,
importExpression: moduleRefId,
...moduleImporter(() => this.#app.import(moduleRefId), method).toHandleMethod(),
name: handler
},
routeName: method === "handle" ? controllerName.toString() : `${controllerName}.${string.snakeCase(method)}`
};
}
if (Array.isArray(handler)) {
const controller = handler[0];
const method = handler[1] ?? "handle";
if (is.class(controller)) {
const controllerName$1 = new StringBuilder(controller.name).removeSuffix("controller").snakeCase();
return {
handler: {
method,
reference: handler,
importExpression: null,
...moduleCaller(controller, method).toHandleMethod()
},
routeName: method === "handle" ? controllerName$1.toString() : `${controllerName$1}.${string.snakeCase(method)}`
};
}
const controllerName = controller.name ? new StringBuilder(controller.name).removeSuffix("controller").snakeCase() : void 0;
return {
handler: {
method,
reference: handler,
importExpression: String(controller),
...moduleImporter(controller, method).toHandleMethod()
},
routeName: controllerName ? method === "handle" ? controllerName.toString() : `${controllerName}.${string.snakeCase(method)}` : void 0
};
}
return { handler };
}
#getMatchers() {
return {
...this.#globalMatchers,
...this.#matchers
};
}
#computePattern() {
const pattern = dropSlash(this.#pattern);
const prefix = this.#prefixes.slice().reverse().map((one) => dropSlash(one)).join("");
return prefix ? `${prefix}${pattern === "/" ? "" : pattern}` : pattern;
}
getHandler() {
return this.#handler;
}
where(param, matcher) {
if (this.#matchers[param]) return this;
if (typeof matcher === "string") this.#matchers[param] = { match: new RegExp(matcher) };
else if (is.regExp(matcher)) this.#matchers[param] = { match: matcher };
else this.#matchers[param] = matcher;
return this;
}
prefix(prefix) {
this.#prefixes.push(prefix);
return this;
}
domain(domain, overwrite = false) {
if (this.#routeDomain === "root" || overwrite) this.#routeDomain = domain;
return this;
}
use(middleware) {
this.#middleware.push(Array.isArray(middleware) ? middleware : [middleware]);
return this;
}
middleware(middleware) {
return this.use(middleware);
}
as(name, prepend = false) {
if (prepend) {
if (!this.#name) throw new RuntimeException(`Routes inside a group must have names before calling "router.group.as"`);
this.#name = `${name}.${this.#name}`;
return this;
}
this.#name = name;
return this;
}
isDeleted() {
return this.#isDeleted;
}
markAsDeleted() {
this.#isDeleted = true;
}
getName() {
return this.#name;
}
getPattern() {
return this.#pattern;
}
setPattern(pattern) {
this.#pattern = pattern;
return this;
}
getMiddleware() {
return this.#middleware;
}
#getMiddlewareForStore() {
const middleware = new Middleware();
this.#routerMiddleware.forEach((one) => {
debug_default("adding global middleware to route %s, %O", this.#pattern, one);
middleware.add(one);
});
this.#middleware.flat().forEach((one) => {
debug_default("adding named middleware to route %s, %O", this.#pattern, one);
middleware.add(one);
});
middleware.freeze();
return middleware;
}
toJSON() {
const pattern = this.#computePattern();
const matchers = this.#getMatchers();
return {
domain: this.#routeDomain,
pattern,
matchers,
tokens: parseRoute(pattern, matchers),
meta: {},
name: this.#name,
handler: this.#handler,
methods: this.#methods,
middleware: this.#getMiddlewareForStore(),
execute
};
}
};
var BriskRoute = class extends Macroable {
#pattern;
#globalMatchers;
#app;
#routerMiddleware;
route = null;
constructor(app, routerMiddleware, options) {
super();
this.#app = app;
this.#routerMiddleware = routerMiddleware;
this.#pattern = options.pattern;
this.#globalMatchers = options.globalMatchers;
}
setHandler(handler) {
this.route = new Route(this.#app, this.#routerMiddleware, {
pattern: this.#pattern,
globalMatchers: this.#globalMatchers,
methods: ["GET", "HEAD"],
handler
});
return this.route;
}
redirect(...args) {
const [identifier, params, options] = args;
function redirectsToRoute(ctx) {
const redirector = ctx.response.redirect();
if (options?.status) redirector.status(options.status);
return redirector.toRoute(identifier, params || ctx.params, options);
}
Object.defineProperty(redirectsToRoute, "listArgs", {
value: identifier,
writable: false
});
return this.setHandler(redirectsToRoute);
}
redirectToPath(url, options) {
function redirectsToPath(ctx) {
const redirector = ctx.response.redirect();
if (options?.status) redirector.status(options.status);
return redirector.toPath(url);
}
Object.defineProperty(redirectsToPath, "listArgs", {
value: url,
writable: false
});
return this.setHandler(redirectsToPath);
}
};
var RouteResource = class extends Macroable {
#resource;
#controller;
#shallow = false;
#globalMatchers;
#app;
#routerMiddleware;
#params = {};
#routesBaseName;
routes = [];
constructor(app, routerMiddleware, options) {
super();
this.#validateResourceName(options.resource);
this.#app = app;
this.#shallow = options.shallow;
this.#routerMiddleware = routerMiddleware;
this.#controller = options.controller;
this.#globalMatchers = options.globalMatchers;
this.#resource = this.#normalizeResourceName(options.resource);
this.#routesBaseName = this.#getRoutesBaseName();
this.#buildRoutes();
}
#normalizeResourceName(resource) {
return resource.replace(/^\//, "").replace(/\/$/, "");
}
#validateResourceName(resource) {
if (!resource || resource === "/") throw new RuntimeException(`Invalid resource name "${resource}"`);
}
#getRoutesBaseName() {
return this.#resource.split(".").map((token) => string.snakeCase(token)).join(".");
}
#createRoute(pattern, methods, action) {
const route = new Route(this.#app, this.#routerMiddleware, {
pattern,
methods,
handler: typeof this.#controller === "string" ? `${this.#controller}.${action}` : [this.#controller, action],
globalMatchers: this.#globalMatchers
});
route.as(`${this.#routesBaseName}.${action}`);
this.routes.push(route);
}
#getResourceId(resource) {
return `${string.snakeCase(string.singular(resource))}_id`;
}
#buildRoutes() {
const resources = this.#resource.split(".");
const mainResource = resources.pop();
this.#params[mainResource] = ":id";
const baseURI = `${resources.map((resource) => {
const paramName = `:${this.#getResourceId(resource)}`;
this.#params[resource] = paramName;
return `${resource}/${paramName}`;
}).join("/")}/${mainResource}`;
this.#createRoute(baseURI, ["GET", "HEAD"], "index");
this.#createRoute(`${baseURI}/create`, ["GET", "HEAD"], "create");
this.#createRoute(baseURI, ["POST"], "store");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["GET", "HEAD"], "show");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id/edit`, ["GET", "HEAD"], "edit");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["PUT", "PATCH"], "update");
this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["DELETE"], "destroy");
}
#filter(names, inverse) {
const actions = Array.isArray(names) ? names : [names];
return this.routes.filter((route) => {
const match = actions.find((name) => route.getName().endsWith(name));
return inverse ? !match : match;
});
}
only(names) {
this.#filter(names, true).forEach((route) => route.markAsDeleted());
return this;
}
except(names) {
this.#filter(names, false).forEach((route) => route.markAsDeleted());
return this;
}
apiOnly() {
return this.except(["create", "edit"]);
}
where(key, matcher) {
this.routes.forEach((route) => {
route.where(key, matcher);
});
return this;
}
tap(actions, callback) {
if (typeof actions === "function") {
this.routes.forEach((route) => {
if (!route.isDeleted()) actions(route);
});
return this;
}
this.#filter(actions, false).forEach((route) => {
if (!route.isDeleted()) callback(route);
});
return this;
}
params(resources) {
Object.keys(resources).forEach((resource) => {
const param = resources[resource];
const existingParam = this.#params[resource];
this.#params[resource] = `:${param}`;
this.routes.forEach((route) => {
route.setPattern(route.getPattern().replace(`${resource}/${existingParam}`, `${resource}/:${param}`));
});
});
return this;
}
use(actions, middleware) {
if (actions === "*") this.tap((route) => route.use(middleware));
else this.tap(actions, (route) => route.use(middleware));
return this;
}
middleware(actions, middleware) {
return this.use(actions, middleware);
}
as(name, normalizeName = true) {
name = normalizeName ? string.snakeCase(name) : name;
this.routes.forEach((route) => {
route.as(route.getName().replace(this.#routesBaseName, name), false);
});
this.#routesBaseName = name;
return this;
}
};
var RouteGroup = class RouteGroup extends Macroable {
#middleware = [];
constructor(routes) {
super();
this.routes = routes;
}
#shareMiddlewareStackWithRoutes(route) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#shareMiddlewareStackWithRoutes(child));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.getMiddleware().unshift(this.#middleware));
return;
}
if (route instanceof BriskRoute) {
route.route.getMiddleware().unshift(this.#middleware);
return;
}
route.getMiddleware().unshift(this.#middleware);
}
#updateRouteName(route, name) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#updateRouteName(child, name));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.as(name, true));
return;
}
if (route instanceof BriskRoute) {
route.route.as(name, true);
return;
}
route.as(name, true);
}
#setRoutePrefix(route, prefix) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#setRoutePrefix(child, prefix));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.prefix(prefix));
return;
}
if (route instanceof BriskRoute) {
route.route.prefix(prefix);
return;
}
route.prefix(prefix);
}
#updateRouteDomain(route, domain) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#updateRouteDomain(child, domain));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.domain(domain));
return;
}
if (route instanceof BriskRoute) {
route.route.domain(domain, false);
return;
}
route.domain(domain, false);
}
#updateRouteMatchers(route, param, matcher) {
if (route instanceof RouteGroup) {
route.routes.forEach((child) => this.#updateRouteMatchers(child, param, matcher));
return;
}
if (route instanceof RouteResource) {
route.routes.forEach((child) => child.where(param, matcher));
return;
}
if (route instanceof BriskRoute) {
route.route.where(param, matcher);
return;
}
route.where(param, matcher);
}
where(param, matcher) {
this.routes.forEach((route) => this.#updateRouteMatchers(route, param, matcher));
return this;
}
prefix(prefix) {
this.routes.forEach((route) => this.#setRoutePrefix(route, prefix));
return this;
}
domain(domain) {
this.routes.forEach((route) => this.#updateRouteDomain(route, domain));
return this;
}
as(name) {
this.routes.forEach((route) => this.#updateRouteName(route, name));
return this;
}
use(middleware) {
if (!this.#middleware.length) this.routes.forEach((route) => this.#shareMiddlewareStackWithRoutes(route));
if (Array.isArray(middleware)) for (let one of middleware) this.#middleware.push(one);
else this.#middleware.push(middleware);
return this;
}
middleware(middleware) {
return this.use(middleware);
}
};
const proxyCache = new Cache({ max: 200 });
function dropSlash(input) {
if (input === "/") return "/";
return `/${input.replace(/^\//, "").replace(/\/$/, "")}`;
}
function toRoutesJSON(routes) {
return routes.reduce((list, route) => {
if (route instanceof RouteGroup) {
list = list.concat(toRoutesJSON(route.routes));
return list;
}
if (route instanceof RouteResource) {
list = list.concat(toRoutesJSON(route.routes));
return list;
}
if (route instanceof BriskRoute) {
if (route.route && !route.route.isDeleted()) list.push(route.route.toJSON());
return list;
}
if (!route.isDeleted()) list.push(route.toJSON());
return list;
}, []);
}
function trustProxy(remoteAddress, proxyFn) {
if (proxyCache.has(remoteAddress)) return proxyCache.get(remoteAddress);
const result = proxyFn(remoteAddress, 0);
proxyCache.set(remoteAddress, result);
return result;
}
function parseRange(range, value) {
const parts = range.split("..");
const min = Number(parts[0]);
const max = Number(parts[1]);
if (parts.length === 1 && !Number.isNaN(min)) return { [min]: value };
if (Number.isNaN(min) || Number.isNaN(max)) return {};
if (min === max) return { [min]: value };
if (max < min) throw new InvalidArgumentsException(`Invalid range "${range}"`);
return [...Array(max - min + 1).keys()].reduce((result, step) => {
result[min + step] = value;
return result;
}, {});
}
function decodeComponentChar(highCharCode, lowCharCode) {
if (highCharCode === 50) {
if (lowCharCode === 53) return "%";
if (lowCharCode === 51) return "#";
if (lowCharCode === 52) return "$";
if (lowCharCode === 54) return "&";
if (lowCharCode === 66) return "+";
if (lowCharCode === 98) return "+";
if (lowCharCode === 67) return ",";
if (lowCharCode === 99) return ",";
if (lowCharCode === 70) return "/";
if (lowCharCode === 102) return "/";
return null;
}
if (highCharCode === 51) {
if (lowCharCode === 65) return ":";
if (lowCharCode === 97) return ":";
if (lowCharCode === 66) return ";";
if (lowCharCode === 98) return ";";
if (lowCharCode === 68) return "=";
if (lowCharCode === 100) return "=";
if (lowCharCode === 70) return "?";
if (lowCharCode === 102) return "?";
return null;
}
if (highCharCode === 52 && lowCharCode === 48) return "@";
return null;
}
function safeDecodeURI(path, useSemicolonDelimiter) {
let shouldDecode = false;
let shouldDecodeParam = false;
let querystring = "";
for (let i = 1; i < path.length; i++) {
const charCode = path.charCodeAt(i);
if (charCode === 37) {
const highCharCode = path.charCodeAt(i + 1);
const lowCharCode = path.charCodeAt(i + 2);
if (decodeComponentChar(highCharCode, lowCharCode) === null) shouldDecode = true;
else {
shouldDecodeParam = true;
if (highCharCode === 50 && lowCharCode === 53) {
shouldDecode = true;
path = path.slice(0, i + 1) + "25" + path.slice(i + 1);
i += 2;
}
i += 2;
}
} else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
querystring = path.slice(i + 1);
path = path.slice(0, i);
break;
}
}
return {
pathname: shouldDecode ? decodeURI(path) : path,
query: querystring,
shouldDecodeParam
};
}
function parseRoute(pattern, matchers) {
return matchit.parse(pattern, matchers);
}
function createSignedURL(identifier, tokens, searchParamsStringifier, encryption, params, options) {
const signature = encryption.getMessageVerifier().sign(createURL(identifier, tokens, searchParamsStringifier, params, {
...options,
prefixUrl: void 0
}), options?.expiresIn, options?.purpose);
return createURL(identifier, tokens, searchParamsStringifier, params, {
...options,
qs: {
...options?.qs,
signature
}
});
}
function matchRoute(url, patterns) {
const tokensBucket = patterns.map((pattern) => parseRoute(pattern));
const match = matchit.match(url, tokensBucket);
if (!match.length) return null;
return matchit.exec(url, match);
}
function serializeCookie(key, value, options) {
let expires;
let maxAge;
if (options) {
expires = typeof options.expires === "function" ? options.expires() : options.expires;
maxAge = options.maxAge ? string.seconds.parse(options.maxAge) : void 0;
}
return serialize(key, value, {
...options,
maxAge,
expires
});
}
async function middlewareInfo(middleware) {
if (typeof middleware === "function") return {
type: "closure",
name: middleware.name || "closure"
};
if ("args" in middleware) return {
type: "named",
name: middleware.name,
args: middleware.args,
...await parseBindingReference([middleware.reference])
};
return {
type: "global",
name: middleware.name,
...await parseBindingReference([middleware.reference])
};
}
async function routeInfo(route) {
return "reference" in route.handler ? {
type: "controller",
...await parseBindingReference(route.handler.reference)
} : {
type: "closure",
name: route.handler.name || "closure",
args: "listArgs" in route.handler ? String(route.handler.listArgs) : void 0
};
}
function appendQueryString(uri, queryString, qsParser) {
const { query, pathname } = safeDecodeURI(uri, false);
const mergedQueryString = qsParser.stringify(Object.assign(qsParser.parse(query), queryString));
return mergedQueryString ? `${pathname}?${mergedQueryString}` : pathname;
}
export { canWriteResponseBody as C, __require as D, __exportAll as E, __toESM as O, tracing_channels_exports as S, __commonJSMin as T, Route as _, middlewareInfo as a, httpRequest as b, routeInfo as c, safeDecodeURI as d, toRoutesJSON as f, BriskRoute as g, RouteResource as h, matchRoute as i, serializeCookie as l, RouteGroup as m, createSignedURL as n, mime as o, trustProxy as p, encodeUrl as r, parseRoute as s, appendQueryString as t, parseRange as u, httpExceptionHandler as v, debug_default as w, httpResponseSerializer as x, httpMiddleware as y };
import { n as findRoute, t as createURL } from "./helpers-C_2HouOe.js";
function createUrlBuilder(routesLoader, searchParamsStringifier) {
let domainsList;
let domainsRoutes;
function createUrlForRoute(identifier, params, options, method) {
if (!domainsRoutes) {
domainsRoutes = typeof routesLoader === "function" ? routesLoader() : routesLoader;
if (!domainsRoutes || typeof domainsRoutes !== "object") throw new Error(`Cannot construct routes. Expected the value to be an object, instead received ${typeof domainsRoutes}`);
if (!domainsList) domainsList = Object.keys(domainsRoutes).filter((domain$1) => domain$1 !== "root");
}
const domain = domainsList.find((name) => identifier.startsWith(`${name}@`));
const routeIdentifier = domain ? identifier.replace(/* @__PURE__ */ new RegExp(`^${domain}@`), "") : identifier;
const route = findRoute(domainsRoutes, routeIdentifier, domain, method, true);
if (!route) {
if (method) throw new Error(`Cannot lookup route "${routeIdentifier}" for method "${method}"`);
throw new Error(`Cannot lookup route "${routeIdentifier}"`);
}
return createURL(route.name ?? route.pattern, route.tokens, searchParamsStringifier, params, options);
}
const urlFor = function route(...[identifier, params, options]) {
return createUrlForRoute(identifier, params, options);
};
urlFor.get = function urlForMethodGet(...[identifier, params, options]) {
const method = "GET";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.post = function urlForMethodPost(...[identifier, params, options]) {
const method = "POST";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.put = function urlForMethodPut(...[identifier, params, options]) {
const method = "PUT";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.patch = function urlForMethodPatch(...[identifier, params, options]) {
const method = "PATCH";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.delete = function urlForMethodDelete(...[identifier, params, options]) {
const method = "DELETE";
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
urlFor.method = function urlForCustomMethod(method, ...[identifier, params, options]) {
const url = createUrlForRoute(identifier, params, options, method);
return {
url,
method,
toString() {
return url;
},
form: {
action: url,
method
}
};
};
return urlFor;
}
export { createUrlBuilder as t };