tezx 1.0.53 → 1.0.55

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/adapter/bun.js CHANGED
@@ -18,7 +18,9 @@ export function bunAdapter(TezX) {
18
18
  },
19
19
  };
20
20
  const response = await TezX.serve(req, options);
21
- if (typeof response?.websocket == "function" && response.ctx instanceof Context && response.ctx.wsProtocol) {
21
+ if (typeof response?.websocket == "function" &&
22
+ response.ctx instanceof Context &&
23
+ response.ctx.wsProtocol) {
22
24
  let websocket = response?.websocket(response?.ctx);
23
25
  const upgradeSuccess = server.upgrade(req, {
24
26
  data: { ...websocket },
@@ -54,7 +56,7 @@ export function bunAdapter(TezX) {
54
56
  drain(ws) {
55
57
  return ws.data?.drain?.(ws);
56
58
  },
57
- }
59
+ },
58
60
  });
59
61
  GlobalConfig.server = server;
60
62
  const protocol = "\x1b[1;34mhttp\x1b[0m";
package/adapter/node.js CHANGED
@@ -25,7 +25,9 @@ export function nodeAdapter(TezX) {
25
25
  connInfo: address,
26
26
  };
27
27
  const response = await TezX.serve(req, options);
28
- if (typeof response?.websocket == "function" && response.ctx instanceof Context && response.ctx.wsProtocol) {
28
+ if (typeof response?.websocket == "function" &&
29
+ response.ctx instanceof Context &&
30
+ response.ctx.wsProtocol) {
29
31
  let ctx = response.ctx;
30
32
  response.websocket(ctx, server);
31
33
  res.end();
@@ -21,7 +21,9 @@ function bunAdapter(TezX) {
21
21
  },
22
22
  };
23
23
  const response = await TezX.serve(req, options);
24
- if (typeof response?.websocket == "function" && response.ctx instanceof context_js_1.Context && response.ctx.wsProtocol) {
24
+ if (typeof response?.websocket == "function" &&
25
+ response.ctx instanceof context_js_1.Context &&
26
+ response.ctx.wsProtocol) {
25
27
  let websocket = response?.websocket(response?.ctx);
26
28
  const upgradeSuccess = server.upgrade(req, {
27
29
  data: { ...websocket },
@@ -57,7 +59,7 @@ function bunAdapter(TezX) {
57
59
  drain(ws) {
58
60
  return ws.data?.drain?.(ws);
59
61
  },
60
- }
62
+ },
61
63
  });
62
64
  config_js_1.GlobalConfig.server = server;
63
65
  const protocol = "\x1b[1;34mhttp\x1b[0m";
@@ -27,7 +27,9 @@ function nodeAdapter(TezX) {
27
27
  connInfo: address,
28
28
  };
29
29
  const response = await TezX.serve(req, options);
30
- if (typeof response?.websocket == "function" && response.ctx instanceof context_js_1.Context && response.ctx.wsProtocol) {
30
+ if (typeof response?.websocket == "function" &&
31
+ response.ctx instanceof context_js_1.Context &&
32
+ response.ctx.wsProtocol) {
31
33
  let ctx = response.ctx;
32
34
  response.websocket(ctx, server);
33
35
  res.end();
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Context = exports.httpStatusMap = void 0;
4
4
  const state_js_1 = require("../utils/state.js");
5
5
  const staticFile_js_1 = require("../utils/staticFile.js");
6
+ const url_js_1 = require("../utils/url.js");
7
+ const config_js_1 = require("./config.js");
6
8
  const environment_js_1 = require("./environment.js");
7
9
  const header_js_1 = require("./header.js");
8
10
  const request_js_1 = require("./request.js");
@@ -83,13 +85,31 @@ class Context {
83
85
  #params = {};
84
86
  resBody;
85
87
  #body;
88
+ #urlRef;
89
+ #requestHeaders;
86
90
  #options;
87
91
  constructor(req, options) {
88
92
  this.#options = options;
89
93
  this.#rawRequest = req;
90
94
  this.method = req?.method?.toUpperCase();
91
- this.pathname = this.req.urlRef.pathname;
92
- this.url = this.req.url;
95
+ this.#requestHeaders = new header_js_1.HeadersParser(req?.headers);
96
+ if (environment_js_1.EnvironmentDetector.getEnvironment == "node" ||
97
+ config_js_1.GlobalConfig.adapter == "node") {
98
+ let encrypted = req?.socket?.encrypted;
99
+ const protocol = typeof encrypted === "boolean"
100
+ ? encrypted
101
+ ? "https"
102
+ : "http"
103
+ : "http";
104
+ const host = environment_js_1.EnvironmentDetector.getHost(this.#requestHeaders);
105
+ const path = req.url || "/";
106
+ this.url = `${protocol}://${host}${path}`;
107
+ }
108
+ else {
109
+ this.url = req.url;
110
+ }
111
+ this.#urlRef = (0, url_js_1.urlParse)(this.url);
112
+ this.pathname = this.#urlRef.pathname;
93
113
  }
94
114
  header(key, value, options) {
95
115
  let append = options?.append;
@@ -102,7 +122,7 @@ class Context {
102
122
  return this;
103
123
  }
104
124
  get cookies() {
105
- const c = this.req.headers.getAll("cookie");
125
+ const c = this.#requestHeaders.getAll("cookie");
106
126
  let cookies = {};
107
127
  if (Array.isArray(c) && c.length != 0) {
108
128
  const cookieHeader = c.join("; ").split(";");
@@ -395,7 +415,13 @@ class Context {
395
415
  return response;
396
416
  }
397
417
  get req() {
398
- return new request_js_1.Request(this.#rawRequest, this.params, this.#options);
418
+ return new request_js_1.Request({
419
+ headers: this.#requestHeaders,
420
+ req: this.#rawRequest,
421
+ urlRef: this.#urlRef,
422
+ options: this.#options,
423
+ params: this.#params,
424
+ });
399
425
  }
400
426
  set params(params) {
401
427
  this.#params = params;
@@ -2,20 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Request = void 0;
4
4
  const formData_js_1 = require("../utils/formData.js");
5
- const url_js_1 = require("../utils/url.js");
6
- const config_js_1 = require("./config.js");
7
- const environment_js_1 = require("./environment.js");
8
5
  const header_js_1 = require("./header.js");
9
6
  class Request {
10
7
  #headers = new header_js_1.HeadersParser();
11
8
  url;
12
9
  method;
13
10
  urlRef = {
14
- hash: undefined,
15
11
  protocol: undefined,
16
12
  origin: undefined,
17
- username: undefined,
18
- password: undefined,
19
13
  hostname: undefined,
20
14
  port: undefined,
21
15
  href: undefined,
@@ -26,29 +20,15 @@ class Request {
26
20
  rawRequest;
27
21
  params = {};
28
22
  remoteAddress = {};
29
- constructor(req, params, options) {
23
+ constructor({ headers, params, req, options, urlRef, }) {
30
24
  this.remoteAddress = options?.connInfo?.remoteAddr;
31
- this.#headers = new header_js_1.HeadersParser(req?.headers);
25
+ this.#headers = headers;
26
+ this.url = urlRef.href || "";
27
+ this.urlRef = urlRef;
32
28
  this.method = req?.method?.toUpperCase();
33
29
  this.params = params;
34
30
  this.rawRequest = req;
35
- if (environment_js_1.EnvironmentDetector.getEnvironment == "node" ||
36
- config_js_1.GlobalConfig.adapter == "node") {
37
- let encrypted = req?.socket?.encrypted;
38
- const protocol = typeof encrypted === "boolean"
39
- ? encrypted
40
- ? "https"
41
- : "http"
42
- : "http";
43
- const host = environment_js_1.EnvironmentDetector.getHost(this.#headers);
44
- const path = req.url || "/";
45
- this.url = `${protocol}://${host}${path}`;
46
- }
47
- else {
48
- this.url = req.url;
49
- }
50
- this.urlRef = (0, url_js_1.urlParse)(this.url);
51
- this.query = this.urlRef.query;
31
+ this.query = urlRef.query;
52
32
  }
53
33
  get headers() {
54
34
  let requestHeaders = this.#headers;
@@ -91,7 +91,7 @@ class TezX extends router_js_1.Router {
91
91
  if (response instanceof Response) {
92
92
  return response;
93
93
  }
94
- if (typeof response == 'function' && ctx.wsProtocol) {
94
+ if (typeof response == "function" && ctx.wsProtocol) {
95
95
  return response;
96
96
  }
97
97
  if (!response && !ctx.body) {
package/cjs/index.js CHANGED
@@ -7,4 +7,4 @@ var server_js_1 = require("./core/server.js");
7
7
  Object.defineProperty(exports, "TezX", { enumerable: true, get: function () { return server_js_1.TezX; } });
8
8
  var params_js_1 = require("./utils/params.js");
9
9
  Object.defineProperty(exports, "useParams", { enumerable: true, get: function () { return params_js_1.useParams; } });
10
- exports.version = "1.0.53";
10
+ exports.version = "1.0.55";
package/cjs/utils/url.js CHANGED
@@ -10,50 +10,21 @@ function sanitizePathSplit(basePath, path) {
10
10
  return parts;
11
11
  }
12
12
  function urlParse(url) {
13
- const urlPattern = /^(?:(\w+):\/\/)?(?:([^:@]+)?(?::([^@]+))?@)?([^:/?#]+)?(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;
14
- let matches = url.match(urlPattern);
15
- if (!matches) {
16
- href: url;
17
- }
18
- const [_, protocol, username, password, hostname, port, path, queryString, hash,] = matches;
19
- let origin = hostname;
20
- if (protocol) {
21
- origin = protocol + "://" + hostname;
22
- }
23
- if (port) {
24
- origin = origin + ":" + port;
25
- }
26
- let p = path;
27
- if (p?.endsWith("/"))
28
- p.slice(0, -1);
29
- function query() {
30
- if (queryString) {
31
- const queryPart = decodeURIComponent(queryString);
32
- const keyValuePairs = queryPart.split("&");
33
- const paramsObj = keyValuePairs?.map((keyValue) => {
34
- const [key, value] = keyValue.split("=");
35
- return {
36
- [key]: value,
37
- };
38
- });
39
- return paramsObj.reduce(function (total, value) {
40
- return { ...total, ...value };
41
- }, {});
42
- }
43
- else {
44
- return {};
45
- }
13
+ let u = URL.parse(url);
14
+ let query = {};
15
+ if (u?.search) {
16
+ const queryPart = decodeURIComponent(u?.search);
17
+ new URLSearchParams(queryPart).forEach((value, key) => {
18
+ query[key] = value;
19
+ });
46
20
  }
47
21
  return {
48
- pathname: p,
49
- hash,
50
- protocol,
51
- origin,
52
- username,
53
- password,
54
- hostname,
22
+ pathname: u?.pathname,
23
+ query: query,
24
+ protocol: u?.protocol,
25
+ origin: u?.origin,
26
+ hostname: u?.hostname,
55
27
  href: url,
56
- port,
57
- query: query(),
28
+ port: u?.port,
58
29
  };
59
30
  }
package/cjs/ws/deno.js CHANGED
@@ -6,7 +6,7 @@ class DenoTransport {
6
6
  const { socket, response } = Deno.upgradeWebSocket(ctx.req.rawRequest, {
7
7
  protocols: options.protocols,
8
8
  idleTimeout: options.idleTimeout,
9
- headers: {}
9
+ headers: {},
10
10
  });
11
11
  this.setupHandlers(socket, ctx, event, options);
12
12
  return response;
package/cjs/ws/index.js CHANGED
@@ -8,22 +8,20 @@ function upgradeWebSocket(callback, options = {}) {
8
8
  const { onUpgradeError = (error, ctx) => {
9
9
  ctx.setStatus = 401;
10
10
  return ctx.text(error.message);
11
- }, protocols = [], idleTimeout = 30000, perMessageDeflate, maxPayload = 1048576 } = options;
11
+ }, protocols = [], idleTimeout = 30000, perMessageDeflate, maxPayload = 1048576, } = options;
12
12
  return async (ctx, next) => {
13
13
  const upgrade = ctx.req.headers.get("upgrade")?.toLowerCase();
14
14
  const connection = ctx.req.headers.get("connection")?.toLowerCase();
15
15
  const key = ctx.req.headers.get("sec-websocket-key");
16
- if (upgrade !== "websocket" ||
17
- !connection?.includes("upgrade") ||
18
- !key) {
16
+ if (upgrade !== "websocket" || !connection?.includes("upgrade") || !key) {
19
17
  if (next) {
20
- ctx.body = { error: '401 Bad Request: Invalid WebSocket headers' };
18
+ ctx.body = { error: "401 Bad Request: Invalid WebSocket headers" };
21
19
  return next();
22
20
  }
23
21
  ctx.setStatus = 401;
24
22
  return onUpgradeError(new Error("401 Bad Request: Invalid WebSocket headers"), ctx);
25
23
  }
26
- ctx.wsProtocol = ctx.req.urlRef.protocol === 'https:' ? 'wss' : 'ws';
24
+ ctx.wsProtocol = ctx.req.urlRef.protocol === "https:" ? "wss" : "ws";
27
25
  try {
28
26
  const env = environment_js_1.EnvironmentDetector.getEnvironment;
29
27
  if (!callback) {
@@ -31,17 +29,17 @@ function upgradeWebSocket(callback, options = {}) {
31
29
  }
32
30
  let websocketCallback = callback(ctx);
33
31
  switch (env) {
34
- case 'deno':
32
+ case "deno":
35
33
  return new deno_js_1.DenoTransport().upgrade(ctx, websocketCallback, {
36
34
  idleTimeout,
37
- protocols
35
+ protocols,
38
36
  });
39
- case 'bun':
37
+ case "bun":
40
38
  return callback;
41
- case 'node':
39
+ case "node":
42
40
  return new node_js_1.NodeTransport().upgrade(ctx, websocketCallback, {
43
41
  maxPayload,
44
- perMessageDeflate
42
+ perMessageDeflate,
45
43
  });
46
44
  default:
47
45
  throw new Error("Unsupported environment for WebSocket upgrade.");
package/cjs/ws/node.js CHANGED
@@ -4,28 +4,28 @@ exports.NodeTransport = void 0;
4
4
  class NodeTransport {
5
5
  wss;
6
6
  async upgrade(ctx, event, options) {
7
- let { WebSocketServer } = await Promise.resolve().then(() => require('ws'));
7
+ let { WebSocketServer } = await Promise.resolve().then(() => require("ws"));
8
8
  return (ctx, server) => {
9
9
  this.wss = new WebSocketServer({
10
10
  noServer: true,
11
11
  maxPayload: options.maxPayload ?? 1048576,
12
12
  perMessageDeflate: options.perMessageDeflate ?? false,
13
13
  });
14
- server.on('upgrade', (request, socket, head) => {
14
+ server.on("upgrade", (request, socket, head) => {
15
15
  this.wss?.handleUpgrade(request, socket, head, (ws) => {
16
- this.wss?.emit('connection', ws, request);
16
+ this.wss?.emit("connection", ws, request);
17
17
  this.setupHandlers(ws, event, options);
18
18
  });
19
19
  });
20
20
  };
21
21
  }
22
22
  setupHandlers(ws, event, options) {
23
- ws.on('open', () => event.open?.(ws));
24
- ws.on('message', (data) => event.message?.(ws, data));
25
- ws.on('close', (code, reason) => event.close?.(ws, { code, reason }));
26
- ws.on('error', (err) => event.error?.(ws, err));
27
- ws.on('ping', (data) => event.ping?.(ws, data));
28
- ws.on('pong', (data) => event.pong?.(ws, data));
23
+ ws.on("open", () => event.open?.(ws));
24
+ ws.on("message", (data) => event.message?.(ws, data));
25
+ ws.on("close", (code, reason) => event.close?.(ws, { code, reason }));
26
+ ws.on("error", (err) => event.error?.(ws, err));
27
+ ws.on("ping", (data) => event.ping?.(ws, data));
28
+ ws.on("pong", (data) => event.pong?.(ws, data));
29
29
  }
30
30
  }
31
31
  exports.NodeTransport = NodeTransport;
package/core/context.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { State } from "../utils/state.js";
2
2
  import { defaultMimeType, mimeTypes } from "../utils/staticFile.js";
3
+ import { urlParse } from "../utils/url.js";
4
+ import { GlobalConfig } from "./config.js";
3
5
  import { EnvironmentDetector } from "./environment.js";
4
6
  import { HeadersParser } from "./header.js";
5
7
  import { Request } from "./request.js";
@@ -80,13 +82,31 @@ export class Context {
80
82
  #params = {};
81
83
  resBody;
82
84
  #body;
85
+ #urlRef;
86
+ #requestHeaders;
83
87
  #options;
84
88
  constructor(req, options) {
85
89
  this.#options = options;
86
90
  this.#rawRequest = req;
87
91
  this.method = req?.method?.toUpperCase();
88
- this.pathname = this.req.urlRef.pathname;
89
- this.url = this.req.url;
92
+ this.#requestHeaders = new HeadersParser(req?.headers);
93
+ if (EnvironmentDetector.getEnvironment == "node" ||
94
+ GlobalConfig.adapter == "node") {
95
+ let encrypted = req?.socket?.encrypted;
96
+ const protocol = typeof encrypted === "boolean"
97
+ ? encrypted
98
+ ? "https"
99
+ : "http"
100
+ : "http";
101
+ const host = EnvironmentDetector.getHost(this.#requestHeaders);
102
+ const path = req.url || "/";
103
+ this.url = `${protocol}://${host}${path}`;
104
+ }
105
+ else {
106
+ this.url = req.url;
107
+ }
108
+ this.#urlRef = urlParse(this.url);
109
+ this.pathname = this.#urlRef.pathname;
90
110
  }
91
111
  header(key, value, options) {
92
112
  let append = options?.append;
@@ -99,7 +119,7 @@ export class Context {
99
119
  return this;
100
120
  }
101
121
  get cookies() {
102
- const c = this.req.headers.getAll("cookie");
122
+ const c = this.#requestHeaders.getAll("cookie");
103
123
  let cookies = {};
104
124
  if (Array.isArray(c) && c.length != 0) {
105
125
  const cookieHeader = c.join("; ").split(";");
@@ -392,7 +412,13 @@ export class Context {
392
412
  return response;
393
413
  }
394
414
  get req() {
395
- return new Request(this.#rawRequest, this.params, this.#options);
415
+ return new Request({
416
+ headers: this.#requestHeaders,
417
+ req: this.#rawRequest,
418
+ urlRef: this.#urlRef,
419
+ options: this.#options,
420
+ params: this.#params,
421
+ });
396
422
  }
397
423
  set params(params) {
398
424
  this.#params = params;
package/core/request.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { UrlRef } from "../utils/url.js";
2
+ import { HeadersParser } from "./header.js";
2
3
  import { ServeOptions } from "./server.js";
3
4
  export type FormDataOptions = {
4
5
  maxSize?: number;
@@ -56,7 +57,13 @@ export declare class Request {
56
57
  * ```
57
58
  */
58
59
  remoteAddress: AddressType;
59
- constructor(req: any, params: Record<string, any>, options: ServeOptions);
60
+ constructor({ headers, params, req, options, urlRef, }: {
61
+ req: any;
62
+ params: Record<string, any>;
63
+ headers: HeadersParser;
64
+ urlRef: UrlRef;
65
+ options: ServeOptions;
66
+ });
60
67
  get headers(): {
61
68
  /**
62
69
  * Retrieves the first value of a specific header.
package/core/request.js CHANGED
@@ -1,18 +1,12 @@
1
1
  import { parseJsonBody, parseMultipartBody, parseTextBody, parseUrlEncodedBody, } from "../utils/formData.js";
2
- import { urlParse } from "../utils/url.js";
3
- import { GlobalConfig } from "./config.js";
4
- import { EnvironmentDetector } from "./environment.js";
5
2
  import { HeadersParser } from "./header.js";
6
3
  export class Request {
7
4
  #headers = new HeadersParser();
8
5
  url;
9
6
  method;
10
7
  urlRef = {
11
- hash: undefined,
12
8
  protocol: undefined,
13
9
  origin: undefined,
14
- username: undefined,
15
- password: undefined,
16
10
  hostname: undefined,
17
11
  port: undefined,
18
12
  href: undefined,
@@ -23,29 +17,15 @@ export class Request {
23
17
  rawRequest;
24
18
  params = {};
25
19
  remoteAddress = {};
26
- constructor(req, params, options) {
20
+ constructor({ headers, params, req, options, urlRef, }) {
27
21
  this.remoteAddress = options?.connInfo?.remoteAddr;
28
- this.#headers = new HeadersParser(req?.headers);
22
+ this.#headers = headers;
23
+ this.url = urlRef.href || "";
24
+ this.urlRef = urlRef;
29
25
  this.method = req?.method?.toUpperCase();
30
26
  this.params = params;
31
27
  this.rawRequest = req;
32
- if (EnvironmentDetector.getEnvironment == "node" ||
33
- GlobalConfig.adapter == "node") {
34
- let encrypted = req?.socket?.encrypted;
35
- const protocol = typeof encrypted === "boolean"
36
- ? encrypted
37
- ? "https"
38
- : "http"
39
- : "http";
40
- const host = EnvironmentDetector.getHost(this.#headers);
41
- const path = req.url || "/";
42
- this.url = `${protocol}://${host}${path}`;
43
- }
44
- else {
45
- this.url = req.url;
46
- }
47
- this.urlRef = urlParse(this.url);
48
- this.query = this.urlRef.query;
28
+ this.query = urlRef.query;
49
29
  }
50
30
  get headers() {
51
31
  let requestHeaders = this.#headers;
package/core/server.js CHANGED
@@ -88,7 +88,7 @@ export class TezX extends Router {
88
88
  if (response instanceof Response) {
89
89
  return response;
90
90
  }
91
- if (typeof response == 'function' && ctx.wsProtocol) {
91
+ if (typeof response == "function" && ctx.wsProtocol) {
92
92
  return response;
93
93
  }
94
94
  if (!response && !ctx.body) {
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Router } from "./core/router.js";
2
- export type { Callback, ctx as Context, Middleware, NextCallback, RouterConfig, StaticServeOption } from "./core/router.js";
2
+ export type { Callback, ctx as Context, Middleware, NextCallback, RouterConfig, StaticServeOption, } from "./core/router.js";
3
3
  export type { CookieOptions, ResponseHeaders } from "./core/context.js";
4
4
  export type { AddressType, ConnAddress, FormDataOptions, HTTPMethod, } from "./core/request.js";
5
5
  export { TezX } from "./core/server.js";
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Router } from "./core/router.js";
2
2
  export { TezX } from "./core/server.js";
3
3
  export { useParams } from "./utils/params.js";
4
- export let version = "1.0.53";
4
+ export let version = "1.0.55";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tezx",
3
- "version": "1.0.53",
3
+ "version": "1.0.55",
4
4
  "description": "TezX is a high-performance, lightweight JavaScript framework designed for speed, scalability, and flexibility. It enables efficient routing, middleware management, and static file serving with minimal configuration. Fully compatible with Node.js, Deno, and Bun.",
5
5
  "main": "cjs/index.js",
6
6
  "module": "index.js",
package/utils/url.d.ts CHANGED
@@ -1,9 +1,6 @@
1
1
  export type UrlRef = {
2
- hash: string | undefined;
3
2
  protocol: string | undefined;
4
3
  origin: string | undefined;
5
- username: string | undefined;
6
- password: string | undefined;
7
4
  hostname: string | undefined;
8
5
  port: string | undefined;
9
6
  href: string | undefined;
package/utils/url.js CHANGED
@@ -6,50 +6,21 @@ export function sanitizePathSplit(basePath, path) {
6
6
  return parts;
7
7
  }
8
8
  export function urlParse(url) {
9
- const urlPattern = /^(?:(\w+):\/\/)?(?:([^:@]+)?(?::([^@]+))?@)?([^:/?#]+)?(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;
10
- let matches = url.match(urlPattern);
11
- if (!matches) {
12
- href: url;
13
- }
14
- const [_, protocol, username, password, hostname, port, path, queryString, hash,] = matches;
15
- let origin = hostname;
16
- if (protocol) {
17
- origin = protocol + "://" + hostname;
18
- }
19
- if (port) {
20
- origin = origin + ":" + port;
21
- }
22
- let p = path;
23
- if (p?.endsWith("/"))
24
- p.slice(0, -1);
25
- function query() {
26
- if (queryString) {
27
- const queryPart = decodeURIComponent(queryString);
28
- const keyValuePairs = queryPart.split("&");
29
- const paramsObj = keyValuePairs?.map((keyValue) => {
30
- const [key, value] = keyValue.split("=");
31
- return {
32
- [key]: value,
33
- };
34
- });
35
- return paramsObj.reduce(function (total, value) {
36
- return { ...total, ...value };
37
- }, {});
38
- }
39
- else {
40
- return {};
41
- }
9
+ let u = URL.parse(url);
10
+ let query = {};
11
+ if (u?.search) {
12
+ const queryPart = decodeURIComponent(u?.search);
13
+ new URLSearchParams(queryPart).forEach((value, key) => {
14
+ query[key] = value;
15
+ });
42
16
  }
43
17
  return {
44
- pathname: p,
45
- hash,
46
- protocol,
47
- origin,
48
- username,
49
- password,
50
- hostname,
18
+ pathname: u?.pathname,
19
+ query: query,
20
+ protocol: u?.protocol,
21
+ origin: u?.origin,
22
+ hostname: u?.hostname,
51
23
  href: url,
52
- port,
53
- query: query(),
24
+ port: u?.port,
54
25
  };
55
26
  }
package/ws/deno.js CHANGED
@@ -3,7 +3,7 @@ export class DenoTransport {
3
3
  const { socket, response } = Deno.upgradeWebSocket(ctx.req.rawRequest, {
4
4
  protocols: options.protocols,
5
5
  idleTimeout: options.idleTimeout,
6
- headers: {}
6
+ headers: {},
7
7
  });
8
8
  this.setupHandlers(socket, ctx, event, options);
9
9
  return response;
package/ws/index.js CHANGED
@@ -5,22 +5,20 @@ export function upgradeWebSocket(callback, options = {}) {
5
5
  const { onUpgradeError = (error, ctx) => {
6
6
  ctx.setStatus = 401;
7
7
  return ctx.text(error.message);
8
- }, protocols = [], idleTimeout = 30000, perMessageDeflate, maxPayload = 1048576 } = options;
8
+ }, protocols = [], idleTimeout = 30000, perMessageDeflate, maxPayload = 1048576, } = options;
9
9
  return async (ctx, next) => {
10
10
  const upgrade = ctx.req.headers.get("upgrade")?.toLowerCase();
11
11
  const connection = ctx.req.headers.get("connection")?.toLowerCase();
12
12
  const key = ctx.req.headers.get("sec-websocket-key");
13
- if (upgrade !== "websocket" ||
14
- !connection?.includes("upgrade") ||
15
- !key) {
13
+ if (upgrade !== "websocket" || !connection?.includes("upgrade") || !key) {
16
14
  if (next) {
17
- ctx.body = { error: '401 Bad Request: Invalid WebSocket headers' };
15
+ ctx.body = { error: "401 Bad Request: Invalid WebSocket headers" };
18
16
  return next();
19
17
  }
20
18
  ctx.setStatus = 401;
21
19
  return onUpgradeError(new Error("401 Bad Request: Invalid WebSocket headers"), ctx);
22
20
  }
23
- ctx.wsProtocol = ctx.req.urlRef.protocol === 'https:' ? 'wss' : 'ws';
21
+ ctx.wsProtocol = ctx.req.urlRef.protocol === "https:" ? "wss" : "ws";
24
22
  try {
25
23
  const env = EnvironmentDetector.getEnvironment;
26
24
  if (!callback) {
@@ -28,17 +26,17 @@ export function upgradeWebSocket(callback, options = {}) {
28
26
  }
29
27
  let websocketCallback = callback(ctx);
30
28
  switch (env) {
31
- case 'deno':
29
+ case "deno":
32
30
  return new DenoTransport().upgrade(ctx, websocketCallback, {
33
31
  idleTimeout,
34
- protocols
32
+ protocols,
35
33
  });
36
- case 'bun':
34
+ case "bun":
37
35
  return callback;
38
- case 'node':
36
+ case "node":
39
37
  return new NodeTransport().upgrade(ctx, websocketCallback, {
40
38
  maxPayload,
41
- perMessageDeflate
39
+ perMessageDeflate,
42
40
  });
43
41
  default:
44
42
  throw new Error("Unsupported environment for WebSocket upgrade.");
package/ws/node.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Context } from '../index.js';
2
- import { WebSocketEvent, WebSocketOptions } from './index.js';
1
+ import { Context } from "../index.js";
2
+ import { WebSocketEvent, WebSocketOptions } from "./index.js";
3
3
  export declare class NodeTransport {
4
4
  private wss?;
5
5
  upgrade(ctx: Context, event: WebSocketEvent, options: WebSocketOptions): Promise<(ctx: Context, server: any) => void>;
package/ws/node.js CHANGED
@@ -1,27 +1,27 @@
1
1
  export class NodeTransport {
2
2
  wss;
3
3
  async upgrade(ctx, event, options) {
4
- let { WebSocketServer } = await import('ws');
4
+ let { WebSocketServer } = await import("ws");
5
5
  return (ctx, server) => {
6
6
  this.wss = new WebSocketServer({
7
7
  noServer: true,
8
8
  maxPayload: options.maxPayload ?? 1048576,
9
9
  perMessageDeflate: options.perMessageDeflate ?? false,
10
10
  });
11
- server.on('upgrade', (request, socket, head) => {
11
+ server.on("upgrade", (request, socket, head) => {
12
12
  this.wss?.handleUpgrade(request, socket, head, (ws) => {
13
- this.wss?.emit('connection', ws, request);
13
+ this.wss?.emit("connection", ws, request);
14
14
  this.setupHandlers(ws, event, options);
15
15
  });
16
16
  });
17
17
  };
18
18
  }
19
19
  setupHandlers(ws, event, options) {
20
- ws.on('open', () => event.open?.(ws));
21
- ws.on('message', (data) => event.message?.(ws, data));
22
- ws.on('close', (code, reason) => event.close?.(ws, { code, reason }));
23
- ws.on('error', (err) => event.error?.(ws, err));
24
- ws.on('ping', (data) => event.ping?.(ws, data));
25
- ws.on('pong', (data) => event.pong?.(ws, data));
20
+ ws.on("open", () => event.open?.(ws));
21
+ ws.on("message", (data) => event.message?.(ws, data));
22
+ ws.on("close", (code, reason) => event.close?.(ws, { code, reason }));
23
+ ws.on("error", (err) => event.error?.(ws, err));
24
+ ws.on("ping", (data) => event.ping?.(ws, data));
25
+ ws.on("pong", (data) => event.pong?.(ws, data));
26
26
  }
27
27
  }