@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
package/README.md
CHANGED
|
@@ -369,6 +369,14 @@ in the worker. Request events observe that final serialized result. Middleware,
|
|
|
369
369
|
handler and serialization errors follow the existing error/token behavior;
|
|
370
370
|
request/event deadlines and SQL transaction cleanup still apply.
|
|
371
371
|
|
|
372
|
+
Unexpected failures are logged through `context log` with the request ID, the
|
|
373
|
+
request token's `clientId`, and optional `sessionId` and `userId` claims when
|
|
374
|
+
non-null. The original error message and stack trace are included when available. Workers enable Node source
|
|
375
|
+
maps so compiled application errors point to their `.lango` source when matching
|
|
376
|
+
`.mjs.map` files are deployed. Keep these files alongside the compiled modules.
|
|
377
|
+
HTTP clients receive the generic `InternalServerError` response; internal error
|
|
378
|
+
messages and stack traces remain in the server logs.
|
|
379
|
+
|
|
372
380
|
## Configuration
|
|
373
381
|
|
|
374
382
|
```xml
|
|
@@ -840,3 +848,46 @@ There is no automatic retry.
|
|
|
840
848
|
|
|
841
849
|
Request auditing runs once for the physical batch response, not once per internal
|
|
842
850
|
item; an internal result cannot replace the prepared outer HTTP reply.
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
## Verbose diagnostics
|
|
854
|
+
|
|
855
|
+
Run `lango-server <application-directory> --verbose` (or `npm start -- --verbose`
|
|
856
|
+
in a generated UI application). The flag can appear before or after the directory.
|
|
857
|
+
It enables `LANGO_VERBOSE=1` for the server process and its workers. Normal startup
|
|
858
|
+
keeps debug logs disabled. `LANGO_VERBOSE=1` also enables diagnostics for a server
|
|
859
|
+
started through its library API.
|
|
860
|
+
|
|
861
|
+
Verbose logs show configuration loading, worker module/export resolution, HTTP
|
|
862
|
+
request paths, queue/dispatch stages, matched routes, handler invocation and
|
|
863
|
+
response status. Verified request identity is included once available. Request
|
|
864
|
+
bodies, authorization headers, signing keys and raw JWTs are not logged.
|
|
865
|
+
|
|
866
|
+
```lango
|
|
867
|
+
context log
|
|
868
|
+
if log.verbose?
|
|
869
|
+
log.debug("Preparing optional diagnostic details")
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
`log.verbose?` is readonly. `debug()` is filtered automatically, while `info()`,
|
|
873
|
+
`warn()` and `err()` remain enabled. Rebuild application modules with Lango JS
|
|
874
|
+
0.1.17 or newer to give their default log objects the same verbose behavior.
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
For browser startup, GET / serves the static HTML shell; it does not invoke an
|
|
878
|
+
application handler. Browser modules subsequently POST / to bootstrap and POST
|
|
879
|
+
/index (or the selected page path) to request the view. Verbose static logs show
|
|
880
|
+
the serving directory and HTTP completion status. Invalid JWTs are rejected
|
|
881
|
+
before handler invocation, with a verbose diagnostic identifying that stage.
|
|
882
|
+
A client with an expired/replaced stored token can therefore load HTML but fail
|
|
883
|
+
its bootstrap POST with 401 before any application log statement runs.
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
HTTP failures are visible without verbose mode: completed 4xx responses use
|
|
887
|
+
`log.warn()` and completed 5xx responses use `log.err()`, with the method, URL
|
|
888
|
+
path, status and dispatched request ID where available. Successful responses
|
|
889
|
+
remain debug-only. JWT rejection reasons are warnings even before a handler is
|
|
890
|
+
invoked; raw JWTs and unverified claims are not logged as client identity.
|
|
891
|
+
Expired or invalid tokens can occur during ordinary session lifetimes, but a
|
|
892
|
+
failed startup is still a logged rejection. Detailed internal failures retain
|
|
893
|
+
their existing exception and identity logs.
|
package/dist/.lango/runtime.mjs
CHANGED
|
@@ -100,6 +100,9 @@ function postgresQuery(sql, parameters) {
|
|
|
100
100
|
return { text: text + sql.slice(at), values };
|
|
101
101
|
}
|
|
102
102
|
export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
|
|
103
|
+
const loggingStore = Symbol.for("lango.logging");
|
|
104
|
+
const logging = globalThis[loggingStore] ?? { verbose: false };
|
|
105
|
+
globalThis[loggingStore] = logging;
|
|
103
106
|
const contextStore = Symbol.for("lango.contexts");
|
|
104
107
|
const contexts = globalThis[contextStore] ?? new Map();
|
|
105
108
|
globalThis[contextStore] = contexts;
|
|
@@ -114,6 +117,8 @@ export class RuntimeConfigurationError extends Error {
|
|
|
114
117
|
export function configure(options = {}) {
|
|
115
118
|
if (options === null || typeof options !== "object" || Array.isArray(options))
|
|
116
119
|
throw new RuntimeConfigurationError("runtime configuration must be an object");
|
|
120
|
+
if (options.verbose !== undefined && typeof options.verbose !== "boolean")
|
|
121
|
+
throw new RuntimeConfigurationError("runtime verbose must be boolean");
|
|
117
122
|
const nextCatalog = options.catalog ?? {};
|
|
118
123
|
const nextOutput = options.output ?? null;
|
|
119
124
|
const nextDatabase = options.database_adapter ?? null;
|
|
@@ -135,6 +140,7 @@ export function configure(options = {}) {
|
|
|
135
140
|
} catch (error) {
|
|
136
141
|
throw new RuntimeConfigurationError(error.message);
|
|
137
142
|
}
|
|
143
|
+
if (options.verbose !== undefined) logging.verbose = options.verbose;
|
|
138
144
|
defaultI18n = nextI18n;
|
|
139
145
|
output = nextOutput;
|
|
140
146
|
if (database !== null) failedTransactions.delete(database);
|
|
@@ -341,7 +347,8 @@ export function println(value) {
|
|
|
341
347
|
}
|
|
342
348
|
|
|
343
349
|
const defaultLog = Object.freeze({
|
|
344
|
-
|
|
350
|
+
get verbose() { return logging.verbose || process.env.LANGO_VERBOSE === "1"; },
|
|
351
|
+
debug(value) { if (!defaultLog.verbose) return null; return writeLog(process.stdout, "DEBUG", value); },
|
|
345
352
|
info(value) { return writeLog(process.stdout, "INFO", value); },
|
|
346
353
|
warn(value) { return writeLog(process.stderr, "WARN", value); },
|
|
347
354
|
err(value) { return writeLog(process.stderr, "ERROR", value); },
|
|
@@ -100,6 +100,9 @@ function postgresQuery(sql, parameters) {
|
|
|
100
100
|
return { text: text + sql.slice(at), values };
|
|
101
101
|
}
|
|
102
102
|
export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
|
|
103
|
+
const loggingStore = Symbol.for("lango.logging");
|
|
104
|
+
const logging = globalThis[loggingStore] ?? { verbose: false };
|
|
105
|
+
globalThis[loggingStore] = logging;
|
|
103
106
|
const contextStore = Symbol.for("lango.contexts");
|
|
104
107
|
const contexts = globalThis[contextStore] ?? new Map();
|
|
105
108
|
globalThis[contextStore] = contexts;
|
|
@@ -114,6 +117,8 @@ export class RuntimeConfigurationError extends Error {
|
|
|
114
117
|
export function configure(options = {}) {
|
|
115
118
|
if (options === null || typeof options !== "object" || Array.isArray(options))
|
|
116
119
|
throw new RuntimeConfigurationError("runtime configuration must be an object");
|
|
120
|
+
if (options.verbose !== undefined && typeof options.verbose !== "boolean")
|
|
121
|
+
throw new RuntimeConfigurationError("runtime verbose must be boolean");
|
|
117
122
|
const nextCatalog = options.catalog ?? {};
|
|
118
123
|
const nextOutput = options.output ?? null;
|
|
119
124
|
const nextDatabase = options.database_adapter ?? null;
|
|
@@ -135,6 +140,7 @@ export function configure(options = {}) {
|
|
|
135
140
|
} catch (error) {
|
|
136
141
|
throw new RuntimeConfigurationError(error.message);
|
|
137
142
|
}
|
|
143
|
+
if (options.verbose !== undefined) logging.verbose = options.verbose;
|
|
138
144
|
defaultI18n = nextI18n;
|
|
139
145
|
output = nextOutput;
|
|
140
146
|
if (database !== null) failedTransactions.delete(database);
|
|
@@ -341,7 +347,8 @@ export function println(value) {
|
|
|
341
347
|
}
|
|
342
348
|
|
|
343
349
|
const defaultLog = Object.freeze({
|
|
344
|
-
|
|
350
|
+
get verbose() { return logging.verbose || process.env.LANGO_VERBOSE === "1"; },
|
|
351
|
+
debug(value) { if (!defaultLog.verbose) return null; return writeLog(process.stdout, "DEBUG", value); },
|
|
345
352
|
info(value) { return writeLog(process.stdout, "INFO", value); },
|
|
346
353
|
warn(value) { return writeLog(process.stderr, "WARN", value); },
|
|
347
354
|
err(value) { return writeLog(process.stderr, "ERROR", value); },
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isNumber as __isNumber,
|
|
3
|
+
isString as __isString,
|
|
4
|
+
isBool as __isBool,
|
|
5
|
+
isObject as __isObject,
|
|
6
|
+
isArray as __isArray,
|
|
7
|
+
requireBoolean as __requireBoolean,
|
|
8
|
+
normalize as __normalize,
|
|
9
|
+
boundary as __boundary,
|
|
10
|
+
requireArity as __requireArity,
|
|
11
|
+
} from "./.lango/runtime.mjs";
|
|
12
|
+
|
|
13
|
+
export function errorDetails(error) {
|
|
14
|
+
__requireArity(arguments.length, [0], "errorDetails");
|
|
15
|
+
error = __boundary(error);
|
|
16
|
+
if (__requireBoolean(__isObject(error))) {
|
|
17
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.stack))) && __requireBoolean(__normalize(error.stack) !== ""))) {
|
|
18
|
+
return __normalize(error.stack);
|
|
19
|
+
}
|
|
20
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
|
|
21
|
+
return __normalize(error.message);
|
|
22
|
+
}
|
|
23
|
+
if (__requireBoolean(__isString(__normalize(error.code)))) {
|
|
24
|
+
return __normalize(error.code);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return `${error}`;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function errorMessage(error) {
|
|
32
|
+
__requireArity(arguments.length, [0], "errorMessage");
|
|
33
|
+
error = __boundary(error);
|
|
34
|
+
if (__requireBoolean(__isObject(error))) {
|
|
35
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
|
|
36
|
+
return __normalize(error.message);
|
|
37
|
+
}
|
|
38
|
+
if (__requireBoolean(__isString(__normalize(error.code)))) {
|
|
39
|
+
return __normalize(error.code);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return `${error}`;
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=error_details.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
|
package/dist/cli/server.mjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { trace, responseLog } from "./trace.mjs";
|
|
2
3
|
import { LongpollBroker } from "./longpoll_broker.mjs";
|
|
3
4
|
import { LongpollSession } from "./longpoll_session.mjs";
|
|
4
5
|
import { prepareDatabase } from "./database.mjs";
|
|
6
|
+
import { errorDetails } from "./error_details.mjs";
|
|
5
7
|
import { deployment } from "./options.mjs";
|
|
6
8
|
import { Routes } from "./routes.mjs";
|
|
7
9
|
import { BodyReader } from "./body_reader.mjs";
|
|
@@ -119,6 +121,7 @@ export class Server {
|
|
|
119
121
|
}
|
|
120
122
|
#launch() {
|
|
121
123
|
let settings = __normalize(this.#definition.settings);
|
|
124
|
+
trace(`Server starting: ${__normalize(settings.root)}; workers=${__normalize(settings.workers)}`);
|
|
122
125
|
if (__requireBoolean(__normalize(settings.static) !== null)) {
|
|
123
126
|
try {
|
|
124
127
|
this.#static = new StaticFiles(__normalize(settings.static));
|
|
@@ -147,7 +150,7 @@ export class Server {
|
|
|
147
150
|
try {
|
|
148
151
|
error = __boundary(error);
|
|
149
152
|
__normalize(this.#ready.reject(error));
|
|
150
|
-
__normalize(__contextGet("log").err(
|
|
153
|
+
__normalize(__contextGet("log").err(`Worker pool error: ${errorDetails(error)}`));
|
|
151
154
|
return null;
|
|
152
155
|
} finally {
|
|
153
156
|
__contextRestore(__contextScope);
|
|
@@ -228,6 +231,7 @@ export class Server {
|
|
|
228
231
|
let record = __normalize(this.#tasks[__normalize(message.id)]);
|
|
229
232
|
if (__requireBoolean(__normalize(message.kind) === "prepared")) {
|
|
230
233
|
record.result = __normalize(message.result);
|
|
234
|
+
record.logIdentity = __normalize(message.logIdentity);
|
|
231
235
|
this.#resetDeadline(record, __normalize(this.#definition.settings.eventTimeoutMs));
|
|
232
236
|
}
|
|
233
237
|
if (__requireBoolean(__normalize(message.kind) === "event")) {
|
|
@@ -274,6 +278,7 @@ export class Server {
|
|
|
274
278
|
__requireArity(arguments.length, [0, 1], "trackResponse");
|
|
275
279
|
req = __boundary(req);
|
|
276
280
|
res = __boundary(res);
|
|
281
|
+
let target = __normalize(__normalize(req.url.split("?"))[0]);
|
|
277
282
|
for (const record of __normalize(this.#connections)) {
|
|
278
283
|
if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
|
|
279
284
|
record.active = __numericAdd(__normalize(record.active), 1);
|
|
@@ -283,6 +288,11 @@ export class Server {
|
|
|
283
288
|
return null;
|
|
284
289
|
}
|
|
285
290
|
state.done = true;
|
|
291
|
+
if (__requireBoolean(__normalize(res.writableFinished))) {
|
|
292
|
+
responseLog(__normalize(res.langoRequestId), __normalize(req.method), target, __normalize(res.statusCode));
|
|
293
|
+
} else {
|
|
294
|
+
trace(`HTTP ${__normalize(req.method)} ${target} connection closed before response completed`);
|
|
295
|
+
}
|
|
286
296
|
record.active = __finite(__normalize(record.active) - 1);
|
|
287
297
|
if (__requireBoolean(__requireBoolean(__normalize(this.#state) === "closing") && __requireBoolean(__normalize(record.active) === 0))) {
|
|
288
298
|
__normalize(record.socket.end());
|
|
@@ -311,6 +321,7 @@ export class Server {
|
|
|
311
321
|
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
312
322
|
return rejectHttp(req, res, 503, "Unavailable");
|
|
313
323
|
}
|
|
324
|
+
trace(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])}`);
|
|
314
325
|
if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
|
|
315
326
|
let failed = __withArity((status, code) => {
|
|
316
327
|
status = __boundary(status);
|
|
@@ -378,10 +389,16 @@ export class Server {
|
|
|
378
389
|
return null;
|
|
379
390
|
return null;
|
|
380
391
|
}, [0], "closure")).catch(__withArity((error) => {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
392
|
+
const __contextScope = [];
|
|
393
|
+
try {
|
|
394
|
+
error = __boundary(error);
|
|
395
|
+
__normalize(__contextGet("log").err(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])} request failed: ${errorDetails(error)}`));
|
|
396
|
+
this.#send(res, failure(500, "InternalServerError"));
|
|
397
|
+
return null;
|
|
398
|
+
return null;
|
|
399
|
+
} finally {
|
|
400
|
+
__contextRestore(__contextScope);
|
|
401
|
+
}
|
|
385
402
|
}, [0], "closure"));
|
|
386
403
|
return null;
|
|
387
404
|
}
|
|
@@ -458,6 +475,8 @@ export class Server {
|
|
|
458
475
|
return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "Unavailable")));
|
|
459
476
|
}
|
|
460
477
|
let id = __normalize(crypto.randomUUID());
|
|
478
|
+
res.langoRequestId = id;
|
|
479
|
+
trace(`[${id}] Queued request ${__normalize(req.method)} ${__normalize(req.url)}`);
|
|
461
480
|
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 };
|
|
462
481
|
if (__requireBoolean(token !== null)) {
|
|
463
482
|
record.task.request.headers.authorization = `Bearer ${token}`;
|
|
@@ -517,6 +536,7 @@ export class Server {
|
|
|
517
536
|
let record = __normalize(this.#waiting.shift());
|
|
518
537
|
record.started = true;
|
|
519
538
|
this.#active = __numericAdd(__normalize(this.#active), 1);
|
|
539
|
+
trace(`[${__normalize(record.id)}] Dispatching to worker`);
|
|
520
540
|
let pending = __normalize(this.#pool.run(__normalize(record.task), { signal: record.controller.signal }));
|
|
521
541
|
this.#settle(record, pending);
|
|
522
542
|
}
|
|
@@ -537,7 +557,7 @@ export class Server {
|
|
|
537
557
|
try {
|
|
538
558
|
error = __boundary(error);
|
|
539
559
|
if (__requireBoolean(__normalize(record.result) !== null)) {
|
|
540
|
-
__normalize(__contextGet("log").err(
|
|
560
|
+
__normalize(__contextGet("log").err(`${__normalize(record.logIdentity)} Request event interrupted; preserving prepared result`));
|
|
541
561
|
}
|
|
542
562
|
this.#finish(record, __normalize(record.result), error);
|
|
543
563
|
return null;
|
|
@@ -658,6 +678,7 @@ export class Server {
|
|
|
658
678
|
__requireArity(arguments.length, [0, 1], "send");
|
|
659
679
|
res = __boundary(res);
|
|
660
680
|
result = __boundary(result);
|
|
681
|
+
trace(`HTTP response status=${__normalize(result.status)}`);
|
|
661
682
|
if (__requireBoolean(__normalize(this.#state) === "closing")) {
|
|
662
683
|
result.headers.connection = "close";
|
|
663
684
|
}
|
|
@@ -699,20 +720,26 @@ function failure(status, code) {
|
|
|
699
720
|
}
|
|
700
721
|
|
|
701
722
|
function write(res, result) {
|
|
702
|
-
|
|
703
|
-
res = __boundary(res);
|
|
704
|
-
result = __boundary(result);
|
|
705
|
-
if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
|
|
706
|
-
return null;
|
|
707
|
-
}
|
|
723
|
+
const __contextScope = [];
|
|
708
724
|
try {
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
__normalize(res.
|
|
725
|
+
__requireArity(arguments.length, [0, 1], "write");
|
|
726
|
+
res = __boundary(res);
|
|
727
|
+
result = __boundary(result);
|
|
728
|
+
if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
|
|
729
|
+
return null;
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
__normalize(res.writeHead(__normalize(result.status), __normalize(result.headers)));
|
|
733
|
+
__normalize(res.end(__normalize(result.body)));
|
|
734
|
+
} catch (error) {
|
|
735
|
+
__normalize(__contextGet("log").err(`[${__normalize(res.langoRequestId)}] Response write failed: ${errorDetails(error)}`));
|
|
736
|
+
__normalize(res.destroy());
|
|
737
|
+
}
|
|
738
|
+
return null;
|
|
739
|
+
return null;
|
|
740
|
+
} finally {
|
|
741
|
+
__contextRestore(__contextScope);
|
|
713
742
|
}
|
|
714
|
-
return null;
|
|
715
|
-
return null;
|
|
716
743
|
}
|
|
717
744
|
|
|
718
745
|
function rejectHttp(req, res, status, code) {
|
|
@@ -734,10 +761,26 @@ function rejectHttp(req, res, status, code) {
|
|
|
734
761
|
export function main(args) {
|
|
735
762
|
__requireArity(arguments.length, [0], "main");
|
|
736
763
|
args = __boundary(args);
|
|
737
|
-
|
|
738
|
-
|
|
764
|
+
let directory = null;
|
|
765
|
+
let verbose = false;
|
|
766
|
+
for (const arg of args) {
|
|
767
|
+
if (__requireBoolean(arg === "--verbose")) {
|
|
768
|
+
verbose = true;
|
|
769
|
+
} else {
|
|
770
|
+
if (__requireBoolean(__requireBoolean(__normalize(arg.startsWith("--"))) || __requireBoolean(directory !== null))) {
|
|
771
|
+
throw "Usage: lango-server <application-directory> [--verbose]";
|
|
772
|
+
}
|
|
773
|
+
directory = arg;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (__requireBoolean(directory === null)) {
|
|
777
|
+
throw "Usage: lango-server <application-directory> [--verbose]";
|
|
778
|
+
}
|
|
779
|
+
if (__requireBoolean(verbose)) {
|
|
780
|
+
__hostGlobal(["process"]).env.LANGO_VERBOSE = "1";
|
|
739
781
|
}
|
|
740
|
-
|
|
782
|
+
trace(`Loading server configuration: ${directory}`);
|
|
783
|
+
let server = new Server(directory);
|
|
741
784
|
let stop = () => {
|
|
742
785
|
return __normalize(server.close()).catch(__withArity((error) => {
|
|
743
786
|
const __contextScope = [];
|
package/dist/cli/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;;;;;;;;;;;;;;;;"}
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {
|
|
2
|
+
contextGet as __contextGet,
|
|
3
|
+
contextSet as __contextSet,
|
|
4
|
+
contextRestore as __contextRestore,
|
|
5
|
+
requireBoolean as __requireBoolean,
|
|
6
|
+
normalize as __normalize,
|
|
7
|
+
boundary as __boundary,
|
|
8
|
+
requireArity as __requireArity,
|
|
9
|
+
} from "./.lango/runtime.mjs";
|
|
10
|
+
|
|
11
|
+
export function trace(message) {
|
|
12
|
+
const __contextScope = [];
|
|
13
|
+
try {
|
|
14
|
+
__requireArity(arguments.length, [0], "trace");
|
|
15
|
+
message = __boundary(message);
|
|
16
|
+
if (__requireBoolean(__normalize(__contextGet("log").verbose) === true)) {
|
|
17
|
+
__normalize(__contextGet("log").debug(message));
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
return null;
|
|
21
|
+
} finally {
|
|
22
|
+
__contextRestore(__contextScope);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function responseLog(id, method, path, status) {
|
|
27
|
+
const __contextScope = [];
|
|
28
|
+
try {
|
|
29
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "responseLog");
|
|
30
|
+
id = __boundary(id);
|
|
31
|
+
method = __boundary(method);
|
|
32
|
+
path = __boundary(path);
|
|
33
|
+
status = __boundary(status);
|
|
34
|
+
let message = `HTTP ${method} ${path} completed status=${status}`;
|
|
35
|
+
if (__requireBoolean(id !== null)) {
|
|
36
|
+
message = `[${id}] ${message}`;
|
|
37
|
+
}
|
|
38
|
+
if (__requireBoolean(status >= 500)) {
|
|
39
|
+
__normalize(__contextGet("log").err(message));
|
|
40
|
+
} else {
|
|
41
|
+
if (__requireBoolean(status >= 400)) {
|
|
42
|
+
__normalize(__contextGet("log").warn(message));
|
|
43
|
+
} else {
|
|
44
|
+
trace(message);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
return null;
|
|
49
|
+
} finally {
|
|
50
|
+
__contextRestore(__contextScope);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=trace.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace.mjs","sources":["trace.lango"],"sourcesContent":["export trace(message)\nexport responseLog(id, method, path, status)\n\ntrace(message)\n context log\n if log.verbose? == true\n log.debug(message)\n return null\n\n\nresponseLog(id, method, path, status)\n context log\n message = \"HTTP ${method} ${path} completed status=${status}\"\n if id != null\n message = \"[${id}] ${message}\"\n if status >= 500\n log.err(message)\n else\n if status >= 400\n log.warn(message)\n else\n trace(message)\n return null\n"],"names":[],"mappings":";;;;;;;;;;AAGA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isNumber as __isNumber,
|
|
3
|
+
isString as __isString,
|
|
4
|
+
isBool as __isBool,
|
|
5
|
+
isObject as __isObject,
|
|
6
|
+
isArray as __isArray,
|
|
7
|
+
requireBoolean as __requireBoolean,
|
|
8
|
+
normalize as __normalize,
|
|
9
|
+
boundary as __boundary,
|
|
10
|
+
requireArity as __requireArity,
|
|
11
|
+
} from "./.lango/runtime.mjs";
|
|
12
|
+
|
|
13
|
+
export function errorDetails(error) {
|
|
14
|
+
__requireArity(arguments.length, [0], "errorDetails");
|
|
15
|
+
error = __boundary(error);
|
|
16
|
+
if (__requireBoolean(__isObject(error))) {
|
|
17
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.stack))) && __requireBoolean(__normalize(error.stack) !== ""))) {
|
|
18
|
+
return __normalize(error.stack);
|
|
19
|
+
}
|
|
20
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
|
|
21
|
+
return __normalize(error.message);
|
|
22
|
+
}
|
|
23
|
+
if (__requireBoolean(__isString(__normalize(error.code)))) {
|
|
24
|
+
return __normalize(error.code);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return `${error}`;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function errorMessage(error) {
|
|
32
|
+
__requireArity(arguments.length, [0], "errorMessage");
|
|
33
|
+
error = __boundary(error);
|
|
34
|
+
if (__requireBoolean(__isObject(error))) {
|
|
35
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
|
|
36
|
+
return __normalize(error.message);
|
|
37
|
+
}
|
|
38
|
+
if (__requireBoolean(__isString(__normalize(error.code)))) {
|
|
39
|
+
return __normalize(error.code);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return `${error}`;
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=error_details.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
|