@jsenv/server 12.6.2 → 12.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jsenv/server",
3
- "version": "12.6.2",
3
+ "version": "12.7.1",
4
4
  "description": "Write your Node.js server using pure functions",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -10,61 +10,38 @@
10
10
  },
11
11
  "repository": {
12
12
  "type": "git",
13
- "url": "https://github.com/jsenv/server"
13
+ "url": "https://github.com/jsenv/jsenv-core",
14
+ "directory": "packages/server"
14
15
  },
15
16
  "engines": {
16
17
  "node": ">=16.13.0"
17
18
  },
18
19
  "publishConfig": {
19
- "access": "public"
20
+ "access": "public",
21
+ "registry": "https://registry.npmjs.org"
20
22
  },
21
23
  "type": "module",
22
24
  "exports": {
23
25
  ".": {
24
- "import": "./main.js"
26
+ "import": "./src/main.js"
25
27
  },
26
28
  "./*": "./*"
27
29
  },
28
- "main": "./main.js",
30
+ "main": "./src/main.js",
29
31
  "files": [
30
- "/src/",
31
- "/main.js"
32
+ "/src/"
32
33
  ],
33
34
  "scripts": {
34
- "importmap": "node ./script/importmap/importmap.mjs",
35
- "eslint": "node ./node_modules/eslint/bin/eslint.js . --ext=.js,.mjs",
36
- "performance": "node --expose-gc ./script/performance/performance.mjs --log",
37
- "snapshot": "node ./test/internal_error/generate_html_snapshot_files.mjs",
38
- "test": "node ./script/test/test.mjs",
39
- "test-with-coverage": "npm run test -- --coverage",
40
- "prettier": "prettier --write .",
41
- "certificate-install": "node ./script/certificate/certificate_install.mjs",
42
- "playwright-install": "npx playwright install-deps && npx playwright install"
35
+ "test": "node --conditions=development ./scripts/test.mjs"
43
36
  },
44
37
  "dependencies": {
45
- "@jsenv/abort": "4.1.2",
46
- "@jsenv/logger": "4.0.1",
47
- "@jsenv/url-meta": "6.2.0",
48
- "node-fetch": "2.6.7",
49
- "path-to-regexp": "6.2.0"
38
+ "@jsenv/abort": "4.2.2",
39
+ "@jsenv/logger": "4.1.1",
40
+ "@jsenv/url-meta": "7.0.0",
41
+ "@jsenv/utils": "2.0.0"
50
42
  },
51
43
  "devDependencies": {
52
- "@jsenv/assert": "2.5.2",
53
- "@jsenv/core": "25.4.9",
54
- "@jsenv/eslint-config": "16.0.9",
55
- "@jsenv/filesystem": "2.7.1",
56
- "@jsenv/github-release-package": "1.3.4",
57
- "@jsenv/https-local": "1.0.7",
58
- "@jsenv/importmap-eslint-resolver": "5.2.5",
59
- "@jsenv/importmap-node-module": "5.1.3",
60
- "@jsenv/package-publish": "1.7.2",
61
- "@jsenv/performance-impact": "2.2.7",
62
- "eslint": "8.7.0",
63
- "eslint-plugin-import": "2.25.4",
64
- "eventsource": "1.1.0",
65
- "fastify": "3.27.0",
66
- "fastify-static": "4.5.0",
67
- "playwright": "1.18.1",
68
- "prettier": "2.5.1"
44
+ "@jsenv/fetch": "../fetch/",
45
+ "eventsource": "2.0.2"
69
46
  }
70
- }
47
+ }
@@ -4,31 +4,26 @@
4
4
  * It is meant to be used inside "requestToResponse"
5
5
  */
6
6
 
7
- import { createReadStream, statSync, promises } from "node:fs"
8
-
7
+ import { createReadStream, statSync, readFile } from "node:fs"
9
8
  import {
10
9
  isFileSystemPath,
11
- urlToFileSystemPath,
12
10
  fileSystemPathToUrl,
13
11
  } from "@jsenv/server/src/internal/filesystem.js"
14
12
  import { bufferToEtag } from "@jsenv/server/src/internal/etag.js"
13
+ import { CONTENT_TYPE } from "@jsenv/utils/src/content_type/content_type.js"
14
+
15
15
  import { composeTwoResponses } from "./internal/response_composition.js"
16
16
  import { convertFileSystemErrorToResponseProperties } from "./internal/convertFileSystemErrorToResponseProperties.js"
17
- import { jsenvContentTypeMap } from "./jsenvContentTypeMap.js"
18
17
  import { timeFunction } from "./server_timing/timing_measure.js"
19
18
  import { negotiateContentEncoding } from "./content_negotiation/negotiateContentEncoding.js"
20
- import { urlToContentType } from "./urlToContentType.js"
21
19
  import { serveDirectory } from "./serve_directory.js"
22
20
 
