lien 4.0.0 → 5.0.1

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/example/index.js CHANGED
@@ -1,26 +1,24 @@
1
- "use strict";
2
-
3
- var Lien = require("../lib");
1
+ import Lien from "../lib/index.js";
4
2
 
5
3
  // Init lien server
6
- var server = new Lien({
4
+ const server = new Lien({
7
5
  port: 9000,
8
- public: __dirname + "/public"
6
+ public: `${import.meta.dirname}/public`
9
7
  });
10
8
 
11
9
  // Listen for load
12
- server.on("load", function (err) {
10
+ server.on("load", err => {
13
11
  console.log(err || "Server started on port 9000.");
14
12
  err && process.exit(1);
15
13
  });
16
14
 
17
15
  // Add page
18
- server.get("/", function (lien) {
16
+ server.get("/", lien => {
19
17
  lien.end("Hello World");
20
18
  });
21
19
 
22
20
  // Add a dynamic route
23
- server.get("/post/:id", function (lien) {
21
+ server.get("/post/:id", lien => {
24
22
  lien.end("Post id: " + lien.params.id);
25
23
  });
26
24
 
@@ -28,6 +26,6 @@ server.get("/post/:id", function (lien) {
28
26
  server.get("/test", "index.html");
29
27
 
30
28
  // Listen for server errors
31
- server.on("serverError", function (err) {
29
+ server.on("serverError", err => {
32
30
  console.log(err.stack);
33
- });
31
+ });
package/example/login.js CHANGED
@@ -1,43 +1,40 @@
1
- "use strict";
1
+ import Lien from "../lib/index.js";
2
+ import MongoStore from "connect-mongo";
2
3
 
3
- // Dependencies
4
- var Lien = require("../lib");
5
-
6
- var users = {
4
+ const users = {
7
5
  Alice: "123",
8
6
  Bob: "1234"
9
7
  };
10
8
 
11
9
  // Init lien app
12
- var app = new Lien({
10
+ const app = new Lien({
13
11
  host: "localhost",
14
12
  port: 9000,
15
- public: __dirname + "/public",
13
+ public: `${import.meta.dirname}/public`,
16
14
  session: {
17
- store: "connect-mongo",
18
- storeOptions: {
19
- url: "mongodb://localhost/test-app"
20
- }
15
+ secret: process.env.SESSION_SECRET,
16
+ store: MongoStore.create({
17
+ mongoUrl: process.env.MONGO_URL || "mongodb://127.0.0.1/test-app"
18
+ })
21
19
  }
22
20
  });
23
21
 
24
22
  // Listen for load
25
- app.on("load", function (err) {
23
+ app.on("load", err => {
26
24
  console.log(err || "App started on port 9000.");
27
25
  err && process.exit(1);
28
26
  });
29
27
 
30
28
  // Add page
31
- app.all("/", function (lien) {
29
+ app.all("/", lien => {
32
30
  if (lien.getSessionData("logged_in")) {
33
31
  lien.file("logout.html");
34
32
  } else {
35
33
  lien.file("login.html");
36
34
  }
37
35
  });
38
-
39
- app.post("/api/login", function (lien) {
40
- if (!lien.data.username || !lien.data.password) {
36
+ app.post("/api/login", lien => {
37
+ if (!lien.data?.username || !lien.data?.password) {
41
38
  return lien.apiError("Incomplete data.");
42
39
  }
43
40
 
@@ -53,30 +50,25 @@ app.post("/api/login", function (lien) {
53
50
  });
54
51
  return lien.redirect("/");
55
52
  }
56
-
57
53
  lien.apiError("Invalid credentials.", 403);
58
54
  });
59
-
60
- app.get("/api/session", function (lien) {
55
+ app.get("/api/session", lien => {
61
56
  lien.end(lien.getSessionData());
62
57
  });
63
-
64
- app.post("/api/logout", function (lien) {
58
+ app.post("/api/logout", async lien => {
65
59
  if (!lien.getSessionData("logged_in")) {
66
60
  return lien.apiError("You were not logged in anyways.");
67
61
  }
68
-
69
- lien.destroySession();
62
+ await lien.destroySession();
70
63
  lien.redirect("/");
71
64
  });
72
65
 
73
66
  // Add a dynamic route
74
- app.get("/post/:id", function (lien) {
67
+ app.get("/post/:id", lien => {
75
68
  lien.end("Post id: " + lien.params.id);
76
69
  });
77
-
78
- app.use("/auth", function (lien, next) {
79
- var username = lien.getSessionData("username");
70
+ app.use("/auth", async lien => {
71
+ const username = lien.getSessionData("username");
80
72
  lien.user = username ? {
81
73
  name: username
82
74
  } : null;
@@ -85,24 +77,19 @@ app.use("/auth", function (lien, next) {
85
77
  error: "Unauthorized"
86
78
  });
87
79
  }
88
- next();
89
80
  });
90
-
91
- app.get("/auth", function (lien) {
81
+ app.get("/auth", lien => {
92
82
  lien.end({
93
83
  user: "/auth/user"
94
84
  });
95
85
  });
96
-
97
- app.get("/auth/user", function (lien) {
86
+ app.get("/auth/user", lien => {
98
87
  lien.end({
99
88
  foo: "Bar",
100
89
  user: lien.user
101
90
  });
102
91
  });
103
-
104
92
  app.get("/test", "/index.html");
105
-
106
- app.on("serverError", function (err) {
93
+ app.on("serverError", err => {
107
94
  console.log(err.stack);
108
- });
95
+ });
package/example/secure.js CHANGED
@@ -1,16 +1,13 @@
1
- "use strict";
2
-
3
- // Dependencies
4
- var Lien = require("../lib");
1
+ import Lien from "../lib/index.js";
5
2
 
6
3
  // Init lien server
7
- var server = new Lien({
4
+ const server = new Lien({
8
5
  host: "localhost",
9
6
  port: 9000,
10
- public: __dirname + "/public",
7
+ public: import.meta.dirname + "/public",
11
8
  ssl: {
12
- key: __dirname + "/ssl/key.pem",
13
- cert: __dirname + "/ssl/cert.pem"
9
+ key: import.meta.dirname + "/ssl/key.pem",
10
+ cert: import.meta.dirname + "/ssl/cert.pem"
14
11
  }
15
12
  });
16
13
 
@@ -29,5 +26,4 @@ server.addPage("/", function (lien) {
29
26
  server.addPage("/post/:id", function (lien) {
30
27
  lien.end("Post id: " + lien.params.id);
31
28
  });
32
-
33
- server.addPage("/test", "/index.html");
29
+ server.addPage("/test", "/index.html");
package/lib/errors.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Selects HTML, JSON, or plain text for a built-in error response.
3
+ *
4
+ * @private
5
+ * @param {import("./lien.js").default} lien The request object.
6
+ * @param {string} message The public error message.
7
+ * @param {number} status The HTTP status.
8
+ * @returns {Promise<void>|undefined} The response operation, if it can still be sent.
9
+ */
10
+ function sendError (lien, message, status) {
11
+ if (lien.accepts("html")) {
12
+ return lien.end(message, status);
13
+ }
14
+
15
+ if (lien.accepts("json")) {
16
+ return lien.apiError(message, status);
17
+ }
18
+ return lien.end(message, status, "txt");
19
+ }
20
+
21
+ /**
22
+ * Appends not-found, CSRF, and error middleware to the server.
23
+ * Client errors retain their status. Internal errors use a generic public message.
24
+ *
25
+ * @param {import("./server.js").default} server The server to configure.
26
+ * @param {import("./server.js").ErrorPages} [options={}] Custom handlers or public filenames.
27
+ * @returns {void}
28
+ * @private
29
+ */
30
+ export function configureErrorPages (server, options = {}) {
31
+ const pages = {
32
+ notFound: lien => sendError(lien, "404 — Not found.", 404),
33
+ serverError: (lien, error) => {
34
+ const status = error.status ?? error.statusCode;
35
+ const code = Number.isInteger(status) && status >= 400 && status < 600 ? status : 500;
36
+ return sendError(lien, code === 500 ? "500 — Internal Server Error" : `${code} — Invalid request.`, code);
37
+ },
38
+ badCsrf: lien => sendError(lien, "What‽ Your browser did something unexpected.", 422),
39
+ ...options
40
+ };
41
+ server.app.use((req, res, next) => server._handleRoute(req, res, pages.notFound, [], next));
42
+ server.app.use((error, req, res, next) => {
43
+ if (res.headersSent) {
44
+ return next(error);
45
+ }
46
+ if (error.code === "ENOENT" || error.status === 404 || error.statusCode === 404) {
47
+ return server._handleRoute(req, res, pages.notFound, [error], next);
48
+ }
49
+ if (error.code === "EBADCSRFTOKEN") {
50
+ return server._handleRoute(req, res, pages.badCsrf, [error], next);
51
+ }
52
+ server.emit("serverError", error, req, res);
53
+ if (server.options.logErrors) {
54
+ console.error(error.stack);
55
+ }
56
+ return server._handleRoute(req, res, pages.serverError, [error], next);
57
+ });
58
+ }
@@ -0,0 +1,232 @@
1
+ import { METHODS } from "node:http";
2
+ import { parse, pathToRegexp } from "path-to-regexp";
3
+ import Hooks from "./hooks.js";
4
+
5
+ /**
6
+ * @typedef {Object<string, Object<string, Array<{re: RegExp, trans: Hooks}>>>} HookRegistry
7
+ * Hook definitions indexed by type and lowercase HTTP method.
8
+ * @private
9
+ */
10
+
11
+ /**
12
+ * HTTP method names used to register the public shortcuts.
13
+ *
14
+ * @type {Array<string>}
15
+ * @private
16
+ */
17
+ export const methods = [...new Set(METHODS.map(method => method.toLowerCase()))];
18
+ /**
19
+ * Converts Lien's legacy route syntax to path-to-regexp 9 syntax.
20
+ *
21
+ * @param {import("./server.js").RoutePattern} url The pattern to normalize.
22
+ * @returns {import("./server.js").RoutePattern}
23
+ * @private
24
+ */
25
+ export function normalizePattern (url) {
26
+ if (Array.isArray(url)) {
27
+ return url.map(normalizePattern);
28
+ }
29
+ if (typeof url !== "string") {
30
+ return url;
31
+ }
32
+ return url
33
+ .replace(/\/:([\w$]+)\?/g, "{/:$1}")
34
+ .replace(/\/:([\w$]+)\+/g, "/*$1")
35
+ .replace(/\/:([\w$]+)\*/g, "{/*$1}");
36
+ }
37
+
38
+ /**
39
+ * Compiles custom parameter expressions, which path-to-regexp 9 no longer parses.
40
+ *
41
+ * @param {string} pattern The legacy pattern.
42
+ * @returns {{regexp: RegExp, keys: Array<{name: string}>}} The matcher and capture names.
43
+ * @private
44
+ */
45
+ function compileCustomPattern (pattern) {
46
+ const keys = [];
47
+ let source = "^";
48
+ const escape = value => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
49
+ for (let index = 0; index < pattern.length;) {
50
+ if (pattern.startsWith("(.*)", index)) {
51
+ source += "(.*)";
52
+ keys.push({ name: keys.length });
53
+ index += 4;
54
+ continue;
55
+ }
56
+ if (pattern[index] !== ":" || !/[\w$]/.test(pattern[index + 1] ?? "")) {
57
+ source += escape(pattern[index++]);
58
+ continue;
59
+ }
60
+ let end = index + 1;
61
+ while (/[\w$]/.test(pattern[end] ?? "")) {
62
+ end++;
63
+ }
64
+ const name = pattern.slice(index + 1, end);
65
+ let expression = "[^/]+?";
66
+ if (pattern[end] === "(") {
67
+ const start = ++end;
68
+ let depth = 1;
69
+ while (end < pattern.length && depth) {
70
+ if (pattern[end] === "\\") {
71
+ end += 2;
72
+ continue;
73
+ }
74
+ if (pattern[end] === "(") depth++;
75
+ if (pattern[end] === ")") depth--;
76
+ end++;
77
+ }
78
+ if (depth) {
79
+ throw new TypeError(`Unclosed parameter expression in route: ${pattern}`);
80
+ }
81
+ expression = pattern.slice(start, end - 1);
82
+ }
83
+ const modifier = /[?+*]/.test(pattern[end] ?? "") ? pattern[end++] : "";
84
+ const prefix = source.endsWith("/") ? "/" : source.endsWith("\\.") ? "\\." : "";
85
+ if (prefix) {
86
+ source = source.slice(0, -prefix.length);
87
+ }
88
+ if (modifier === "?") {
89
+ source += `(?:${prefix}(${expression}))?`;
90
+ } else if (modifier === "+" || modifier === "*") {
91
+ const separator = prefix || "/";
92
+ const repeated = `(${expression}(?:${separator}${expression})*)`;
93
+ source += modifier === "+" ? `${prefix}${repeated}` : `(?:${prefix}${repeated})?`;
94
+ } else {
95
+ source += `${prefix}(${expression})`;
96
+ }
97
+ keys.push({ name });
98
+ index = end;
99
+ }
100
+ return { regexp: new RegExp(`${source}(?:/)?$`, "i"), keys };
101
+ }
102
+
103
+ /** Counts capture groups while ignoring escaped parentheses and character classes. */
104
+ function countCaptures (regexp) {
105
+ let count = 0;
106
+ let inClass = false;
107
+ const source = regexp.source;
108
+ for (let index = 0; index < source.length; index++) {
109
+ if (source[index] === "\\") {
110
+ index++;
111
+ } else if (source[index] === "[") {
112
+ inClass = true;
113
+ } else if (source[index] === "]") {
114
+ inClass = false;
115
+ } else if (!inClass && source[index] === "(" &&
116
+ (source[index + 1] !== "?" ||
117
+ (source[index + 2] === "<" && !/[=!]/.test(source[index + 3] ?? "")))) {
118
+ count++;
119
+ }
120
+ }
121
+ return count;
122
+ }
123
+
124
+ /**
125
+ * Compiles strings, regular expressions, and mixed pattern arrays.
126
+ *
127
+ * @param {import("./server.js").RoutePattern} url The route pattern.
128
+ * @returns {{regexp: RegExp, keys: Array<{name: string}>}} The matcher and capture names.
129
+ * @private
130
+ */
131
+ function compilePattern (url) {
132
+ if (Array.isArray(url)) {
133
+ const parts = url.map(compilePattern);
134
+ return {
135
+ regexp: new RegExp(parts.map(({ regexp }) => `(?:${regexp.source})`).join("|"), "i"),
136
+ keys: parts.flatMap(({ keys, regexp, rawRegExp }) => rawRegExp
137
+ ? Array.from({ length: countCaptures(regexp) }, (_, index) => ({ name: index, rawRegExp: true }))
138
+ : keys)
139
+ };
140
+ }
141
+ if (url instanceof RegExp) {
142
+ return { regexp: url, keys: [], rawRegExp: true };
143
+ }
144
+ if (url === "*" || url === "(.*)") {
145
+ return { regexp: /^(.*)(?:\/)?$/i, keys: [{ name: 0 }] };
146
+ }
147
+ if (/:([\w$]+)\(|\(\.\*\)/.test(url)) {
148
+ return compileCustomPattern(url);
149
+ }
150
+ const pattern = normalizePattern(url);
151
+ if (pattern.endsWith("/")) {
152
+ const parsed = parse(pattern);
153
+ const [token] = parsed.tokens;
154
+ // Let path-to-regexp supply the optional delimiter for literal paths.
155
+ if (parsed.tokens.length === 1 && token.type === "text" &&
156
+ token.value.length > 1 && !token.value.endsWith("//")) {
157
+ token.value = token.value.slice(0, -1);
158
+ }
159
+ return pathToRegexp(parsed);
160
+ }
161
+ return pathToRegexp(pattern);
162
+ }
163
+
164
+ /**
165
+ * Compiles a legacy Lien pattern for Express 5 and restores named parameters.
166
+ *
167
+ * @param {import("./server.js").RoutePattern} url The route pattern.
168
+ * @returns {{regexp: RegExp, restoreParams: Function}} The matcher and parameter middleware.
169
+ * @private
170
+ */
171
+ export function compileRoute (url) {
172
+ const { regexp, keys } = compilePattern(url);
173
+ const restoreParams = (req, res, next) => {
174
+ const captures = req.params;
175
+ req.params = keys.length ? Object.fromEntries(keys.flatMap((key, index) => {
176
+ const value = key.rawRegExp ? captures[index] : captures[key.name] ?? captures[index];
177
+ return value === undefined ? [] : [
178
+ [key.name, value]
179
+ ];
180
+ })) : captures;
181
+ next();
182
+ };
183
+ return { regexp, restoreParams };
184
+ }
185
+
186
+ /**
187
+ * Selects registered pipelines by request path or by identical compiled pattern.
188
+ *
189
+ * @param {HookRegistry} registry The hook definitions.
190
+ * @param {string} type The hook type.
191
+ * @param {string|import("./server.js").RoutePattern} url The request path or registered pattern.
192
+ * @param {string} method The lowercase HTTP method.
193
+ * @param {boolean} [strict=false] Whether to compare compiled patterns.
194
+ * @returns {Hooks|null} The selected pipeline, or null.
195
+ * @private
196
+ */
197
+ export function getHooks (registry, type, url, method, strict = false) {
198
+ const pattern = strict ? compilePattern(url).regexp.toString() : null;
199
+ const matching = (registry[type]?.[method] ?? []).filter(({ re }) => {
200
+ re.lastIndex = 0;
201
+ return strict ? re.toString() === pattern : re.test(url);
202
+ }).map(({ trans }) => trans);
203
+ if (!matching.length) {
204
+ return null;
205
+ }
206
+ return matching.length === 1 ? matching[0] : new Hooks().add(matching, Hooks.PARALLEL);
207
+ }
208
+
209
+ /**
210
+ * Stores a native pipeline under its type, method, and compiled pattern.
211
+ *
212
+ * @param {HookRegistry} registry The hook definitions.
213
+ * @param {string} type The hook type.
214
+ * @param {import("./server.js").RoutePattern} url The registered pattern.
215
+ * @param {string} method The lowercase HTTP method.
216
+ * @param {Hooks} pipeline The pipeline to register.
217
+ * @returns {Hooks} The inserted pipeline.
218
+ * @throws {TypeError} If the pipeline is not native.
219
+ * @private
220
+ */
221
+ export function insertHook (registry, type, url, method, pipeline) {
222
+ if (!(pipeline instanceof Hooks)) {
223
+ throw new TypeError("insertHook expects a Lien.Hooks pipeline. Register external callbacks with .add().");
224
+ }
225
+ const group = registry[type] ??= Object.create(null);
226
+ const hooks = group[method] ??= [];
227
+ hooks.push({
228
+ re: compilePattern(url).regexp,
229
+ trans: pipeline
230
+ });
231
+ return pipeline;
232
+ }