@lango-project/lango-server 0.2.0 → 0.2.2
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/README.md +51 -0
- package/dist/.lango/runtime.mjs +8 -1
- package/dist/cli/.lango/runtime.mjs +8 -1
- package/dist/cli/error_details.mjs +45 -0
- package/dist/cli/error_details.mjs.map +1 -0
- package/dist/cli/server.mjs +64 -21
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +2 -0
- package/dist/cli/static_files.mjs.map +1 -1
- package/dist/cli/trace.mjs +53 -0
- package/dist/cli/trace.mjs.map +1 -0
- package/dist/error_details.mjs +45 -0
- package/dist/error_details.mjs.map +1 -0
- package/dist/request_identity.mjs +22 -0
- package/dist/request_identity.mjs.map +1 -0
- package/dist/runtime.mjs +23 -7
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +64 -21
- package/dist/server.mjs.map +1 -1
- package/dist/static_files.mjs +2 -0
- package/dist/static_files.mjs.map +1 -1
- package/dist/trace.mjs +53 -0
- package/dist/trace.mjs.map +1 -0
- package/dist/worker.mjs +1 -0
- package/dist/worker.mjs.map +1 -1
- package/package.json +2 -2
- package/src/error_details.lango +21 -0
- package/src/request_identity.lango +9 -0
- package/src/runtime.lango +23 -2
- package/src/server.lango +42 -5
- package/src/static_files.lango +3 -0
- package/src/trace.lango +23 -0
- package/src/worker.lango +1 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {
|
|
2
|
+
requireBoolean as __requireBoolean,
|
|
3
|
+
normalize as __normalize,
|
|
4
|
+
boundary as __boundary,
|
|
5
|
+
requireArity as __requireArity,
|
|
6
|
+
} from "./.lango/runtime.mjs";
|
|
7
|
+
|
|
8
|
+
export function requestIdentity(id, token) {
|
|
9
|
+
__requireArity(arguments.length, [0, 1], "requestIdentity");
|
|
10
|
+
id = __boundary(id);
|
|
11
|
+
token = __boundary(token);
|
|
12
|
+
let identity = `[${id}] [clientId=${__normalize(token.clientId)}]`;
|
|
13
|
+
for (const name of ["sessionId", "userId"]) {
|
|
14
|
+
let value = __normalize(token.get(name));
|
|
15
|
+
if (__requireBoolean(value !== null)) {
|
|
16
|
+
identity = `${identity} [${name}=${value}]`;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return identity;
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=request_identity.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request_identity.mjs","sources":["request_identity.lango"],"sourcesContent":["export requestIdentity(id, token)\n\nrequestIdentity(id, token)\n identity = \"[${id}] [clientId=${token.clientId?}]\"\n for [\"sessionId\", \"userId\"] as name\n value = token.get(name)\n if value != null\n identity = \"${identity} [${name}=${value}]\"\n return identity\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;"}
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { trace } from "./trace.mjs";
|
|
1
2
|
import { routePattern, matchPath, moreSpecific } from "./route_pattern.mjs";
|
|
2
3
|
import { ServerContext } from "./server_context.mjs";
|
|
3
4
|
import { Database } from "./database.mjs";
|
|
@@ -5,6 +6,8 @@ import { Token } from "./token.mjs";
|
|
|
5
6
|
import { Tokens } from "./tokens.mjs";
|
|
6
7
|
import { Response } from "./response.mjs";
|
|
7
8
|
import { HttpFailure } from "./http_failure.mjs";
|
|
9
|
+
import { requestIdentity } from "./request_identity.mjs";
|
|
10
|
+
import { errorDetails, errorMessage } from "./error_details.mjs";
|
|
8
11
|
import * as threads from "node:worker_threads";
|
|
9
12
|
import {
|
|
10
13
|
hostGlobal as __hostGlobal,
|
|
@@ -58,6 +61,7 @@ export class Runtime {
|
|
|
58
61
|
this.#database = new Database(definition.settings.database, definition.settings.root);
|
|
59
62
|
}
|
|
60
63
|
preload() {
|
|
64
|
+
trace(`Worker ${__normalize(threads.threadId)}: preparing database, middleware, routes and events`);
|
|
61
65
|
let definitions = __normalize(this.#definition.routes);
|
|
62
66
|
let pending = __normalize(this.#database.open());
|
|
63
67
|
if (__requireBoolean(__normalize(this.#definition.middlewares) !== null)) {
|
|
@@ -163,6 +167,7 @@ export class Runtime {
|
|
|
163
167
|
__requireArity(arguments.length, [0], "target");
|
|
164
168
|
spec = __boundary(spec);
|
|
165
169
|
let file = __normalize(spec.module);
|
|
170
|
+
trace(`Worker ${__normalize(threads.threadId)}: resolving ${file} export ${__normalize(spec.handler)}`);
|
|
166
171
|
if (__requireBoolean(__includes(file, __normalize(this.#modules)))) {
|
|
167
172
|
return __normalize(__hostGlobal(["Promise"]).resolve(exported(__normalize(this.#modules[file]), __normalize(spec.handler))));
|
|
168
173
|
}
|
|
@@ -212,10 +217,12 @@ export class Runtime {
|
|
|
212
217
|
claims = __normalize(this.#tokens.read(__normalize(__contextGet("request").headers.authorization)));
|
|
213
218
|
}
|
|
214
219
|
} catch (error) {
|
|
220
|
+
__normalize(__contextGet("log").warn(`[${__normalize(__contextGet("request").id)}] ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization rejected before handler: ${errorMessage(error)}`));
|
|
215
221
|
return failure(401, "Unauthorized");
|
|
216
222
|
}
|
|
217
223
|
let matched = this.#match(__normalize(__contextGet("request").path));
|
|
218
224
|
if (__requireBoolean(matched === null)) {
|
|
225
|
+
trace(`[${__normalize(__contextGet("request").id)}] No route matched ${__normalize(__contextGet("request").path)}`);
|
|
219
226
|
return failure(404, "RouteNotFound");
|
|
220
227
|
}
|
|
221
228
|
let route = __normalize(matched.route);
|
|
@@ -236,6 +243,7 @@ export class Runtime {
|
|
|
236
243
|
return failure(400, "InvalidPath");
|
|
237
244
|
}
|
|
238
245
|
__contextScope.push(__contextSet("token", new Token(claims)));
|
|
246
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Matched route ${matched.route.path}; fresh=${fresh}`);
|
|
239
247
|
__contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
|
|
240
248
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
241
249
|
const __contextScope = [];
|
|
@@ -275,6 +283,7 @@ export class Runtime {
|
|
|
275
283
|
if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
|
|
276
284
|
return null;
|
|
277
285
|
}
|
|
286
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Invoking handler; middleware=${__normalize(route.middleware) !== null}`);
|
|
278
287
|
let handler = __normalize(route.handler);
|
|
279
288
|
let middleware = __normalize(route.middleware);
|
|
280
289
|
if (__requireBoolean(middleware !== null)) {
|
|
@@ -313,6 +322,7 @@ export class Runtime {
|
|
|
313
322
|
}
|
|
314
323
|
return pollResponse;
|
|
315
324
|
}
|
|
325
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Handler completed; serializing response`);
|
|
316
326
|
let body = __normalize(__hostGlobal(["JSON"]).stringify(output));
|
|
317
327
|
if (__requireBoolean(!__requireBoolean(__isString(body)))) {
|
|
318
328
|
throw "Handler result is not JSON serializable";
|
|
@@ -324,33 +334,36 @@ export class Runtime {
|
|
|
324
334
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(task.internal) !== true) && __requireBoolean(__normalize(this.#definition.settings.requestEvent))) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
|
|
325
335
|
return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
|
|
326
336
|
}
|
|
337
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request completed status=${__normalize(result.status)}`);
|
|
327
338
|
return result;
|
|
328
339
|
return null;
|
|
329
340
|
} finally {
|
|
330
341
|
__contextRestore(__contextScope);
|
|
331
342
|
}
|
|
332
|
-
})(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3) => (error) => {
|
|
343
|
+
})(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4) => (error) => {
|
|
333
344
|
const __contextScope = [];
|
|
334
345
|
try {
|
|
335
346
|
__contextScope.push(__contextSet("server", __capturedContext0));
|
|
336
347
|
__contextScope.push(__contextSet("request", __capturedContext1));
|
|
337
348
|
__contextScope.push(__contextSet("log", __capturedContext2));
|
|
338
349
|
__contextScope.push(__contextSet("db", __capturedContext3));
|
|
350
|
+
__contextScope.push(__contextSet("token", __capturedContext4));
|
|
339
351
|
error = __boundary(error);
|
|
340
352
|
closeScope(__contextGet("db"), false);
|
|
341
353
|
if (__requireBoolean(__isKindof(error, HttpFailure))) {
|
|
342
354
|
return __normalize(error.result());
|
|
343
355
|
}
|
|
344
356
|
if (__requireBoolean(__requireBoolean(error === "TokenExpired") || __requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401)))) {
|
|
357
|
+
__normalize(__contextGet("log").warn(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization or validation rejected: Unauthorized`));
|
|
345
358
|
return failure(401, "Unauthorized");
|
|
346
359
|
}
|
|
347
|
-
__normalize(__contextGet("log").err(
|
|
360
|
+
__normalize(__contextGet("log").err(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request failed: ${errorDetails(error)}`));
|
|
348
361
|
return failure(500, "InternalServerError");
|
|
349
362
|
return null;
|
|
350
363
|
} finally {
|
|
351
364
|
__contextRestore(__contextScope);
|
|
352
365
|
}
|
|
353
|
-
})(__contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db")), [0], "closure")).finally(((__capturedContext0) => () => {
|
|
366
|
+
})(__contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db"), __contextGet("token")), [0], "closure")).finally(((__capturedContext0) => () => {
|
|
354
367
|
const __contextScope = [];
|
|
355
368
|
try {
|
|
356
369
|
__contextScope.push(__contextSet("db", __capturedContext0));
|
|
@@ -451,6 +464,7 @@ export class Runtime {
|
|
|
451
464
|
if (__requireBoolean(!__requireBoolean(__includes(name, __normalize(this.#events))))) {
|
|
452
465
|
return null;
|
|
453
466
|
}
|
|
467
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Running event ${name}`);
|
|
454
468
|
let handler = __normalize(this.#events[name]);
|
|
455
469
|
__normalize(threads.parentPort.postMessage({ kind: "event", id: __normalize(__contextGet("request").id) }));
|
|
456
470
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
@@ -550,7 +564,7 @@ export class Runtime {
|
|
|
550
564
|
__contextScope.push(__contextSet("token", new Token(claims, true)));
|
|
551
565
|
__contextScope.push(__contextSet("response", __normalize(__hostGlobal(["Object"]).freeze({ }))));
|
|
552
566
|
let metadata = { input: input, output: output, status: __normalize(result.status) };
|
|
553
|
-
__normalize(threads.parentPort.postMessage({ kind: "prepared", id: id, result: result }));
|
|
567
|
+
__normalize(threads.parentPort.postMessage({ kind: "prepared", logIdentity: requestIdentity(id, __contextGet("token")), id: id, result: result }));
|
|
554
568
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
555
569
|
const __contextScope = [];
|
|
556
570
|
try {
|
|
@@ -577,20 +591,22 @@ export class Runtime {
|
|
|
577
591
|
} finally {
|
|
578
592
|
__contextRestore(__contextScope);
|
|
579
593
|
}
|
|
580
|
-
})(__contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1) => (error) => {
|
|
594
|
+
})(__contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3) => (error) => {
|
|
581
595
|
const __contextScope = [];
|
|
582
596
|
try {
|
|
583
597
|
__contextScope.push(__contextSet("log", __capturedContext0));
|
|
584
598
|
__contextScope.push(__contextSet("db", __capturedContext1));
|
|
599
|
+
__contextScope.push(__contextSet("request", __capturedContext2));
|
|
600
|
+
__contextScope.push(__contextSet("token", __capturedContext3));
|
|
585
601
|
error = __boundary(error);
|
|
586
602
|
closeScope(__contextGet("db"), false);
|
|
587
|
-
__normalize(__contextGet("log").err("Request event failed
|
|
603
|
+
__normalize(__contextGet("log").err(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request event failed: ${errorDetails(error)}`));
|
|
588
604
|
return null;
|
|
589
605
|
return null;
|
|
590
606
|
} finally {
|
|
591
607
|
__contextRestore(__contextScope);
|
|
592
608
|
}
|
|
593
|
-
})(__contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity((ignored) => {
|
|
609
|
+
})(__contextGet("log"), __contextGet("db"), __contextGet("request"), __contextGet("token")), [0], "closure")).then(__withArity((ignored) => {
|
|
594
610
|
ignored = __boundary(ignored);
|
|
595
611
|
return result;
|
|
596
612
|
return null;
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n @serverContext = new ServerContext(definition.routes, refresh)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n return failure(401, \"Unauthorized\")\n log.err(\"[${request.id}] Request failed\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n closeScope(db, false)\n log.err(\"Request event failed\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA;;;;;;;;;;;AAuUA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\nimport \"./request_identity\"\n requestIdentity(id, token)\nimport \"./error_details\"\n errorDetails(error)\n errorMessage(error)\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n @serverContext = new ServerContext(definition.routes, refresh)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n trace(\"Worker ${threads.threadId}: preparing database, middleware, routes and events\")\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n trace(\"Worker ${threads.threadId}: resolving ${file} export ${spec.handler}\")\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n trace(\"${requestIdentity(request.id, token)} Matched route ${matched.route.path}; fresh=${fresh}\")\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n trace(\"${requestIdentity(request.id, token)} Invoking handler; middleware=${route.middleware != null}\")\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n trace(\"${requestIdentity(request.id, token)} Handler completed; serializing response\")\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n trace(\"${requestIdentity(request.id, token)} Request completed status=${result.status}\")\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n capture token\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n log.warn(\"${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized\")\n return failure(401, \"Unauthorized\")\n log.err(\"${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n trace(\"${requestIdentity(request.id, token)} Running event ${name}\")\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n logIdentity: requestIdentity(id, token)\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n capture request\n capture token\n closeScope(db, false)\n log.err(\"${requestIdentity(request.id, token)} Request event failed: ${errorDetails(error)}\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA;;;;;;;;;;;AAmVA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
package/dist/server.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { trace, responseLog } from "./trace.mjs";
|
|
1
2
|
import { LongpollBroker } from "./longpoll_broker.mjs";
|
|
2
3
|
import { LongpollSession } from "./longpoll_session.mjs";
|
|
3
4
|
import { prepareDatabase } from "./database.mjs";
|
|
5
|
+
import { errorDetails } from "./error_details.mjs";
|
|
4
6
|
import { deployment } from "./options.mjs";
|
|
5
7
|
import { Routes } from "./routes.mjs";
|
|
6
8
|
import { BodyReader } from "./body_reader.mjs";
|
|
@@ -118,6 +120,7 @@ export class Server {
|
|
|
118
120
|
}
|
|
119
121
|
#launch() {
|
|
120
122
|
let settings = __normalize(this.#definition.settings);
|
|
123
|
+
trace(`Server starting: ${__normalize(settings.root)}; workers=${__normalize(settings.workers)}`);
|
|
121
124
|
if (__requireBoolean(__normalize(settings.static) !== null)) {
|
|
122
125
|
try {
|
|
123
126
|
this.#static = new StaticFiles(__normalize(settings.static));
|
|
@@ -146,7 +149,7 @@ export class Server {
|
|
|
146
149
|
try {
|
|
147
150
|
error = __boundary(error);
|
|
148
151
|
__normalize(this.#ready.reject(error));
|
|
149
|
-
__normalize(__contextGet("log").err(
|
|
152
|
+
__normalize(__contextGet("log").err(`Worker pool error: ${errorDetails(error)}`));
|
|
150
153
|
return null;
|
|
151
154
|
} finally {
|
|
152
155
|
__contextRestore(__contextScope);
|
|
@@ -227,6 +230,7 @@ export class Server {
|
|
|
227
230
|
let record = __normalize(this.#tasks[__normalize(message.id)]);
|
|
228
231
|
if (__requireBoolean(__normalize(message.kind) === "prepared")) {
|
|
229
232
|
record.result = __normalize(message.result);
|
|
233
|
+
record.logIdentity = __normalize(message.logIdentity);
|
|
230
234
|
this.#resetDeadline(record, __normalize(this.#definition.settings.eventTimeoutMs));
|
|
231
235
|
}
|
|
232
236
|
if (__requireBoolean(__normalize(message.kind) === "event")) {
|
|
@@ -273,6 +277,7 @@ export class Server {
|
|
|
273
277
|
__requireArity(arguments.length, [0, 1], "trackResponse");
|
|
274
278
|
req = __boundary(req);
|
|
275
279
|
res = __boundary(res);
|
|
280
|
+
let target = __normalize(__normalize(req.url.split("?"))[0]);
|
|
276
281
|
for (const record of __normalize(this.#connections)) {
|
|
277
282
|
if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
|
|
278
283
|
record.active = __numericAdd(__normalize(record.active), 1);
|
|
@@ -282,6 +287,11 @@ export class Server {
|
|
|
282
287
|
return null;
|
|
283
288
|
}
|
|
284
289
|
state.done = true;
|
|
290
|
+
if (__requireBoolean(__normalize(res.writableFinished))) {
|
|
291
|
+
responseLog(__normalize(res.langoRequestId), __normalize(req.method), target, __normalize(res.statusCode));
|
|
292
|
+
} else {
|
|
293
|
+
trace(`HTTP ${__normalize(req.method)} ${target} connection closed before response completed`);
|
|
294
|
+
}
|
|
285
295
|
record.active = __finite(__normalize(record.active) - 1);
|
|
286
296
|
if (__requireBoolean(__requireBoolean(__normalize(this.#state) === "closing") && __requireBoolean(__normalize(record.active) === 0))) {
|
|
287
297
|
__normalize(record.socket.end());
|
|
@@ -310,6 +320,7 @@ export class Server {
|
|
|
310
320
|
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
311
321
|
return rejectHttp(req, res, 503, "Unavailable");
|
|
312
322
|
}
|
|
323
|
+
trace(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])}`);
|
|
313
324
|
if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
|
|
314
325
|
let failed = __withArity((status, code) => {
|
|
315
326
|
status = __boundary(status);
|
|
@@ -377,10 +388,16 @@ export class Server {
|
|
|
377
388
|
return null;
|
|
378
389
|
return null;
|
|
379
390
|
}, [0], "closure")).catch(__withArity((error) => {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
391
|
+
const __contextScope = [];
|
|
392
|
+
try {
|
|
393
|
+
error = __boundary(error);
|
|
394
|
+
__normalize(__contextGet("log").err(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])} request failed: ${errorDetails(error)}`));
|
|
395
|
+
this.#send(res, failure(500, "InternalServerError"));
|
|
396
|
+
return null;
|
|
397
|
+
return null;
|
|
398
|
+
} finally {
|
|
399
|
+
__contextRestore(__contextScope);
|
|
400
|
+
}
|
|
384
401
|
}, [0], "closure"));
|
|
385
402
|
return null;
|
|
386
403
|
}
|
|
@@ -457,6 +474,8 @@ export class Server {
|
|
|
457
474
|
return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "Unavailable")));
|
|
458
475
|
}
|
|
459
476
|
let id = __normalize(crypto.randomUUID());
|
|
477
|
+
res.langoRequestId = id;
|
|
478
|
+
trace(`[${id}] Queued request ${__normalize(req.method)} ${__normalize(req.url)}`);
|
|
460
479
|
let record = { id: id, task: { authorize: authorize, pollResult: pollResult, body: body, request: { id: id, method: __normalize(req.method), path: __normalize(req.url), headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(req.headers))), remoteAddress: req.socket.remoteAddress } }, completed: __normalize(__hostGlobal(["Promise"]).withResolvers()), controller: new (__hostGlobal(["AbortController"]))(), started: false, result: null, expired: false, deadline: __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __normalize(settings.requestTimeoutMs)), timer: null };
|
|
461
480
|
if (__requireBoolean(token !== null)) {
|
|
462
481
|
record.task.request.headers.authorization = `Bearer ${token}`;
|
|
@@ -516,6 +535,7 @@ export class Server {
|
|
|
516
535
|
let record = __normalize(this.#waiting.shift());
|
|
517
536
|
record.started = true;
|
|
518
537
|
this.#active = __numericAdd(__normalize(this.#active), 1);
|
|
538
|
+
trace(`[${__normalize(record.id)}] Dispatching to worker`);
|
|
519
539
|
let pending = __normalize(this.#pool.run(__normalize(record.task), { signal: record.controller.signal }));
|
|
520
540
|
this.#settle(record, pending);
|
|
521
541
|
}
|
|
@@ -536,7 +556,7 @@ export class Server {
|
|
|
536
556
|
try {
|
|
537
557
|
error = __boundary(error);
|
|
538
558
|
if (__requireBoolean(__normalize(record.result) !== null)) {
|
|
539
|
-
__normalize(__contextGet("log").err(
|
|
559
|
+
__normalize(__contextGet("log").err(`${__normalize(record.logIdentity)} Request event interrupted; preserving prepared result`));
|
|
540
560
|
}
|
|
541
561
|
this.#finish(record, __normalize(record.result), error);
|
|
542
562
|
return null;
|
|
@@ -657,6 +677,7 @@ export class Server {
|
|
|
657
677
|
__requireArity(arguments.length, [0, 1], "send");
|
|
658
678
|
res = __boundary(res);
|
|
659
679
|
result = __boundary(result);
|
|
680
|
+
trace(`HTTP response status=${__normalize(result.status)}`);
|
|
660
681
|
if (__requireBoolean(__normalize(this.#state) === "closing")) {
|
|
661
682
|
result.headers.connection = "close";
|
|
662
683
|
}
|
|
@@ -698,20 +719,26 @@ function failure(status, code) {
|
|
|
698
719
|
}
|
|
699
720
|
|
|
700
721
|
function write(res, result) {
|
|
701
|
-
|
|
702
|
-
res = __boundary(res);
|
|
703
|
-
result = __boundary(result);
|
|
704
|
-
if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
|
|
705
|
-
return null;
|
|
706
|
-
}
|
|
722
|
+
const __contextScope = [];
|
|
707
723
|
try {
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
__normalize(res.
|
|
724
|
+
__requireArity(arguments.length, [0, 1], "write");
|
|
725
|
+
res = __boundary(res);
|
|
726
|
+
result = __boundary(result);
|
|
727
|
+
if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
try {
|
|
731
|
+
__normalize(res.writeHead(__normalize(result.status), __normalize(result.headers)));
|
|
732
|
+
__normalize(res.end(__normalize(result.body)));
|
|
733
|
+
} catch (error) {
|
|
734
|
+
__normalize(__contextGet("log").err(`[${__normalize(res.langoRequestId)}] Response write failed: ${errorDetails(error)}`));
|
|
735
|
+
__normalize(res.destroy());
|
|
736
|
+
}
|
|
737
|
+
return null;
|
|
738
|
+
return null;
|
|
739
|
+
} finally {
|
|
740
|
+
__contextRestore(__contextScope);
|
|
712
741
|
}
|
|
713
|
-
return null;
|
|
714
|
-
return null;
|
|
715
742
|
}
|
|
716
743
|
|
|
717
744
|
function rejectHttp(req, res, status, code) {
|
|
@@ -733,10 +760,26 @@ function rejectHttp(req, res, status, code) {
|
|
|
733
760
|
export function main(args) {
|
|
734
761
|
__requireArity(arguments.length, [0], "main");
|
|
735
762
|
args = __boundary(args);
|
|
736
|
-
|
|
737
|
-
|
|
763
|
+
let directory = null;
|
|
764
|
+
let verbose = false;
|
|
765
|
+
for (const arg of args) {
|
|
766
|
+
if (__requireBoolean(arg === "--verbose")) {
|
|
767
|
+
verbose = true;
|
|
768
|
+
} else {
|
|
769
|
+
if (__requireBoolean(__requireBoolean(__normalize(arg.startsWith("--"))) || __requireBoolean(directory !== null))) {
|
|
770
|
+
throw "Usage: lango-server <application-directory> [--verbose]";
|
|
771
|
+
}
|
|
772
|
+
directory = arg;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
if (__requireBoolean(directory === null)) {
|
|
776
|
+
throw "Usage: lango-server <application-directory> [--verbose]";
|
|
777
|
+
}
|
|
778
|
+
if (__requireBoolean(verbose)) {
|
|
779
|
+
__hostGlobal(["process"]).env.LANGO_VERBOSE = "1";
|
|
738
780
|
}
|
|
739
|
-
|
|
781
|
+
trace(`Loading server configuration: ${directory}`);
|
|
782
|
+
let server = new Server(directory);
|
|
740
783
|
let stop = () => {
|
|
741
784
|
return __normalize(server.close()).catch(__withArity((error) => {
|
|
742
785
|
const __contextScope = [];
|
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n if state.done\n return null\n state.done = true\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"[${record.id}] Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n if args.length != 1\n throw \"Usage: lango-server <application-directory>\"\n server = new Server(args[0])\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAoGA;;;;;;;;;;;;;;;;;AAgXA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\n responseLog(id, method, path, status)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n trace(\"Server starting: ${settings.root}; workers=${settings.workers}\")\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error: ${errorDetails(error)}\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n record.logIdentity = message.logIdentity\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n target = req.url.split(\"?\")[0]\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n capture req\n capture res\n capture target\n if state.done\n return null\n state.done = true\n if res.writableFinished\n responseLog(res.langoRequestId, req.method, target, res.statusCode)\n else\n trace(\"HTTP ${req.method} ${target} connection closed before response completed\")\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n trace(\"HTTP ${req.method} ${req.url.split('?')[0]}\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture req\n context log\n log.err(\"HTTP ${req.method} ${req.url.split('?')[0]} request failed: ${errorDetails(error)}\")\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n res.langoRequestId = id\n trace(\"[${id}] Queued request ${req.method} ${req.url}\")\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n trace(\"[${record.id}] Dispatching to worker\")\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"${record.logIdentity} Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n trace(\"HTTP response status=${result.status}\")\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n context log\n log.err(\"[${res.langoRequestId}] Response write failed: ${errorDetails(error)}\")\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n directory = null\n verbose = false\n for args as arg\n if arg == \"--verbose\"\n verbose = true\n else\n if arg.startsWith(\"--\") or directory != null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n directory = arg\n if directory == null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n if verbose\n process.env.LANGO_VERBOSE = \"1\"\n trace(\"Loading server configuration: ${directory}\")\n server = new Server(directory)\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;"}
|
package/dist/static_files.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { trace } from "./trace.mjs";
|
|
1
2
|
import * as fs from "node:fs";
|
|
2
3
|
import * as path from "node:path";
|
|
3
4
|
import * as files from "serve-static";
|
|
@@ -87,6 +88,7 @@ export class StaticFiles {
|
|
|
87
88
|
if (__requireBoolean(runtime)) {
|
|
88
89
|
serve = __normalize(this.#runtime);
|
|
89
90
|
}
|
|
91
|
+
trace(`Static ${__normalize(req.method)} ${pathname}: directory=${__normalize(this.#settings.directory)}; index=${__normalize(this.#settings.index)}; runtime=${runtime}`);
|
|
90
92
|
__call(serve, req, res, done);
|
|
91
93
|
return null;
|
|
92
94
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n trace(\"Static ${req.method} ${pathname}: directory=${@settings.directory}; index=${@settings.index}; runtime=${runtime}\")\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|