23
- const ETAG_MEMORY_MAP = new Map()
24
-
25
21
  export const fetchFileSystem = async (
26
22
  filesystemUrl,
27
23
  {
28
24
  // signal,
29
25
  method = "GET",
30
26
  headers = {},
31
- contentTypeMap = jsenvContentTypeMap,
32
27
  etagEnabled = false,
33
28
  etagMemory = true,
34
29
  etagMemoryMaxSize = 1000,
@@ -97,13 +92,11 @@ export const fetchFileSystem = async (
97
92
  }
98
93
  }
99
94
 
100
- let sourceUrl = `file://${new URL(urlString).pathname}`
101
- const sourceFilesystemPath = urlToFileSystemPath(filesystemUrl)
102
-
95
+ const sourceUrl = `file://${new URL(urlString).pathname}`
103
96
  try {
104
97
  const [readStatTiming, sourceStat] = await timeFunction(
105
98
  "file service>read file stat",
106
- () => statSync(sourceFilesystemPath),
99
+ () => statSync(new URL(sourceUrl)),
107
100
  )
108
101
  if (sourceStat.isDirectory()) {
109
102
  if (canReadDirectory) {
@@ -155,7 +148,6 @@ export const fetchFileSystem = async (
155
148
  const compressedResponse = await getCompressedResponse({
156
149
  headers,
157
150
  sourceUrl,
158
- contentTypeMap,
159
151
  })
160
152
  if (compressedResponse) {
161
153
  response = compressedResponse
@@ -165,7 +157,6 @@ export const fetchFileSystem = async (
165
157
  response = await getRawResponse({
166
158
  sourceStat,
167
159
  sourceUrl,
168
- contentTypeMap,
169
160
  })
170
161
  }
171
162
 
@@ -287,6 +278,7 @@ const getEtagResponse = async ({
287
278
  }
288
279
  }
289
280
 
281
+ const ETAG_MEMORY_MAP = new Map()
290
282
  const computeEtag = async ({
291
283
  etagMemory,
292
284
  etagMemoryMaxSize,
@@ -302,9 +294,15 @@ const computeEtag = async ({
302
294
  return etagMemoryEntry.eTag
303
295
  }
304
296
  }
305
- const fileContentAsBuffer = await promises.readFile(
306
- urlToFileSystemPath(sourceUrl),
307
- )
297
+ const fileContentAsBuffer = await new Promise((resolve, reject) => {
298
+ readFile(new URL(sourceUrl), (error, buffer) => {
299
+ if (error) {
300
+ reject(error)
301
+ } else {
302
+ resolve(buffer)
303
+ }
304
+ })
305
+ })
308
306
  const eTag = bufferToEtag(fileContentAsBuffer)
309
307
  if (etagMemory) {
310
308
  if (ETAG_MEMORY_MAP.size >= etagMemoryMaxSize) {
@@ -364,11 +362,7 @@ const getMtimeResponse = async ({ headers, sourceStat }) => {
364
362
  }
365
363
  }
366
364
 
367
- const getCompressedResponse = async ({
368
- sourceUrl,
369
- headers,
370
- contentTypeMap,
371
- }) => {
365
+ const getCompressedResponse = async ({ sourceUrl, headers }) => {
372
366
  const acceptedCompressionFormat = negotiateContentEncoding(
373
367
  { headers },
374
368
  Object.keys(availableCompressionFormats),
@@ -385,7 +379,7 @@ const getCompressedResponse = async ({
385
379
  return {
386
380
  status: 200,
387
381
  headers: {
388
- "content-type": urlToContentType(sourceUrl, contentTypeMap),
382
+ "content-type": CONTENT_TYPE.fromUrlExtension(sourceUrl),
389
383
  "content-encoding": acceptedCompressionFormat,
390
384
  "vary": "accept-encoding",
391
385
  },
@@ -394,29 +388,32 @@ const getCompressedResponse = async ({
394
388
  }
395
389
 
396
390
  const fileUrlToReadableStream = (fileUrl) => {
397
- return createReadStream(urlToFileSystemPath(fileUrl), { emitClose: true })
391
+ return createReadStream(new URL(fileUrl), {
392
+ emitClose: true,
393
+ autoClose: true,
394
+ })
398
395
  }
399
396
 
400
397
  const availableCompressionFormats = {
401
398
  br: async (fileReadableStream) => {
402
- const { createBrotliCompress } = await import("zlib")
399
+ const { createBrotliCompress } = await import("node:zlib")
403
400
  return fileReadableStream.pipe(createBrotliCompress())
404
401
  },
405
402
  deflate: async (fileReadableStream) => {
406
- const { createDeflate } = await import("zlib")
403
+ const { createDeflate } = await import("node:zlib")
407
404
  return fileReadableStream.pipe(createDeflate())
408
405
  },
409
406
  gzip: async (fileReadableStream) => {
410
- const { createGzip } = await import("zlib")
407
+ const { createGzip } = await import("node:zlib")
411
408
  return fileReadableStream.pipe(createGzip())
412
409
  },
413
410
  }
414
411
 
415
- const getRawResponse = async ({ sourceUrl, sourceStat, contentTypeMap }) => {
412
+ const getRawResponse = async ({ sourceUrl, sourceStat }) => {
416
413
  return {
417
414
  status: 200,
418
415
  headers: {
419
- "content-type": urlToContentType(sourceUrl, contentTypeMap),
416
+ "content-type": CONTENT_TYPE.fromUrlExtension(sourceUrl),
420
417
  "content-length": sourceStat.size,
421
418
  },
422
419
  body: fileUrlToReadableStream(sourceUrl),
@@ -1,5 +1,4 @@
1
- import { networkInterfaces } from "os"
2
- import { URL } from "url"
1
+ import { networkInterfaces } from "node:os"
3
2
 
4
3
  export const getServerOrigins = ({ protocol, ip, port }) => {
5
4
  const isInternalIp = ip === "127.0.0.1"
@@ -4,8 +4,8 @@ https://stackoverflow.com/a/42019773/2634179
4
4
 
5
5
  */
6
6
 
7
- import http from "http"
8
- import net from "net"
7
+ import http from "node:http"
8
+ import net from "node:net"
9
9
  import { listenEvent } from "./listenEvent.js"
10
10
 
11
11
  export const createPolyglotServer = async ({
package/src/main.js ADDED
@@ -0,0 +1,48 @@
1
+ /*
2
+ * This file is the first file executed by code using the package
3
+ * Its responsability is to export what is documented
4
+ * Ideally this file should be kept simple to help discovering codebase progressively.
5
+ */
6
+
7
+ export { startServer } from "./startServer.js"
8
+ export { composeServices } from "./service_composition/service_composition.js"
9
+ export { setupRoutes } from "./service_composition/routing.js"
10
+ export { readRequestBody } from "./readRequestBody.js"
11
+ export { fetchFileSystem } from "./fetch_filesystem.js"
12
+ export {
13
+ STOP_REASON_INTERNAL_ERROR,
14
+ STOP_REASON_PROCESS_SIGHUP,
15
+ STOP_REASON_PROCESS_SIGTERM,
16
+ STOP_REASON_PROCESS_SIGINT,
17
+ STOP_REASON_PROCESS_BEFORE_EXIT,
18
+ STOP_REASON_PROCESS_EXIT,
19
+ STOP_REASON_NOT_SPECIFIED,
20
+ } from "./stopReasons.js"
21
+
22
+ // CORS
23
+ export {
24
+ pluginCORS,
25
+ jsenvAccessControlAllowedHeaders,
26
+ jsenvAccessControlAllowedMethods,
27
+ } from "./cors/plugin_cors.js"
28
+
29
+ // server timings
30
+ export { pluginServerTiming } from "./server_timing/plugin_server_timing.js"
31
+ export { timeFunction, timeStart } from "./server_timing/timing_measure.js"
32
+
33
+ // SSE
34
+ export { createSSERoom } from "./sse/createSSERoom.js"
35
+
36
+ // content-negotiation
37
+ export { negotiateContentType } from "./content_negotiation/negotiateContentType.js"
38
+ export { negotiateContentEncoding } from "./content_negotiation/negotiateContentEncoding.js"
39
+ export { negotiateContentLanguage } from "./content_negotiation/negotiateContentLanguage.js"
40
+ export { pluginContentNegotiationCheck } from "./content_negotiation/plugin_content_negotiation_check.js"
41
+
42
+ // others
43
+ export { serveDirectory } from "./serve_directory.js"
44
+ export { fromFetchResponse } from "./from_fetch_response.js"
45
+ export { composeTwoResponses } from "./internal/response_composition.js"
46
+ export { pluginRessourceAliases } from "./ressource_aliases/plugin_ressource_aliases.js"
47
+ export { pluginRequestWaitingCheck } from "./plugin_request_waiting_check.js"
48
+ export { findFreePort } from "./internal/listen.js"
@@ -1,4 +1,4 @@
1
- import { createDetailedMessage } from "@jsenv/logger"
1
+ import { createDetailedMessage } from "@jsenv/log"
2
2
 
3
3
  export const pluginRequestWaitingCheck = ({
4
4
  requestWaitingMs = 20000,
@@ -1,4 +1,4 @@
1
- import { applyAliases } from "@jsenv/url-meta"
1
+ import { URL_META } from "@jsenv/url-meta"
2
2
 
3
3
  export const pluginRessourceAliases = (ressourceAliases) => {
4
4
  const aliases = {}
@@ -9,7 +9,7 @@ export const pluginRessourceAliases = (ressourceAliases) => {
9
9
  ressource_aliases: {
10
10
  onRequest: (request, { redirectRequest }) => {
11
11
  const ressourceBeforeAlias = request.ressource
12
- const urlAfterAliasing = applyAliases({
12
+ const urlAfterAliasing = URL_META.applyAliases({
13
13
  url: asFileUrl(request.pathname),
14
14
  aliases,
15
15
  })
@@ -1,4 +1,4 @@
1
- import { performance } from "perf_hooks"
1
+ import { performance } from "node:perf_hooks"
2
2
 
3
3
  export const timeStart = (name) => {
4
4
  // as specified in https://w3c.github.io/server-timing/#the-performanceservertiming-interface
@@ -0,0 +1,431 @@
1
+ // ESM version of "path-to-regexp@6.2.1"
2
+ // https://github.com/pillarjs/path-to-regexp/blob/master/package.json
3
+
4
+ /**
5
+ * Tokenize input string.
6
+ */
7
+ function lexer(str) {
8
+ var tokens = []
9
+ var i = 0
10
+ while (i < str.length) {
11
+ var char = str[i]
12
+ if (char === "*" || char === "+" || char === "?") {
13
+ tokens.push({ type: "MODIFIER", index: i, value: str[i++] })
14
+ continue
15
+ }
16
+ if (char === "\\") {
17
+ tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] })
18
+ continue
19
+ }
20
+ if (char === "{") {
21
+ tokens.push({ type: "OPEN", index: i, value: str[i++] })
22
+ continue
23
+ }
24
+ if (char === "}") {
25
+ tokens.push({ type: "CLOSE", index: i, value: str[i++] })
26
+ continue
27
+ }
28
+ if (char === ":") {
29
+ var name = ""
30
+ let j = i + 1
31
+ while (j < str.length) {
32
+ var code = str.charCodeAt(j)
33
+ if (
34
+ // `0-9`
35
+ (code >= 48 && code <= 57) ||
36
+ // `A-Z`
37
+ (code >= 65 && code <= 90) ||
38
+ // `a-z`
39
+ (code >= 97 && code <= 122) ||
40
+ // `_`
41
+ code === 95
42
+ ) {
43
+ name += str[j++]
44
+ continue
45
+ }
46
+ break
47
+ }
48
+ if (!name) throw new TypeError("Missing parameter name at ".concat(i))
49
+ tokens.push({ type: "NAME", index: i, value: name })
50
+ i = j
51
+ continue
52
+ }
53
+ if (char === "(") {
54
+ var count = 1
55
+ var pattern = ""
56
+ var j = i + 1
57
+ if (str[j] === "?") {
58
+ throw new TypeError('Pattern cannot start with "?" at '.concat(j))
59
+ }
60
+ while (j < str.length) {
61
+ if (str[j] === "\\") {
62
+ pattern += str[j++] + str[j++]
63
+ continue
64
+ }
65
+ if (str[j] === ")") {
66
+ count--
67
+ if (count === 0) {
68
+ j++
69
+ break
70
+ }
71
+ } else if (str[j] === "(") {
72
+ count++
73
+ if (str[j + 1] !== "?") {
74
+ throw new TypeError(
75
+ "Capturing groups are not allowed at ".concat(j),
76
+ )
77
+ }
78
+ }
79
+ pattern += str[j++]
80
+ }
81
+ if (count) throw new TypeError("Unbalanced pattern at ".concat(i))
82
+ if (!pattern) throw new TypeError("Missing pattern at ".concat(i))
83
+ tokens.push({ type: "PATTERN", index: i, value: pattern })
84
+ i = j
85
+ continue
86
+ }
87
+ tokens.push({ type: "CHAR", index: i, value: str[i++] })
88
+ }
89
+ tokens.push({ type: "END", index: i, value: "" })
90
+ return tokens
91
+ }
92
+ /**
93
+ * Parse a string for the raw tokens.
94
+ */
95
+ export function parse(str, { prefixes = "./", delimiter = "/#?" } = {}) {
96
+ var tokens = lexer(str)
97
+
98
+ var defaultPattern = "[^".concat(escapeString(delimiter), "]+?")
99
+ var result = []
100
+ var key = 0
101
+ var i = 0
102
+ var path = ""
103
+ var tryConsume = function (type) {
104
+ if (i < tokens.length && tokens[i].type === type) return tokens[i++].value
105
+ return undefined
106
+ }
107
+ var mustConsume = function (type) {
108
+ var value = tryConsume(type)
109
+ if (value !== undefined) return value
110
+ var _a = tokens[i]
111
+ var nextType = _a.type
112
+ var index = _a.inde
113
+ throw new TypeError(
114
+ "Unexpected "
115
+ .concat(nextType, " at ")
116
+ .concat(index, ", expected ")
117
+ .concat(type),
118
+ )
119
+ }
120
+ var consumeText = function () {
121
+ var result = ""
122
+ var value
123
+ while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) {
124
+ result += value
125
+ }
126
+ return result
127
+ }
128
+ while (i < tokens.length) {
129
+ var char = tryConsume("CHAR")
130
+ var name = tryConsume("NAME")
131
+ var pattern = tryConsume("PATTERN")
132
+ if (name || pattern) {
133
+ let prefix = char || ""
134
+ if (prefixes.indexOf(prefix) === -1) {
135
+ path += prefix
136
+ prefix = ""
137
+ }
138
+ if (path) {
139
+ result.push(path)
140
+ path = ""
141
+ }
142
+ result.push({
143
+ name: name || key++,
144
+ prefix,
145
+ suffix: "",
146
+ pattern: pattern || defaultPattern,
147
+ modifier: tryConsume("MODIFIER") || "",
148
+ })
149
+ continue
150
+ }
151
+ var value = char || tryConsume("ESCAPED_CHAR")
152
+ if (value) {
153
+ path += value
154
+ continue
155
+ }
156
+ if (path) {
157
+ result.push(path)
158
+ path = ""
159
+ }
160
+ var open = tryConsume("OPEN")
161
+ if (open) {
162
+ var prefix = consumeText()
163
+ var name_1 = tryConsume("NAME") || ""
164
+ var pattern_1 = tryConsume("PATTERN") || ""
165
+ var suffix = consumeText()
166
+ mustConsume("CLOSE")
167
+ result.push({
168
+ name: name_1 || (pattern_1 ? key++ : ""),
169
+ pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
170
+ prefix,
171
+ suffix,
172
+ modifier: tryConsume("MODIFIER") || "",
173
+ })
174
+ continue
175
+ }
176
+ mustConsume("END")
177
+ }
178
+ return result
179
+ }
180
+ /**
181
+ * Compile a string to a template function for the path.
182
+ */
183
+ export function compile(str, options) {
184
+ return tokensToFunction(parse(str, options), options)
185
+ }
186
+ /**
187
+ * Expose a method for transforming tokens into the path function.
188
+ */
189
+ export function tokensToFunction(
190
+ tokens,
191
+ { sensitive, encode = (x) => x, validate = true },
192
+ ) {
193
+ // Compile all the tokens into regexps.
194
+ var matches = tokens.map(function (token) {
195
+ if (typeof token === "object") {
196
+ return new RegExp(
197
+ "^(?:".concat(token.pattern, ")$"),
198
+ sensitive ? "" : "i",
199
+ )
200
+ }
201
+ return undefined
202
+ })
203
+ return function (data) {
204
+ var path = ""
205
+ for (var i = 0; i < tokens.length; i++) {
206
+ var token = tokens[i]
207
+ if (typeof token === "string") {
208
+ path += token
209
+ continue
210
+ }
211
+ var value = data ? data[token.name] : undefined
212
+ var optional = token.modifier === "?" || token.modifier === "*"
213
+ var repeat = token.modifier === "*" || token.modifier === "+"
214
+ if (Array.isArray(value)) {
215
+ if (!repeat) {
216
+ throw new TypeError(
217
+ 'Expected "'.concat(
218
+ token.name,
219
+ '" to not repeat, but got an array',
220
+ ),
221
+ )
222
+ }
223
+ if (value.length === 0) {
224
+ if (optional) continue
225
+ throw new TypeError(
226
+ 'Expected "'.concat(token.name, '" to not be empty'),
227
+ )
228
+ }
229
+ for (var j = 0; j < value.length; j++) {
230
+ let segment = encode(value[j], token)
231
+ if (validate && !matches[i].test(segment)) {
232
+ throw new TypeError(
233
+ 'Expected all "'
234
+ .concat(token.name, '" to match "')
235
+ .concat(token.pattern, '", but got "')
236
+ .concat(segment, '"'),
237
+ )
238
+ }
239
+ path += token.prefix + segment + token.suffix
240
+ }
241
+ continue
242
+ }
243
+ if (typeof value === "string" || typeof value === "number") {
244
+ var segment = encode(String(value), token)
245
+ if (validate && !matches[i].test(segment)) {
246
+ throw new TypeError(
247
+ 'Expected "'
248
+ .concat(token.name, '" to match "')
249
+ .concat(token.pattern, '", but got "')
250
+ .concat(segment, '"'),
251
+ )
252
+ }
253
+ path += token.prefix + segment + token.suffix
254
+ continue
255
+ }
256
+ if (optional) continue
257
+ var typeOfMessage = repeat ? "an array" : "a string"
258
+ throw new TypeError(
259
+ 'Expected "'.concat(token.name, '" to be ').concat(typeOfMessage),
260
+ )
261
+ }
262
+ return path
263
+ }
264
+ }
265
+ /**
266
+ * Create path match function from `path-to-regexp` spec.
267
+ */
268
+ export function match(str, options) {
269
+ var keys = []
270
+ var re = pathToRegexp(str, keys, options)
271
+ return regexpToFunction(re, keys, options)
272
+ }
273
+ /**
274
+ * Create a path match function from `path-to-regexp` output.
275
+ */
276
+ export function regexpToFunction(re, keys, { decode = (x) => x }) {
277
+ return function (pathname) {
278
+ var m = re.exec(pathname)
279
+ if (!m) return false
280
+ var path = m[0]
281
+ var index = m.index
282
+ var params = Object.create(null)
283
+ var _loop_1 = function (i) {
284
+ if (m[i] === undefined) return "continue"
285
+ var key = keys[i - 1]
286
+ if (key.modifier === "*" || key.modifier === "+") {
287
+ params[key.name] = m[i]
288
+ .split(key.prefix + key.suffix)
289
+ .map(function (value) {
290
+ return decode(value, key)
291
+ })
292
+ } else {
293
+ params[key.name] = decode(m[i], key)
294
+ }
295
+ return undefined
296
+ }
297
+ for (var i = 1; i < m.length; i++) {
298
+ _loop_1(i)
299
+ }
300
+ return { path, index, params }
301
+ }
302
+ }
303
+ /**
304
+ * Escape a regular expression string.
305
+ */
306
+ function escapeString(str) {
307
+ return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1")
308
+ }
309
+ /**
310
+ * Pull out keys from a regexp.
311
+ */
312
+ function regexpToRegexp(path, keys) {
313
+ if (!keys) return path
314
+ var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g
315
+ var index = 0
316
+ var execResult = groupsRegex.exec(path.source)
317
+ while (execResult) {
318
+ keys.push({
319
+ // Use parenthesized substring match if available, index otherwise
320
+ name: execResult[1] || index++,
321
+ prefix: "",
322
+ suffix: "",
323
+ modifier: "",
324
+ pattern: "",
325
+ })
326
+ execResult = groupsRegex.exec(path.source)
327
+ }
328
+ return path
329
+ }
330
+ /**
331
+ * Transform an array into a regexp.
332
+ */
333
+ function arrayToRegexp(paths, keys, { sensitive }) {
334
+ var parts = paths.map(function (path) {
335
+ return pathToRegexp(path, keys, { sensitive }).source
336
+ })
337
+ return new RegExp("(?:".concat(parts.join("|"), ")"), sensitive ? "" : "i")
338
+ }
339
+ /**
340
+ * Create a path regexp from string input.
341
+ */
342
+ function stringToRegexp(path, keys, options) {
343
+ return tokensToRegexp(parse(path, options), keys, options)
344
+ }
345
+ /**
346
+ * Expose a function for taking tokens and returning a RegExp.
347
+ */
348
+ export function tokensToRegexp(
349
+ tokens,
350
+ keys,
351
+ {
352
+ sensitive,
353
+ strict = false,
354
+ start = true,
355
+ end = true,
356
+ encode = (x) => x,
357
+ delimiter = "/#?",
358
+ endsWith = "",
359
+ } = {},
360
+ ) {
361
+ var endsWithRe = "[".concat(escapeString(endsWith), "]|$")
362
+ var delimiterRe = "[".concat(escapeString(delimiter), "]")
363
+ var route = start ? "^" : ""
364
+ // Iterate over the tokens and create our regexp string.
365
+ for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
366
+ var token = tokens_1[_i]
367
+ if (typeof token === "string") {
368
+ route += escapeString(encode(token))
369
+ } else {
370
+ var prefix = escapeString(encode(token.prefix))
371
+ var suffix = escapeString(encode(token.suffix))
372
+ if (token.pattern) {
373
+ if (keys) keys.push(token)
374
+ if (prefix || suffix) {
375
+ if (token.modifier === "+" || token.modifier === "*") {
376
+ var mod = token.modifier === "*" ? "?" : ""
377
+ route += "(?:"
378
+ .concat(prefix, "((?:")
379
+ .concat(token.pattern, ")(?:")
380
+ .concat(suffix)
381
+ .concat(prefix, "(?:")
382
+ .concat(token.pattern, "))*)")
383
+ .concat(suffix, ")")
384
+ .concat(mod)
385
+ } else {
386
+ route += "(?:"
387
+ .concat(prefix, "(")
388
+ .concat(token.pattern, ")")
389
+ .concat(suffix, ")")
390
+ .concat(token.modifier)
391
+ }
392
+ } else if (token.modifier === "+" || token.modifier === "*") {
393
+ route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")")
394
+ } else {
395
+ route += "(".concat(token.pattern, ")").concat(token.modifier)
396
+ }
397
+ } else {
398
+ route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier)
399
+ }
400
+ }
401
+ }
402
+ if (end) {
403
+ if (!strict) route += "".concat(delimiterRe, "?")
404
+ route += endsWith ? "(?=".concat(endsWithRe, ")") : "$"
405
+ } else {
406
+ var endToken = tokens[tokens.length - 1]
407
+ var isEndDelimited =
408
+ typeof endToken === "string"
409
+ ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1
410
+ : endToken === undefined
411
+ if (!strict) {
412
+ route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?")
413
+ }
414
+ if (!isEndDelimited) {
415
+ route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")")
416
+ }
417
+ }
418
+ return new RegExp(route, sensitive ? "" : "i")
419
+ }
420
+ /**
421
+ * Normalize the given path string, returning a regular expression.
422
+ *
423
+ * An empty array can be passed in for the keys, which will hold the
424
+ * placeholder key descriptions. For example, using `/user/:id`, `keys` will
425
+ * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
426
+ */
427
+ export function pathToRegexp(path, keys, options) {
428
+ if (path instanceof RegExp) return regexpToRegexp(path, keys)
429
+ if (Array.isArray(path)) return arrayToRegexp(path, keys, options)
430
+ return stringToRegexp(path, keys, options)
431
+ }
@@ -1,10 +1,6 @@
1
- import { createRequire } from "node:module"
2
-
3
- const require = createRequire(import.meta.url)
1
+ import { match } from "./path_to_regexp.js"
4
2
 
5
3
  export const setupRoutes = (routes) => {
6
- const { match } = require("path-to-regexp")
7
-
8
4
  const candidates = Object.keys(routes).map((pathPattern) => {
9
5
  const applyPatternMatching = match(pathPattern, {
10
6
  decode: decodeURIComponent,
@@ -1,4 +1,4 @@
1
- import { createLogger } from "@jsenv/logger"
1
+ import { createLogger } from "@jsenv/log"
2
2
 
3
3
  import {
4
4
  createObservable,
@@ -1,6 +1,6 @@
1
1
  import http from "node:http"
2
2
  import cluster from "node:cluster"
3
- import { createDetailedMessage, createLogger } from "@jsenv/logger"
3
+ import { createDetailedMessage, createLogger } from "@jsenv/log"
4
4
  import {
5
5
  Abort,
6
6
  raceProcessTeardownEvents,
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 jsenv
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/main.js DELETED
@@ -1,50 +0,0 @@
1
- /*
2
- * This file is the first file executed by code using the package
3
- * Its responsability is to export what is documented
4
- * Ideally this file should be kept simple to help discovering codebase progressively.
5
- */
6
-
7
- export { startServer } from "./src/startServer.js"
8
- export { composeServices } from "./src/service_composition/service_composition.js"
9
- export { setupRoutes } from "./src/service_composition/routing.js"
10
- export { readRequestBody } from "./src/readRequestBody.js"
11
- export { fetchFileSystem } from "./src/fetch_filesystem.js"
12
- export {
13
- STOP_REASON_INTERNAL_ERROR,
14
- STOP_REASON_PROCESS_SIGHUP,
15
- STOP_REASON_PROCESS_SIGTERM,
16
- STOP_REASON_PROCESS_SIGINT,
17
- STOP_REASON_PROCESS_BEFORE_EXIT,
18
- STOP_REASON_PROCESS_EXIT,
19
- STOP_REASON_NOT_SPECIFIED,
20
- } from "./src/stopReasons.js"
21
-
22
- // CORS
23
- export {
24
- pluginCORS,
25
- jsenvAccessControlAllowedHeaders,
26
- jsenvAccessControlAllowedMethods,
27
- } from "./src/cors/plugin_cors.js"
28
-
29
- // server timings
30
- export { pluginServerTiming } from "./src/server_timing/plugin_server_timing.js"
31
- export { timeFunction, timeStart } from "./src/server_timing/timing_measure.js"
32
-
33
- // SSE
34
- export { createSSERoom } from "./src/sse/createSSERoom.js"
35
-
36
- // content-negotiation
37
- export { negotiateContentType } from "./src/content_negotiation/negotiateContentType.js"
38
- export { negotiateContentEncoding } from "./src/content_negotiation/negotiateContentEncoding.js"
39
- export { negotiateContentLanguage } from "./src/content_negotiation/negotiateContentLanguage.js"
40
- export { pluginContentNegotiationCheck } from "./src/content_negotiation/plugin_content_negotiation_check.js"
41
-
42
- // others
43
- export { fetchUrl } from "./src/fetch_url.js"
44
- export { serveDirectory } from "./src/serve_directory.js"
45
- export { fromFetchResponse } from "./src/from_fetch_response.js"
46
- export { composeTwoResponses } from "./src/internal/response_composition.js"
47
- export { pluginRessourceAliases } from "./src/ressource_aliases/plugin_ressource_aliases.js"
48
- export { pluginRequestWaitingCheck } from "./src/plugin_request_waiting_check.js"
49
- export { findFreePort } from "./src/internal/listen.js"
50
- export { urlToContentType } from "./src/urlToContentType.js"
package/src/fetch_url.js DELETED
@@ -1,112 +0,0 @@
1
- // https://github.com/node-fetch/node-fetch/blob/8c197f8982a238b3c345c64b17bfa92e16b4f7c4/src/response.js#L1
2
-
3
- import { Agent } from "node:https"
4
- import nodeFetch, { Response } from "node-fetch"
5
-
6
- import { fetchFileSystem } from "./fetch_filesystem.js"
7
- import { isFileHandle, fileHandleToReadableStream } from "./internal/body.js"
8
-
9
- export const fetchUrl = async (
10
- url,
11
- {
12
- signal = new AbortController().signal,
13
- ignoreHttpsError = false,
14
- canReadDirectory,
15
- contentTypeMap,
16
- cacheStrategy,
17
- method = "GET",
18
- headers = {},
19
- ...rest
20
- } = {},
21
- ) => {
22
- try {
23
- url = String(new URL(url))
24
- } catch (e) {
25
- throw new Error(
26
- `fetchUrl first argument must be an absolute url, received ${url}`,
27
- )
28
- }
29
-
30
- if (url.startsWith("file://")) {
31
- const responseProperties = await fetchFileSystem(url, {
32
- signal,
33
- method,
34
- headers,
35
- rootDirectoryUrl: "file://",
36
- cacheStrategy,
37
- canReadDirectory,
38
- contentTypeMap,
39
- ...rest,
40
- })
41
- const responseBody = responseProperties.body
42
-
43
- const response = new Response(
44
- typeof responseBody === "string"
45
- ? Buffer.from(responseBody)
46
- : isFileHandle(responseBody)
47
- ? fileHandleToReadableStream(responseBody)
48
- : responseBody,
49
- {
50
- url,
51
- status: responseProperties.status,
52
- statusText: responseProperties.statusText,
53
- headers: responseProperties.headers,
54
- },
55
- )
56
- return response
57
- }
58
-
59
- if (url.startsWith("data:")) {
60
- const { mediaType, base64Flag, data } = parseDataUrl(url)
61
- const body = base64Flag ? Buffer.from(data, "base64") : Buffer.from(data)
62
- const response = new Response(body, {
63
- url,
64
- status: 200,
65
- headers: {
66
- "content-type": mediaType,
67
- },
68
- })
69
- return response
70
- }
71
-
72
- const response = await nodeFetch(url, {
73
- signal,
74
- method,
75
- headers,
76
- ...(ignoreHttpsError && url.startsWith("https")
77
- ? {
78
- agent: () => {
79
- return new Agent({
80
- rejectUnauthorized: false,
81
- })
82
- },
83
- }
84
- : {}),
85
- ...rest,
86
- })
87
-
88
- return response
89
- }
90
-
91
- const parseDataUrl = (dataUrl) => {
92
- const afterDataProtocol = dataUrl.slice("data:".length)
93
- const commaIndex = afterDataProtocol.indexOf(",")
94
- const beforeComma = afterDataProtocol.slice(0, commaIndex)
95
-
96
- let mediaType
97
- let base64Flag
98
- if (beforeComma.endsWith(`;base64`)) {
99
- mediaType = beforeComma.slice(0, -`;base64`.length)
100
- base64Flag = true
101
- } else {
102
- mediaType = beforeComma
103
- base64Flag = false
104
- }
105
-
106
- const afterComma = afterDataProtocol.slice(commaIndex + 1)
107
- return {
108
- mediaType: mediaType === "" ? "text/plain;charset=US-ASCII" : mediaType,
109
- base64Flag,
110
- data: afterComma,
111
- }
112
- }
@@ -1,102 +0,0 @@
1
- export const jsenvContentTypeMap = {
2
- "application/javascript": {
3
- extensions: ["js", "cjs", "mjs", "ts", "jsx"],
4
- },
5
- "application/json": {
6
- extensions: ["json"],
7
- },
8
- "application/importmap+json": {
9
- extensions: ["importmap"],
10
- },
11
- "application/manifest+json": {
12
- extensions: ["webmanifest"],
13
- },
14
- "application/octet-stream": {},
15
- "application/pdf": {
16
- extensions: ["pdf"],
17
- },
18
- "application/xml": {
19
- extensions: ["xml"],
20
- },
21
- "application/x-gzip": {
22
- extensions: ["gz"],
23
- },
24
- "application/wasm": {
25
- extensions: ["wasm"],
26
- },
27
- "application/zip": {
28
- extensions: ["zip"],
29
- },
30
- "audio/basic": {
31
- extensions: ["au", "snd"],
32
- },
33
- "audio/mpeg": {
34
- extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"],
35
- },
36
- "audio/midi": {
37
- extensions: ["midi", "mid", "kar", "rmi"],
38
- },
39
- "audio/mp4": {
40
- extensions: ["m4a", "mp4a"],
41
- },
42
- "audio/ogg": {
43
- extensions: ["oga", "ogg", "spx"],
44
- },
45
- "audio/webm": {
46
- extensions: ["weba"],
47
- },
48
- "audio/x-wav": {
49
- extensions: ["wav"],
50
- },
51
- "font/ttf": {
52
- extensions: ["ttf"],
53
- },
54
- "font/woff": {
55
- extensions: ["woff"],
56
- },
57
- "font/woff2": {
58
- extensions: ["woff2"],
59
- },
60
- "image/png": {
61
- extensions: ["png"],
62
- },
63
- "image/gif": {
64
- extensions: ["gif"],
65
- },
66
- "image/jpeg": {
67
- extensions: ["jpg"],
68
- },
69
- "image/svg+xml": {
70
- extensions: ["svg", "svgz"],
71
- },
72
- "text/plain": {
73
- extensions: ["txt"],
74
- },
75
- "text/html": {
76
- extensions: ["html"],
77
- },
78
- "text/css": {
79
- extensions: ["css"],
80
- },
81
- "text/x-sass": {
82
- extensions: ["sass"],
83
- },
84
- "text/x-scss": {
85
- extensions: ["scss"],
86
- },
87
- "text/cache-manifest": {
88
- extensions: ["appcache"],
89
- },
90
- "video/mp4": {
91
- extensions: ["mp4", "mp4v", "mpg4"],
92
- },
93
- "video/mpeg": {
94
- extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"],
95
- },
96
- "video/ogg": {
97
- extensions: ["ogv"],
98
- },
99
- "video/webm": {
100
- extensions: ["webm"],
101
- },
102
- }
@@ -1,36 +0,0 @@
1
- // https://github.com/jshttp/mime-db/blob/master/src/apache-types.json
2
-
3
- import { extname } from "node:path"
4
-
5
- import { jsenvContentTypeMap } from "./jsenvContentTypeMap.js"
6
-
7
- export const urlToContentType = (
8
- url,
9
- contentTypeMap = jsenvContentTypeMap,
10
- contentTypeDefault = "application/octet-stream",
11
- ) => {
12
- if (typeof contentTypeMap !== "object") {
13
- throw new TypeError(
14
- `contentTypeMap must be an object, got ${contentTypeMap}`,
15
- )
16
- }
17
- const { pathname } = new URL(url)
18
-
19
- const extensionWithDot = extname(pathname)
20
-
21
- if (!extensionWithDot || extensionWithDot === ".") {
22
- return contentTypeDefault
23
- }
24
-
25
- const extension = extensionWithDot.slice(1)
26
- const availableContentTypes = Object.keys(contentTypeMap)
27
- const contentTypeForExtension = availableContentTypes.find(
28
- (contentTypeName) => {
29
- const contentType = contentTypeMap[contentTypeName]
30
- return (
31
- contentType.extensions && contentType.extensions.indexOf(extension) > -1
32
- )
33
- },
34
- )
35
- return contentTypeForExtension || contentTypeDefault
36
- }