@lango-project/lango-server 0.1.1 → 0.1.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 +86 -7
- package/dist/cli/endpoint.mjs +2 -6
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_options.mjs +1 -1
- package/dist/cli/longpoll_options.mjs.map +1 -1
- package/dist/cli/route_pattern.mjs +129 -0
- package/dist/cli/route_pattern.mjs.map +1 -0
- package/dist/cli/routes.mjs +25 -13
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/endpoint.mjs +2 -6
- package/dist/endpoint.mjs.map +1 -1
- package/dist/http_failure.mjs +45 -0
- package/dist/http_failure.mjs.map +1 -0
- package/dist/longpoll_options.mjs +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/response.mjs +8 -0
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +22 -0
- package/dist/route_info.mjs.map +1 -0
- package/dist/route_pattern.mjs +129 -0
- package/dist/route_pattern.mjs.map +1 -0
- package/dist/routes.mjs +25 -13
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +57 -20
- package/dist/runtime.mjs.map +1 -1
- package/dist/server_context.mjs +12 -2
- package/dist/server_context.mjs.map +1 -1
- package/dist/token.mjs +12 -0
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +16 -1
- package/dist/tokens.mjs.map +1 -1
- package/package.json +2 -2
- package/src/endpoint.lango +3 -4
- package/src/http_failure.lango +26 -0
- package/src/longpoll_options.lango +1 -1
- package/src/response.lango +6 -0
- package/src/route_info.lango +15 -0
- package/src/route_pattern.lango +86 -0
- package/src/routes.lango +20 -8
- package/src/runtime.lango +55 -17
- package/src/server_context.lango +11 -3
- package/src/token.lango +11 -0
- package/src/tokens.lango +11 -1
|
@@ -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 routeInfo(definitions) {
|
|
9
|
+
__requireArity(arguments.length, [0], "routeInfo");
|
|
10
|
+
definitions = __boundary(definitions);
|
|
11
|
+
let result = [];
|
|
12
|
+
for (const route of definitions) {
|
|
13
|
+
let kind = __normalize(route.kind);
|
|
14
|
+
if (__requireBoolean(kind === null)) {
|
|
15
|
+
kind = "endpoint";
|
|
16
|
+
}
|
|
17
|
+
result.push({ path: __normalize(route.path), kind: kind, auth: __normalize(route.auth), middleware: __normalize(route.middleware) });
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=route_info.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route_info.mjs","sources":["route_info.lango"],"sourcesContent":["export routeInfo(definitions)\n\nrouteInfo(definitions)\n result = []\n for definitions as route\n kind = route.kind\n if kind == null\n kind = \"endpoint\"\n result.add({\n path: route.path\n kind: kind\n auth: route.auth\n middleware: route.middleware\n })\n return result\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hostGlobal as __hostGlobal,
|
|
3
|
+
isNumber as __isNumber,
|
|
4
|
+
isString as __isString,
|
|
5
|
+
isBool as __isBool,
|
|
6
|
+
isObject as __isObject,
|
|
7
|
+
isArray as __isArray,
|
|
8
|
+
entries as __entries,
|
|
9
|
+
range as __range,
|
|
10
|
+
requireBoolean as __requireBoolean,
|
|
11
|
+
normalize as __normalize,
|
|
12
|
+
finite as __finite,
|
|
13
|
+
boundary as __boundary,
|
|
14
|
+
requireArity as __requireArity,
|
|
15
|
+
} from "./.lango/runtime.mjs";
|
|
16
|
+
|
|
17
|
+
export function routePattern(path) {
|
|
18
|
+
__requireArity(arguments.length, [0], "routePattern");
|
|
19
|
+
path = __boundary(path);
|
|
20
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(path))) || __requireBoolean(!__requireBoolean(__normalize(path.startsWith("/"))))) || __requireBoolean(__normalize(path.includes("?")))) || __requireBoolean(__normalize(path.includes("#")))) || __requireBoolean(__normalize(path.includes("\\")))) || __requireBoolean(__normalize(path.includes("//"))))) {
|
|
21
|
+
throw "Endpoint requires an absolute URL path";
|
|
22
|
+
}
|
|
23
|
+
if (__requireBoolean(__requireBoolean(__normalize(path.includes("*"))) && __requireBoolean(__requireBoolean(!__requireBoolean(__normalize(path.endsWith("/*")))) || __requireBoolean(__normalize(path.indexOf("*")) !== __normalize(path.lastIndexOf("*")))))) {
|
|
24
|
+
throw "Only trailing /* wildcards are supported";
|
|
25
|
+
}
|
|
26
|
+
let segments = __normalize(path.split("/"));
|
|
27
|
+
segments = __normalize(segments.slice(1));
|
|
28
|
+
let wildcard = __normalize(path.endsWith("/*"));
|
|
29
|
+
if (__requireBoolean(wildcard)) {
|
|
30
|
+
__normalize(segments.pop());
|
|
31
|
+
}
|
|
32
|
+
let names = [];
|
|
33
|
+
let shape = [];
|
|
34
|
+
let identifier = new (__hostGlobal(["RegExp"]))("^[A-Za-z_][A-Za-z0-9_]*$");
|
|
35
|
+
let reserved = ["__proto__", "constructor", "prototype"];
|
|
36
|
+
for (const segment of segments) {
|
|
37
|
+
if (__requireBoolean(__requireBoolean(__normalize(segment.includes("{"))) || __requireBoolean(__normalize(segment.includes("}"))))) {
|
|
38
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(segment.startsWith("{")))) || __requireBoolean(!__requireBoolean(__normalize(segment.endsWith("}")))))) {
|
|
39
|
+
throw "Path parameters must occupy an entire segment";
|
|
40
|
+
}
|
|
41
|
+
let name = __normalize(segment.slice(1, __finite(-1)));
|
|
42
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(identifier.test(name)))) || __requireBoolean(__normalize(reserved.includes(name))))) {
|
|
43
|
+
throw `Invalid path parameter name: ${name}`;
|
|
44
|
+
}
|
|
45
|
+
if (__requireBoolean(__normalize(names.includes(name)))) {
|
|
46
|
+
throw `Duplicate path parameter: ${name}`;
|
|
47
|
+
}
|
|
48
|
+
names.push(name);
|
|
49
|
+
shape.push("{}");
|
|
50
|
+
} else {
|
|
51
|
+
shape.push(segment);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (__requireBoolean(wildcard)) {
|
|
55
|
+
shape.push("*");
|
|
56
|
+
}
|
|
57
|
+
let key = __normalize(shape.join("/"));
|
|
58
|
+
key = `/${key}`;
|
|
59
|
+
return { segments: segments, wildcard: wildcard, key: key };
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function matchPath(pattern, path) {
|
|
64
|
+
__requireArity(arguments.length, [0, 1], "matchPath");
|
|
65
|
+
pattern = __boundary(pattern);
|
|
66
|
+
path = __boundary(path);
|
|
67
|
+
let parts = __normalize(path.split("/"));
|
|
68
|
+
if (__requireBoolean(__normalize(parts[0]) !== "")) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
parts = __normalize(parts.slice(1));
|
|
72
|
+
let count = pattern.segments.length;
|
|
73
|
+
if (__requireBoolean(__normalize(pattern.wildcard))) {
|
|
74
|
+
if (__requireBoolean(__normalize(parts.length) <= count)) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
if (__requireBoolean(__normalize(parts.length) !== count)) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
let parameters = { };
|
|
83
|
+
for (const [index, segment] of __entries(__normalize(pattern.segments))) {
|
|
84
|
+
let value = __normalize(parts[index]);
|
|
85
|
+
if (__requireBoolean(__normalize(segment.startsWith("{")))) {
|
|
86
|
+
if (__requireBoolean(value === "")) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
let name = __normalize(segment.slice(1, __finite(-1)));
|
|
90
|
+
parameters[name] = value;
|
|
91
|
+
} else {
|
|
92
|
+
if (__requireBoolean(segment !== value)) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return parameters;
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function moreSpecific(candidate, current) {
|
|
102
|
+
__requireArity(arguments.length, [0, 1], "moreSpecific");
|
|
103
|
+
candidate = __boundary(candidate);
|
|
104
|
+
current = __boundary(current);
|
|
105
|
+
if (__requireBoolean(current === null)) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
if (__requireBoolean(__normalize(candidate.wildcard) !== __normalize(current.wildcard))) {
|
|
109
|
+
return !__requireBoolean(__normalize(candidate.wildcard));
|
|
110
|
+
}
|
|
111
|
+
let first = __normalize(candidate.segments);
|
|
112
|
+
let second = __normalize(current.segments);
|
|
113
|
+
let count = __normalize(first.length);
|
|
114
|
+
if (__requireBoolean(__normalize(second.length) < count)) {
|
|
115
|
+
count = __normalize(second.length);
|
|
116
|
+
}
|
|
117
|
+
for (const index of __range(0, count)) {
|
|
118
|
+
let segment = __normalize(first[index]);
|
|
119
|
+
let alternative = __normalize(second[index]);
|
|
120
|
+
let literal = !__requireBoolean(__normalize(segment.startsWith("{")));
|
|
121
|
+
let other = !__requireBoolean(__normalize(alternative.startsWith("{")));
|
|
122
|
+
if (__requireBoolean(literal !== other)) {
|
|
123
|
+
return literal;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return __normalize(first.length) > __normalize(second.length);
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=route_pattern.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route_pattern.mjs","sources":["route_pattern.lango"],"sourcesContent":["import js global RegExp\n\nexport routePattern(path)\nexport matchPath(pattern, path)\nexport moreSpecific(candidate, current)\n\nroutePattern(path)\n if !is_string(path) or !path.startsWith(\"/\") or path.includes(\"?\") or path.includes(\"#\") or path.includes(\"\\\\\") or path.includes(\"//\")\n throw \"Endpoint requires an absolute URL path\"\n if path.includes(\"*\") and (!path.endsWith(\"/*\") or path.indexOf(\"*\") != path.lastIndexOf(\"*\"))\n throw \"Only trailing /* wildcards are supported\"\n segments = path.split(\"/\")\n segments = segments.slice(1)\n wildcard = path.endsWith(\"/*\")\n if wildcard\n segments.pop()\n names = []\n shape = []\n identifier = new RegExp(\"^[A-Za-z_][A-Za-z0-9_]*$\")\n reserved = [\"__proto__\", \"constructor\", \"prototype\"]\n for segments as segment\n if segment.includes(\"{\") or segment.includes(\"}\")\n if !segment.startsWith(\"{\") or !segment.endsWith(\"}\")\n throw \"Path parameters must occupy an entire segment\"\n name = segment.slice(1, -1)\n if !identifier.test(name) or reserved.includes(name)\n throw \"Invalid path parameter name: ${name}\"\n if names.includes(name)\n throw \"Duplicate path parameter: ${name}\"\n names.add(name)\n shape.add(\"{}\")\n else\n shape.add(segment)\n if wildcard\n shape.add(\"*\")\n key = shape.join(\"/\")\n key = \"/${key}\"\n return {\n segments: segments\n wildcard: wildcard\n key: key\n }\n\nmatchPath(pattern, path)\n parts = path.split(\"/\")\n if parts[0] != \"\"\n return null\n parts = parts.slice(1)\n count = pattern.segments.length\n if pattern.wildcard\n if parts.length <= count\n return null\n else\n if parts.length != count\n return null\n parameters = {}\n for pattern.segments as index: segment\n value = parts[index]\n if segment.startsWith(\"{\")\n if value == \"\"\n return null\n name = segment.slice(1, -1)\n parameters[name] = value\n else\n if segment != value\n return null\n return parameters\n\nmoreSpecific(candidate, current)\n if current == null\n return true\n if candidate.wildcard != current.wildcard\n return !candidate.wildcard\n first = candidate.segments\n second = current.segments\n count = first.length\n if second.length < count\n count = second.length\n for range(count) as index\n segment = first[index]\n alternative = second[index]\n literal = !segment.startsWith(\"{\")\n other = !alternative.startsWith(\"{\")\n if literal != other\n return literal\n return first.length > second.length\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/routes.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routePattern } from "./route_pattern.mjs";
|
|
1
2
|
import { contains } from "./options.mjs";
|
|
2
3
|
import { attributes } from "./options.mjs";
|
|
3
4
|
import { middlewareName } from "./middleware.mjs";
|
|
@@ -43,13 +44,25 @@ export class Routes {
|
|
|
43
44
|
__requireArity(arguments.length, [0], "endpoint");
|
|
44
45
|
spec = __boundary(spec);
|
|
45
46
|
let item = new Endpoint(spec);
|
|
47
|
+
this.#checkPath(__normalize(item.path));
|
|
48
|
+
__add(this.#items, { path: __normalize(item.path), module: resolveModule(__normalize(item.module), __normalize(this.#root)), handler: __normalize(item.handler), auth: __normalize(item.auth), middleware: __normalize(item.middleware) });
|
|
49
|
+
return this;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
#checkPath(path) {
|
|
53
|
+
__requireArity(arguments.length, [0], "checkPath");
|
|
54
|
+
path = __boundary(path);
|
|
55
|
+
let pattern = routePattern(path);
|
|
46
56
|
for (const other of __normalize(this.#items)) {
|
|
47
|
-
if (__requireBoolean(__normalize(other.path) ===
|
|
48
|
-
throw `Duplicate endpoint: ${
|
|
57
|
+
if (__requireBoolean(__normalize(other.path) === path)) {
|
|
58
|
+
throw `Duplicate endpoint: ${path}`;
|
|
59
|
+
}
|
|
60
|
+
let existing = routePattern(__normalize(other.path));
|
|
61
|
+
if (__requireBoolean(__normalize(existing.key) === __normalize(pattern.key))) {
|
|
62
|
+
throw `Conflicting endpoint pattern: ${path}`;
|
|
49
63
|
}
|
|
50
64
|
}
|
|
51
|
-
|
|
52
|
-
return this;
|
|
65
|
+
return null;
|
|
53
66
|
return null;
|
|
54
67
|
}
|
|
55
68
|
addMiddleware(name, spec) {
|
|
@@ -64,14 +77,17 @@ export class Routes {
|
|
|
64
77
|
throw "Middleware requires a module and exported handler";
|
|
65
78
|
}
|
|
66
79
|
for (const [key, value] of __entries(spec)) {
|
|
67
|
-
if (__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler"))) {
|
|
80
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler")) && __requireBoolean(key !== "validate"))) {
|
|
68
81
|
throw `Unknown middleware option: ${key}`;
|
|
69
82
|
}
|
|
70
83
|
}
|
|
71
84
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.handler)))) || __requireBoolean(__normalize(spec.handler) === ""))) {
|
|
72
85
|
throw "Middleware handler is required";
|
|
73
86
|
}
|
|
74
|
-
|
|
87
|
+
if (__requireBoolean(__requireBoolean(__normalize(spec.validate) !== null) && __requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.validate)))) || __requireBoolean(__normalize(spec.validate) === "")))) {
|
|
88
|
+
throw "Middleware validate must name an exported function";
|
|
89
|
+
}
|
|
90
|
+
this.#middlewares[name] = { module: resolveModule(__normalize(spec.module), __normalize(this.#root)), handler: __normalize(spec.handler), validate: __normalize(spec.validate) };
|
|
75
91
|
return this;
|
|
76
92
|
return null;
|
|
77
93
|
}
|
|
@@ -83,11 +99,7 @@ export class Routes {
|
|
|
83
99
|
__requireArity(arguments.length, [0], "longpoll");
|
|
84
100
|
spec = __boundary(spec);
|
|
85
101
|
let item = longpollOptions(spec);
|
|
86
|
-
|
|
87
|
-
if (__requireBoolean(__normalize(other.path) === __normalize(item.path))) {
|
|
88
|
-
throw `Duplicate endpoint: ${__normalize(item.path)}`;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
102
|
+
this.#checkPath(__normalize(item.path));
|
|
91
103
|
__add(this.#items, item);
|
|
92
104
|
return this;
|
|
93
105
|
return null;
|
|
@@ -229,12 +241,12 @@ export class Routes {
|
|
|
229
241
|
leaf(tag);
|
|
230
242
|
this.#includeAt(spec, directory, prefix, stack, auth);
|
|
231
243
|
} else if (__normalize(tag.tag()) === "middleware") {
|
|
232
|
-
attributes(tag, ["name", "module", "handler"]);
|
|
244
|
+
attributes(tag, ["name", "module", "handler", "validate"]);
|
|
233
245
|
leaf(tag);
|
|
234
246
|
if (__requireBoolean(!__requireBoolean(allowEvents))) {
|
|
235
247
|
throw "Middleware declarations are only allowed in the application's root routes.xml";
|
|
236
248
|
}
|
|
237
|
-
this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler) });
|
|
249
|
+
this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler), validate: __normalize(spec.validate) });
|
|
238
250
|
} else if (__normalize(tag.tag()) === "event") {
|
|
239
251
|
attributes(tag, ["name", "module", "handler"]);
|
|
240
252
|
leaf(tag);
|
package/dist/routes.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n
|
|
1
|
+
{"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n checkPath(item.path)\n @items.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n auth: item.auth\n middleware: item.middleware\n })\n return @this\n\nRoutes:checkPath(path)\n pattern = routePattern(path)\n for @items as other\n if other.path == path\n throw \"Duplicate endpoint: ${path}\"\n existing = routePattern(other.path)\n if existing.key == pattern.key\n throw \"Conflicting endpoint pattern: ${path}\"\n return null\n\nRoutes:addMiddleware(name, spec)\n middlewareName(name)\n if Object/hasOwn(@middlewares, name)\n throw \"Duplicate middleware: ${name}\"\n if !is_object(spec) or is_array(spec)\n throw \"Middleware requires a module and exported handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\" and key != \"validate\"\n throw \"Unknown middleware option: ${key}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Middleware handler is required\"\n if spec.validate != null and (!is_string(spec.validate) or spec.validate == \"\")\n throw \"Middleware validate must name an exported function\"\n @middlewares[name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n validate: spec.validate\n }\n return @this\n\nRoutes:middlewares()\n return from_json(to_json(@middlewares))\n\nRoutes:longpoll(spec)\n item = longpollOptions(spec)\n checkPath(item.path)\n @items.add(item)\n return @this\n\nRoutes:event(spec)\n if !contains([\"register\", \"validate\", \"request\"], spec.name)\n throw \"Unknown event: ${spec.name}\"\n if spec.name in @events\n throw \"Duplicate event: ${spec.name}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Event handler is required\"\n @events[spec.name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n }\n return @this\n\nRoutes:include(spec, auth = null)\n includeAt(spec, @root, \"\", [], auth)\n return @this\n\nRoutes:xml(file)\n readXml(path/resolve(file), \"\", @root, [], true)\n return @this\n\nRoutes:definitions()\n return from_json(to_json(@items))\n\nRoutes:events()\n return from_json(to_json(@events))\n\nresolveModule(name, directory)\n if !is_string(name) or name == \"\" or name.startsWith(\"node:\")\n throw \"Application module is required\"\n resolver = modules/createRequire(path/join(directory, \"package.json\"))\n resolved = resolver.resolve(name)\n if !path/isAbsolute(resolved)\n throw \"Application module must resolve to a file: ${name}\"\n return resolved\n\njoinPath(prefix, suffix)\n if !is_string(suffix) or !suffix.startsWith(\"/\")\n throw \"Route path must begin with /\"\n if prefix == \"\" or prefix == \"/\"\n return suffix\n if suffix == \"/\"\n return \"${prefix}/\"\n return \"${prefix}${suffix}\"\n\nRoutes:includeAt(spec, directory, prefix, stack, inheritedAuth = null)\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\".\") or spec.module.startsWith(\"/\") or spec.module.startsWith(\"node:\")\n throw \"Include requires an npm package name\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n if !is_string(mount)\n throw \"Include path must be a string\"\n if mount.includes(\"*\") or mount.includes(\"//\") or mount.includes(\"?\") or mount.includes(\"#\") or mount.includes(\"\\\\\")\n throw \"Invalid include prefix\"\n if mount.endsWith(\"/\") and mount != \"/\"\n mount = mount.slice(0, -1)\n combined = joinPath(prefix, mount)\n if combined == \"/\"\n combined = \"\"\n file = resolveModule(\"${spec.module}/routes.xml\", directory)\n readXml(file, combined, path/dirname(file), stack, false, inheritedAuth)\n return null\n\nRoutes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null)\n real = fs/realpathSync(file)\n if stack.includes(real)\n throw \"Route include cycle: ${real}\"\n root = xml2obj(fs/readFileSync(real, \"utf8\"))\n if root.tag() != \"routes\"\n throw \"Expected routes root: ${real}\"\n attributes(root, [])\n nextStack = stack.slice()\n nextStack.add(real)\n collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents)\n return null\n\nRoutes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents)\n if parent.innerText().trim() != \"\"\n throw \"Route XML cannot contain text\"\n for parent.children() as tag\n spec = tag.attributes()\n mod = spec.module\n auth = spec.auth\n if mod == null\n mod = inheritedModule\n if auth == null\n auth = inheritedAuth\n switch tag.tag()\n case \"endpoint\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n })\n case \"longpoll\"\n attributes(tag, [\"path\", \"auth\", \"waitTimeoutMs\", \"retentionMs\", \"maxMessages\", \"fallback\"])\n leaf(tag)\n spec.path = joinPath(prefix, spec.path)\n spec.auth = auth\n if spec.fallback != null\n spec.fallback = joinPath(prefix, spec.fallback)\n longpoll(spec)\n case \"group\"\n attributes(tag, [\"path\", \"module\", \"auth\"])\n collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false)\n case \"include\"\n attributes(tag, [\"module\", \"path\"])\n leaf(tag)\n includeAt(spec, directory, prefix, stack, auth)\n case \"middleware\"\n attributes(tag, [\"name\", \"module\", \"handler\", \"validate\"])\n leaf(tag)\n if !allowEvents\n throw \"Middleware declarations are only allowed in the application's root routes.xml\"\n addMiddleware(spec.name, {\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n validate: spec.validate\n })\n case \"event\"\n attributes(tag, [\"name\", \"module\", \"handler\"])\n leaf(tag)\n if !allowEvents\n throw \"Events are only allowed in the application's root routes.xml\"\n event({\n name: spec.name\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n })\n else\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n middleware: tag.tag()\n })\n return null\n\nleaf(tag)\n if tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Expected an empty ${tag.tag()} element\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;AA6GA;;;;;;;;;;"}
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { routePattern, matchPath, moreSpecific } from "./route_pattern.mjs";
|
|
1
2
|
import { ServerContext } from "./server_context.mjs";
|
|
2
3
|
import { Database } from "./database.mjs";
|
|
3
4
|
import { Token } from "./token.mjs";
|
|
4
5
|
import { Tokens } from "./tokens.mjs";
|
|
5
6
|
import { Response } from "./response.mjs";
|
|
7
|
+
import { HttpFailure } from "./http_failure.mjs";
|
|
6
8
|
import * as threads from "node:worker_threads";
|
|
7
9
|
import {
|
|
8
10
|
hostGlobal as __hostGlobal,
|
|
11
|
+
hostGlobalCall as __hostGlobalCall,
|
|
9
12
|
contextGet as __contextGet,
|
|
10
13
|
contextSet as __contextSet,
|
|
11
14
|
contextRestore as __contextRestore,
|
|
@@ -40,7 +43,7 @@ export class Runtime {
|
|
|
40
43
|
constructor(definition) {
|
|
41
44
|
__requireArity(arguments.length, [0], "constructor");
|
|
42
45
|
definition = __boundary(definition);
|
|
43
|
-
this.#serverContext = new ServerContext();
|
|
46
|
+
this.#serverContext = new ServerContext(__normalize(definition.routes));
|
|
44
47
|
this.#definition = definition;
|
|
45
48
|
this.#routes = [];
|
|
46
49
|
this.#events = { };
|
|
@@ -89,6 +92,16 @@ export class Runtime {
|
|
|
89
92
|
}, [0], "closure")).then(__withArity((handler) => {
|
|
90
93
|
handler = __boundary(handler);
|
|
91
94
|
this.#middlewares[name] = handler;
|
|
95
|
+
if (__requireBoolean(__normalize(spec.validate) !== null)) {
|
|
96
|
+
return this.#target({ module: __normalize(spec.module), handler: __normalize(spec.validate) });
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
return null;
|
|
100
|
+
}, [0], "closure")).then(__withArity((validator) => {
|
|
101
|
+
validator = __boundary(validator);
|
|
102
|
+
if (__requireBoolean(validator !== null)) {
|
|
103
|
+
return __call(validator, __normalize(this.#serverContext.routes()));
|
|
104
|
+
}
|
|
92
105
|
return null;
|
|
93
106
|
return null;
|
|
94
107
|
}, [0], "closure"));
|
|
@@ -99,7 +112,9 @@ export class Runtime {
|
|
|
99
112
|
pending = __boundary(pending);
|
|
100
113
|
route = __boundary(route);
|
|
101
114
|
if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
|
|
102
|
-
|
|
115
|
+
let prepared = __normalize(__hostGlobal(["Object"]).assign({ }, route));
|
|
116
|
+
prepared.pattern = routePattern(__normalize(route.path));
|
|
117
|
+
__add(this.#routes, prepared);
|
|
103
118
|
return pending;
|
|
104
119
|
}
|
|
105
120
|
return pending.then(__withArity((ignored) => {
|
|
@@ -116,7 +131,7 @@ export class Runtime {
|
|
|
116
131
|
}
|
|
117
132
|
middleware = __normalize(this.#middlewares[name]);
|
|
118
133
|
}
|
|
119
|
-
__add(this.#routes, { path: __normalize(route.path), auth: __normalize(route.auth), handler: handler, middleware: middleware });
|
|
134
|
+
__add(this.#routes, { path: __normalize(route.path), pattern: routePattern(__normalize(route.path)), auth: __normalize(route.auth), handler: handler, middleware: middleware });
|
|
120
135
|
return null;
|
|
121
136
|
return null;
|
|
122
137
|
}, [0], "closure"));
|
|
@@ -158,20 +173,20 @@ export class Runtime {
|
|
|
158
173
|
__requireArity(arguments.length, [0], "match");
|
|
159
174
|
path = __boundary(path);
|
|
160
175
|
let best = null;
|
|
161
|
-
let
|
|
176
|
+
let parameters = null;
|
|
177
|
+
let pattern = null;
|
|
162
178
|
for (const route of __normalize(this.#routes)) {
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (__requireBoolean(__requireBoolean(__normalize(path.startsWith(prefix))) && __requireBoolean(__normalize(prefix.length) > length))) {
|
|
169
|
-
best = route;
|
|
170
|
-
length = __normalize(prefix.length);
|
|
171
|
-
}
|
|
179
|
+
let captured = matchPath(__normalize(route.pattern), path);
|
|
180
|
+
if (__requireBoolean(__requireBoolean(captured !== null) && __requireBoolean(moreSpecific(__normalize(route.pattern), pattern)))) {
|
|
181
|
+
best = route;
|
|
182
|
+
parameters = captured;
|
|
183
|
+
pattern = __normalize(route.pattern);
|
|
172
184
|
}
|
|
173
185
|
}
|
|
174
|
-
|
|
186
|
+
if (__requireBoolean(best === null)) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
return { route: best, parameters: parameters };
|
|
175
190
|
return null;
|
|
176
191
|
}
|
|
177
192
|
handle(task) {
|
|
@@ -194,10 +209,11 @@ export class Runtime {
|
|
|
194
209
|
} catch (error) {
|
|
195
210
|
return failure(401, "Unauthorized");
|
|
196
211
|
}
|
|
197
|
-
let
|
|
198
|
-
if (__requireBoolean(
|
|
212
|
+
let matched = this.#match(__normalize(__contextGet("request").path));
|
|
213
|
+
if (__requireBoolean(matched === null)) {
|
|
199
214
|
return failure(404, "RouteNotFound");
|
|
200
215
|
}
|
|
216
|
+
let route = __normalize(matched.route);
|
|
201
217
|
let input = null;
|
|
202
218
|
try {
|
|
203
219
|
input = __normalize(__hostGlobal(["JSON"]).parse(__normalize(task.body)));
|
|
@@ -207,6 +223,13 @@ export class Runtime {
|
|
|
207
223
|
} catch (error) {
|
|
208
224
|
return failure(400, "InvalidJson");
|
|
209
225
|
}
|
|
226
|
+
try {
|
|
227
|
+
for (const [name, value] of __entries(__normalize(matched.parameters))) {
|
|
228
|
+
input[name] = __hostGlobalCall(["decodeURIComponent"], value);
|
|
229
|
+
}
|
|
230
|
+
} catch (error) {
|
|
231
|
+
return failure(400, "InvalidPath");
|
|
232
|
+
}
|
|
210
233
|
__contextScope.push(__contextSet("token", new Token(claims)));
|
|
211
234
|
__contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
|
|
212
235
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
@@ -268,8 +291,7 @@ export class Runtime {
|
|
|
268
291
|
output = __boundary(output);
|
|
269
292
|
if (__requireBoolean(__normalize(task.authorize) === true)) {
|
|
270
293
|
closeScope(__contextGet("db"), true);
|
|
271
|
-
let authorizedClaims =
|
|
272
|
-
authorizedClaims.validatedAt = __normalize(claims.validatedAt);
|
|
294
|
+
let authorizedClaims = this.#tokenClaims(__contextGet("token"), claims, true);
|
|
273
295
|
let encoded = __normalize(this.#tokens.sign(authorizedClaims));
|
|
274
296
|
if (__requireBoolean(__normalize(task.pollResult) === null)) {
|
|
275
297
|
return { status: 200, authorization: encoded };
|
|
@@ -291,8 +313,7 @@ export class Runtime {
|
|
|
291
313
|
}
|
|
292
314
|
closeScope(__contextGet("db"), true);
|
|
293
315
|
let result = __normalize(__contextGet("response").result(body));
|
|
294
|
-
let updated =
|
|
295
|
-
updated.validatedAt = __normalize(claims.validatedAt);
|
|
316
|
+
let updated = this.#tokenClaims(__contextGet("token"), claims, __normalize(result.status) < 400);
|
|
296
317
|
result.headers["x-lango-token"] = __normalize(this.#tokens.sign(updated));
|
|
297
318
|
if (__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.requestEvent)) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
|
|
298
319
|
return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
|
|
@@ -311,6 +332,9 @@ export class Runtime {
|
|
|
311
332
|
__contextScope.push(__contextSet("db", __capturedContext3));
|
|
312
333
|
error = __boundary(error);
|
|
313
334
|
closeScope(__contextGet("db"), false);
|
|
335
|
+
if (__requireBoolean(__isKindof(error, HttpFailure))) {
|
|
336
|
+
return __normalize(error.result());
|
|
337
|
+
}
|
|
314
338
|
if (__requireBoolean(__requireBoolean(error === "TokenExpired") || __requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401)))) {
|
|
315
339
|
return failure(401, "Unauthorized");
|
|
316
340
|
}
|
|
@@ -335,6 +359,19 @@ export class Runtime {
|
|
|
335
359
|
__contextRestore(__contextScope);
|
|
336
360
|
}
|
|
337
361
|
}
|
|
362
|
+
#tokenClaims(token, claims, allowRenewal) {
|
|
363
|
+
__requireArity(arguments.length, [0, 1, 2], "tokenClaims");
|
|
364
|
+
token = __boundary(token);
|
|
365
|
+
claims = __boundary(claims);
|
|
366
|
+
allowRenewal = __boundary(allowRenewal);
|
|
367
|
+
let updated = __normalize(token.snapshot());
|
|
368
|
+
updated.validatedAt = __normalize(claims.validatedAt);
|
|
369
|
+
if (__requireBoolean(__requireBoolean(allowRenewal) && __requireBoolean(__normalize(token.renewalRequested())))) {
|
|
370
|
+
updated = __normalize(this.#tokens.renew(updated));
|
|
371
|
+
}
|
|
372
|
+
return updated;
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
338
375
|
#event(name, input) {
|
|
339
376
|
const __contextScope = [];
|
|
340
377
|
try {
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./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\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n\nRuntime(definition)\n @serverContext = new ServerContext()\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 @middlewares[name] = handler\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n @routes.add(route)\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 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 length = -1\n for @routes as route\n if route.path == path\n return route\n if route.path.endsWith(\"/*\")\n prefix = route.path.slice(0, -1)\n if path.startsWith(prefix) and prefix.length > length\n best = route\n length = prefix.length\n return best\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 route = match(request.path)\n if route == null\n return failure(404, \"RouteNotFound\")\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 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 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 = token.snapshot()\n authorizedClaims.validatedAt = claims.validatedAt\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 = token.snapshot()\n updated.validatedAt = claims.validatedAt\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if @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 closeScope(db, false)\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: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 !(\"validate\" in @events) or Date/now() - claims.validatedAt < 1000\n return null\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA;;;;;;;;;;;AA0PA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
|
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\nRuntime(definition)\n @serverContext = new ServerContext(definition.routes)\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 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 @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: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 !(\"validate\" in @events) or Date/now() - claims.validatedAt < 1000\n return null\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA;;;;;;;;;;;AA4QA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
package/dist/server_context.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routeInfo } from "./route_info.mjs";
|
|
1
2
|
import * as threads from "node:worker_threads";
|
|
2
3
|
import {
|
|
3
4
|
hostGlobal as __hostGlobal,
|
|
@@ -13,8 +14,17 @@ import {
|
|
|
13
14
|
} from "./.lango/runtime.mjs";
|
|
14
15
|
|
|
15
16
|
export class ServerContext {
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
#routes;
|
|
18
|
+
constructor(definitions = null) {
|
|
19
|
+
definitions = __boundary(definitions);
|
|
20
|
+
if (__requireBoolean(definitions === null)) {
|
|
21
|
+
definitions = [];
|
|
22
|
+
}
|
|
23
|
+
this.#routes = routeInfo(definitions);
|
|
24
|
+
}
|
|
25
|
+
routes() {
|
|
26
|
+
return __fromJson(__toJson(__normalize(this.#routes)));
|
|
27
|
+
return null;
|
|
18
28
|
}
|
|
19
29
|
publish(path, key, data) {
|
|
20
30
|
__requireArity(arguments.length, [0, 1, 2], "publish");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class ServerContext()\n methods\n publish(path, key, data)\n cursor(path, key)\n\nServerContext()\n
|
|
1
|
+
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./route_info\"\n routeInfo(definitions)\n\nexport class ServerContext(definitions = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n\nServerContext(definitions = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n\nServerContext:routes()\n return from_json(to_json(@routes))\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/token.mjs
CHANGED
|
@@ -20,12 +20,14 @@ export class Token {
|
|
|
20
20
|
expiresAt;
|
|
21
21
|
#claims;
|
|
22
22
|
#readonly;
|
|
23
|
+
#renew;
|
|
23
24
|
constructor(claims, readonly = false) {
|
|
24
25
|
__requireArity(arguments.length, [0], "constructor");
|
|
25
26
|
claims = __boundary(claims);
|
|
26
27
|
readonly = __boundary(readonly);
|
|
27
28
|
this.#claims = __fromJson(__toJson(claims));
|
|
28
29
|
this.#readonly = readonly;
|
|
30
|
+
this.#renew = false;
|
|
29
31
|
this.clientId = __normalize(claims.clientId);
|
|
30
32
|
this.auth = __normalize(claims.auth);
|
|
31
33
|
this.expiresAt = __normalize(claims.exp);
|
|
@@ -95,6 +97,16 @@ export class Token {
|
|
|
95
97
|
return claims;
|
|
96
98
|
return null;
|
|
97
99
|
}
|
|
100
|
+
renew() {
|
|
101
|
+
this.#writable();
|
|
102
|
+
this.#renew = true;
|
|
103
|
+
return this;
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
renewalRequested() {
|
|
107
|
+
return __normalize(this.#renew);
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
98
110
|
#writable() {
|
|
99
111
|
if (__requireBoolean(__normalize(this.#readonly))) {
|
|
100
112
|
throw "Token is read-only during this event";
|
package/dist/token.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId\n auth\n expiresAt\n methods\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n\nToken:AddAuth(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasAuth(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearAuth()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasAuth(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA
|
|
1
|
+
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId\n auth\n expiresAt\n methods\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n renew()\n renewalRequested()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @renew = false\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n\nToken:AddAuth(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasAuth(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearAuth()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasAuth(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:renew()\n writable()\n @renew = true\n return @this\n\nToken:renewalRequested()\n return @renew\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|