@lango-project/lango-server 0.1.0 → 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 +368 -10
- package/dist/builder.mjs +16 -1
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/endpoint.mjs +8 -6
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_broker.mjs +214 -0
- package/dist/cli/longpoll_broker.mjs.map +1 -0
- package/dist/cli/longpoll_options.mjs +102 -0
- package/dist/cli/longpoll_options.mjs.map +1 -0
- package/dist/cli/longpoll_session.mjs +135 -0
- package/dist/cli/longpoll_session.mjs.map +1 -0
- package/dist/cli/middleware.mjs +25 -0
- package/dist/cli/middleware.mjs.map +1 -0
- package/dist/cli/options.mjs +14 -2
- package/dist/cli/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 +80 -4
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/cli/server.mjs +243 -23
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +125 -0
- package/dist/cli/static_files.mjs.map +1 -0
- package/dist/endpoint.mjs +8 -6
- package/dist/endpoint.mjs.map +1 -1
- package/dist/group.mjs +17 -1
- package/dist/group.mjs.map +1 -1
- package/dist/http_failure.mjs +45 -0
- package/dist/http_failure.mjs.map +1 -0
- package/dist/longpoll_broker.mjs +214 -0
- package/dist/longpoll_broker.mjs.map +1 -0
- package/dist/longpoll_options.mjs +102 -0
- package/dist/longpoll_options.mjs.map +1 -0
- package/dist/longpoll_session.mjs +135 -0
- package/dist/longpoll_session.mjs.map +1 -0
- package/dist/middleware.mjs +25 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/options.mjs +14 -2
- package/dist/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 +80 -4
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +170 -59
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +243 -23
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +88 -0
- package/dist/server_context.mjs.map +1 -0
- package/dist/static_files.mjs +125 -0
- package/dist/static_files.mjs.map +1 -0
- 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 +9 -4
- package/src/builder.lango +11 -0
- package/src/endpoint.lango +10 -4
- package/src/group.lango +14 -0
- package/src/http_failure.lango +26 -0
- package/src/longpoll.lua +61 -0
- package/src/longpoll_broker.lango +161 -0
- package/src/longpoll_options.lango +79 -0
- package/src/longpoll_session.lango +90 -0
- package/src/middleware.lango +10 -0
- package/src/options.lango +16 -0
- package/src/response.lango +6 -0
- package/src/route_info.lango +15 -0
- package/src/route_pattern.lango +86 -0
- package/src/routes.lango +80 -4
- package/src/runtime.lango +113 -13
- package/src/server.lango +182 -17
- package/src/server_context.lango +66 -0
- package/src/static_files.lango +90 -0
- package/src/token.lango +11 -0
- package/src/tokens.lango +11 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as files from "serve-static";
|
|
4
|
+
import {
|
|
5
|
+
hostGlobal as __hostGlobal,
|
|
6
|
+
isNumber as __isNumber,
|
|
7
|
+
isString as __isString,
|
|
8
|
+
isBool as __isBool,
|
|
9
|
+
isObject as __isObject,
|
|
10
|
+
isArray as __isArray,
|
|
11
|
+
entries as __entries,
|
|
12
|
+
requireBoolean as __requireBoolean,
|
|
13
|
+
normalize as __normalize,
|
|
14
|
+
finite as __finite,
|
|
15
|
+
call as __call,
|
|
16
|
+
boundary as __boundary,
|
|
17
|
+
requireArity as __requireArity,
|
|
18
|
+
withArity as __withArity,
|
|
19
|
+
} from "./.lango/runtime.mjs";
|
|
20
|
+
|
|
21
|
+
export class StaticFiles {
|
|
22
|
+
#settings;
|
|
23
|
+
#serve;
|
|
24
|
+
constructor(settings) {
|
|
25
|
+
__requireArity(arguments.length, [0], "constructor");
|
|
26
|
+
settings = __boundary(settings);
|
|
27
|
+
this.#settings = settings;
|
|
28
|
+
if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
|
|
29
|
+
throw "Static directory must be a directory";
|
|
30
|
+
}
|
|
31
|
+
this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
|
|
32
|
+
}
|
|
33
|
+
receive(req, res, failed) {
|
|
34
|
+
__requireArity(arguments.length, [0, 1, 2], "receive");
|
|
35
|
+
req = __boundary(req);
|
|
36
|
+
res = __boundary(res);
|
|
37
|
+
failed = __boundary(failed);
|
|
38
|
+
let mount = __normalize(this.#settings.path);
|
|
39
|
+
let url = __normalize(req.url);
|
|
40
|
+
let pathname = __normalize(__normalize(url.split("?"))[0]);
|
|
41
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(pathname !== mount)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith(`${mount}/`)))))) {
|
|
42
|
+
__call(failed, 404, "NotFound");
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (__requireBoolean(mount !== "/")) {
|
|
46
|
+
req.url = __normalize(url.slice(__normalize(mount.length)));
|
|
47
|
+
if (__requireBoolean(__requireBoolean(__normalize(req.url) === "") || __requireBoolean(__normalize(req.url.startsWith("?"))))) {
|
|
48
|
+
req.url = `/${__normalize(req.url)}`;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let done = __withArity((error) => {
|
|
52
|
+
error = __boundary(error);
|
|
53
|
+
if (__requireBoolean(__normalize(res.headersSent))) {
|
|
54
|
+
__normalize(res.destroy());
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
let status = 404;
|
|
58
|
+
let code = "NotFound";
|
|
59
|
+
if (__requireBoolean(error !== null)) {
|
|
60
|
+
if (__normalize(error.status) === 400) {
|
|
61
|
+
status = 400;
|
|
62
|
+
code = "InvalidPath";
|
|
63
|
+
} else if (__normalize(error.status) === 403) {
|
|
64
|
+
status = 403;
|
|
65
|
+
code = "Forbidden";
|
|
66
|
+
} else if (__normalize(error.status) === 416) {
|
|
67
|
+
status = 416;
|
|
68
|
+
code = "RangeNotSatisfiable";
|
|
69
|
+
} else if (__normalize(error.status) === 404) {
|
|
70
|
+
status = 404;
|
|
71
|
+
} else {
|
|
72
|
+
status = 500;
|
|
73
|
+
code = "InternalServerError";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
__call(failed, status, code);
|
|
77
|
+
return null;
|
|
78
|
+
}, [0], "closure");
|
|
79
|
+
let serve = __normalize(this.#serve);
|
|
80
|
+
__call(serve, req, res, done);
|
|
81
|
+
return null;
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export function staticOptions(root, spec) {
|
|
86
|
+
__requireArity(arguments.length, [0, 1], "staticOptions");
|
|
87
|
+
root = __boundary(root);
|
|
88
|
+
spec = __boundary(spec);
|
|
89
|
+
if (__requireBoolean(spec === null)) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
|
|
93
|
+
throw "static must be a map";
|
|
94
|
+
}
|
|
95
|
+
let allowed = ["path", "directory", "index"];
|
|
96
|
+
for (const [key, value] of __entries(spec)) {
|
|
97
|
+
if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
|
|
98
|
+
throw `Unknown static option: ${key}`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
let mount = __normalize(spec.path);
|
|
102
|
+
if (__requireBoolean(mount === null)) {
|
|
103
|
+
mount = "/";
|
|
104
|
+
}
|
|
105
|
+
let pattern = new (__hostGlobal(["RegExp"]))("^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$");
|
|
106
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(mount))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(mount)))))) {
|
|
107
|
+
throw "Static path must be an absolute URL prefix";
|
|
108
|
+
}
|
|
109
|
+
if (__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(__normalize(mount.endsWith("/"))))) {
|
|
110
|
+
mount = __normalize(mount.slice(0, __finite(-1)));
|
|
111
|
+
}
|
|
112
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.directory)))) || __requireBoolean(__normalize(spec.directory.trim()) === ""))) {
|
|
113
|
+
throw "Static directory is required";
|
|
114
|
+
}
|
|
115
|
+
let index = __normalize(spec.index);
|
|
116
|
+
if (__requireBoolean(index === null)) {
|
|
117
|
+
index = "index.html";
|
|
118
|
+
}
|
|
119
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
|
|
120
|
+
throw "Static index must be a file name";
|
|
121
|
+
}
|
|
122
|
+
return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index };
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=static_files.mjs.map
|
|
@@ -0,0 +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\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\"]\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 return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\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 done = (error)\n capture res\n capture failed\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 failed(status, code)\n serve = @serve\n serve(req, res, done)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/tokens.mjs
CHANGED
|
@@ -2,6 +2,8 @@ import * as jwt from "jsonwebtoken";
|
|
|
2
2
|
import * as crypto from "node:crypto";
|
|
3
3
|
import {
|
|
4
4
|
hostGlobal as __hostGlobal,
|
|
5
|
+
fromJson as __fromJson,
|
|
6
|
+
toJson as __toJson,
|
|
5
7
|
isNumber as __isNumber,
|
|
6
8
|
isString as __isString,
|
|
7
9
|
isBool as __isBool,
|
|
@@ -55,12 +57,25 @@ export class Tokens {
|
|
|
55
57
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.iat))))) || __requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.exp)))))) || __requireBoolean(__normalize(claims.exp) <= __normalize(claims.iat))) || __requireBoolean(__finite(__normalize(claims.exp) - __normalize(claims.iat)) > __normalize(settings.ttlSeconds))) || __requireBoolean(__finite(__normalize(claims.iat) * 1000) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
56
58
|
throw "InvalidToken";
|
|
57
59
|
}
|
|
58
|
-
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) <
|
|
60
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) < 0)) || __requireBoolean(__normalize(claims.validatedAt) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
59
61
|
throw "InvalidToken";
|
|
60
62
|
}
|
|
61
63
|
return claims;
|
|
62
64
|
return null;
|
|
63
65
|
}
|
|
66
|
+
renew(claims) {
|
|
67
|
+
__requireArity(arguments.length, [0], "renew");
|
|
68
|
+
claims = __boundary(claims);
|
|
69
|
+
if (__requireBoolean(__finite(__normalize(claims.exp) * 1000) <= __normalize(__hostGlobal(["Date"]).now()))) {
|
|
70
|
+
throw "TokenExpired";
|
|
71
|
+
}
|
|
72
|
+
let updated = __fromJson(__toJson(claims));
|
|
73
|
+
let now = __normalize(__hostGlobal(["Math"]).floor(__finite(__normalize(__hostGlobal(["Date"]).now()) / 1000)));
|
|
74
|
+
updated.iat = now;
|
|
75
|
+
updated.exp = __numericAdd(now, __normalize(this.#settings.ttlSeconds));
|
|
76
|
+
return updated;
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
64
79
|
sign(claims) {
|
|
65
80
|
__requireArity(arguments.length, [0], "sign");
|
|
66
81
|
claims = __boundary(claims);
|
package/dist/tokens.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt <
|
|
1
|
+
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:renew(claims)\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n updated = from_json(to_json(claims))\n now = Math/floor(Date/now() / 1000)\n updated.iat = now\n updated.exp = now + @settings.ttlSeconds\n return updated\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lango-project/lango-server",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "A small JSON HTTP server for Lango applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -19,21 +19,26 @@
|
|
|
19
19
|
"files": [
|
|
20
20
|
"dist/**",
|
|
21
21
|
"src/*.lango",
|
|
22
|
+
"src/*.lua",
|
|
22
23
|
"README.md",
|
|
23
24
|
"LICENSE",
|
|
24
25
|
"NOTICE"
|
|
25
26
|
],
|
|
26
27
|
"scripts": {
|
|
27
28
|
"build": "lango run tools/clean.lango && lango build src/library.lango --out dist/library.mjs && lango build src/server.lango --out dist/cli/server.mjs --executable && lango build src/worker.lango --out dist/worker.mjs && lango build examples/application/handlers.lango --out examples/application/dist/handlers.mjs && lango build src/postgres_worker.lango --out dist/postgres_worker.mjs && lango build examples/database/handlers.lango --out examples/database/dist/handlers.mjs",
|
|
28
|
-
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/standalone.lango --build-dir .test-output/standalone",
|
|
29
|
+
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/route_parameters.lango --build-dir .test-output/route-parameters && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone",
|
|
29
30
|
"start": "node dist/cli/server.mjs examples/application",
|
|
30
31
|
"prepack": "npm run build",
|
|
31
|
-
"test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres"
|
|
32
|
+
"test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres",
|
|
33
|
+
"test:longpoll": "lango build src/test/longpoll_handlers.lango --out .test-output/longpoll_handlers.mjs && lango test src/test/longpoll.lango --build-dir .test-output/longpoll && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/standalone.lango --build-dir .test-output/standalone-longpoll",
|
|
34
|
+
"test:middleware": "lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/middleware.lango --build-dir .test-output/middleware"
|
|
32
35
|
},
|
|
33
36
|
"dependencies": {
|
|
34
37
|
"jsonwebtoken": "^9.0.3",
|
|
35
38
|
"pg": "^8.23.1",
|
|
36
|
-
"piscina": "^5.3.2"
|
|
39
|
+
"piscina": "^5.3.2",
|
|
40
|
+
"redis": "^5.12.1",
|
|
41
|
+
"serve-static": "^2.2.1"
|
|
37
42
|
},
|
|
38
43
|
"devDependencies": {
|
|
39
44
|
"@lango-project/lango-js": "^0.1.13"
|
package/src/builder.lango
CHANGED
|
@@ -12,7 +12,9 @@ import "./server"
|
|
|
12
12
|
export class Builder(root = null)
|
|
13
13
|
methods
|
|
14
14
|
configure(settings)
|
|
15
|
+
addMiddleware(name, spec)
|
|
15
16
|
endpoint(spec)
|
|
17
|
+
longpoll(spec)
|
|
16
18
|
group(spec)
|
|
17
19
|
include(spec)
|
|
18
20
|
event(spec)
|
|
@@ -30,10 +32,18 @@ Builder:configure(settings)
|
|
|
30
32
|
@settings[key] = value
|
|
31
33
|
return @this
|
|
32
34
|
|
|
35
|
+
Builder:addMiddleware(name, spec)
|
|
36
|
+
@routes.addMiddleware(name, spec)
|
|
37
|
+
return @this
|
|
38
|
+
|
|
33
39
|
Builder:endpoint(spec)
|
|
34
40
|
@routes.endpoint(spec)
|
|
35
41
|
return @this
|
|
36
42
|
|
|
43
|
+
Builder:longpoll(spec)
|
|
44
|
+
@routes.longpoll(spec)
|
|
45
|
+
return @this
|
|
46
|
+
|
|
37
47
|
Builder:group(spec)
|
|
38
48
|
return new Group(@routes, spec)
|
|
39
49
|
|
|
@@ -50,4 +60,5 @@ Builder:build()
|
|
|
50
60
|
settings: options(@root, @settings)
|
|
51
61
|
routes: @routes.definitions()
|
|
52
62
|
events: @routes.events()
|
|
63
|
+
middlewares: @routes.middlewares()
|
|
53
64
|
})
|
package/src/endpoint.lango
CHANGED
|
@@ -1,21 +1,27 @@
|
|
|
1
|
+
import "./route_pattern"
|
|
2
|
+
routePattern(path)
|
|
3
|
+
import "./middleware"
|
|
4
|
+
middlewareName(name)
|
|
5
|
+
|
|
1
6
|
export class Endpoint(spec)
|
|
2
7
|
properties
|
|
3
8
|
path
|
|
4
9
|
module
|
|
5
10
|
handler
|
|
6
11
|
auth
|
|
12
|
+
middleware
|
|
7
13
|
|
|
8
14
|
Endpoint(spec)
|
|
9
|
-
|
|
10
|
-
throw "Endpoint requires an absolute URL path"
|
|
11
|
-
if spec.path.includes("*") and (!spec.path.endsWith("/*") or spec.path.indexOf("*") != spec.path.lastIndexOf("*"))
|
|
12
|
-
throw "Only trailing /* wildcards are supported"
|
|
15
|
+
routePattern(spec.path)
|
|
13
16
|
for ["module", "handler"] as key
|
|
14
17
|
if !is_string(spec[key]) or spec[key] == ""
|
|
15
18
|
throw "Endpoint requires ${key}"
|
|
16
19
|
@path = spec.path
|
|
17
20
|
@module = spec.module
|
|
18
21
|
@handler = spec.handler
|
|
22
|
+
@middleware = spec.middleware
|
|
23
|
+
if @middleware != null
|
|
24
|
+
middlewareName(@middleware)
|
|
19
25
|
@auth = spec.auth
|
|
20
26
|
if @auth == null
|
|
21
27
|
@auth = "login"
|
package/src/group.lango
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import js global Object
|
|
2
|
+
|
|
1
3
|
export class Group(routes, spec, prefix = "", inheritedModule = null, inheritedAuth = null)
|
|
2
4
|
methods
|
|
3
5
|
endpoint(spec)
|
|
6
|
+
longpoll(spec)
|
|
4
7
|
group(spec)
|
|
5
8
|
include(spec)
|
|
6
9
|
|
|
@@ -30,9 +33,20 @@ Group:endpoint(spec)
|
|
|
30
33
|
module: mod
|
|
31
34
|
handler: spec.handler
|
|
32
35
|
auth: auth
|
|
36
|
+
middleware: spec.middleware
|
|
33
37
|
})
|
|
34
38
|
return @this
|
|
35
39
|
|
|
40
|
+
Group:longpoll(spec)
|
|
41
|
+
item = Object/assign({}, spec)
|
|
42
|
+
item.path = "${@prefix}${spec.path}"
|
|
43
|
+
if item.auth == null
|
|
44
|
+
item.auth = @auth
|
|
45
|
+
if item.fallback != null
|
|
46
|
+
item.fallback = "${@prefix}${item.fallback}"
|
|
47
|
+
@routes.longpoll(item)
|
|
48
|
+
return @this
|
|
49
|
+
|
|
36
50
|
Group:group(spec)
|
|
37
51
|
return new Group(@routes, spec, @prefix, @module, @auth)
|
|
38
52
|
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import js global RegExp
|
|
2
|
+
|
|
3
|
+
export class HttpFailure(status, code, headers)
|
|
4
|
+
methods
|
|
5
|
+
result()
|
|
6
|
+
|
|
7
|
+
HttpFailure(status, code, headers)
|
|
8
|
+
if !is_number(status) or status % 1 != 0 or status < 400 or status > 599
|
|
9
|
+
throw "Rejected response requires an error status"
|
|
10
|
+
pattern = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,63}$")
|
|
11
|
+
if !is_string(code) or !pattern.test(code)
|
|
12
|
+
throw "Rejected response requires an error code"
|
|
13
|
+
@status = status
|
|
14
|
+
@code = code
|
|
15
|
+
@headers = from_json(to_json(headers))
|
|
16
|
+
if status == 401
|
|
17
|
+
@headers["www-authenticate"] = "Bearer"
|
|
18
|
+
|
|
19
|
+
HttpFailure:result()
|
|
20
|
+
return {
|
|
21
|
+
status: @status
|
|
22
|
+
headers: from_json(to_json(@headers))
|
|
23
|
+
body: to_json({
|
|
24
|
+
error: @code
|
|
25
|
+
})
|
|
26
|
+
}
|
package/src/longpoll.lua
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
-- Atomic channel generation, trimming, publication and cursor validation.
|
|
2
|
+
local stream, meta = KEYS[1], KEYS[2]
|
|
3
|
+
local operation, candidate = ARGV[1], ARGV[2]
|
|
4
|
+
local retention, maximum = tonumber(ARGV[3]), tonumber(ARGV[4])
|
|
5
|
+
local now = redis.call('TIME')
|
|
6
|
+
local milliseconds = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
|
|
7
|
+
local generation = redis.call('HGET', meta, 'generation')
|
|
8
|
+
if not generation then
|
|
9
|
+
redis.call('DEL', stream)
|
|
10
|
+
generation = candidate
|
|
11
|
+
redis.call('HSET', meta, 'generation', generation, 'floor', '0-0', 'last', '0-0')
|
|
12
|
+
redis.call('PEXPIRE', meta, retention)
|
|
13
|
+
end
|
|
14
|
+
local function compare(a, b)
|
|
15
|
+
local am, as = string.match(a, '^(%d+)%-(%d+)$')
|
|
16
|
+
local bm, bs = string.match(b, '^(%d+)%-(%d+)$')
|
|
17
|
+
if #am ~= #bm then return #am < #bm end
|
|
18
|
+
if am ~= bm then return am < bm end
|
|
19
|
+
if #as ~= #bs then return #as < #bs end
|
|
20
|
+
return as < bs
|
|
21
|
+
end
|
|
22
|
+
local floor = redis.call('HGET', meta, 'floor')
|
|
23
|
+
local cutoff = tostring(math.max(0, milliseconds - retention)) .. '-0'
|
|
24
|
+
local removed = redis.call('XREVRANGE', stream, '(' .. cutoff, '-', 'COUNT', 1)
|
|
25
|
+
if #removed > 0 and compare(floor, removed[1][1]) then floor = removed[1][1] end
|
|
26
|
+
redis.call('XTRIM', stream, 'MINID', cutoff)
|
|
27
|
+
if operation == 'publish' then
|
|
28
|
+
local id = redis.call('XADD', stream, '*', 'data', ARGV[7])
|
|
29
|
+
redis.call('HSET', meta, 'last', id)
|
|
30
|
+
local excess = redis.call('XLEN', stream) - maximum
|
|
31
|
+
if excess > 0 then
|
|
32
|
+
local old = redis.call('XRANGE', stream, '-', '+', 'COUNT', excess)
|
|
33
|
+
floor = old[#old][1]
|
|
34
|
+
redis.call('XTRIM', stream, 'MAXLEN', maximum)
|
|
35
|
+
end
|
|
36
|
+
redis.call('HSET', meta, 'floor', floor)
|
|
37
|
+
redis.call('PEXPIRE', stream, retention)
|
|
38
|
+
redis.call('PEXPIRE', meta, retention)
|
|
39
|
+
return cjson.encode({generation=generation, id=id})
|
|
40
|
+
end
|
|
41
|
+
redis.call('HSET', meta, 'floor', floor)
|
|
42
|
+
local last = redis.call('HGET', meta, 'last')
|
|
43
|
+
if operation == 'cursor' then
|
|
44
|
+
return cjson.encode({generation=generation, id=last})
|
|
45
|
+
end
|
|
46
|
+
local epoch, position = ARGV[5], ARGV[6]
|
|
47
|
+
if epoch ~= '' and (epoch ~= generation or compare(position, floor) or compare(last, position)) then
|
|
48
|
+
return cjson.encode({resyncRequired=true})
|
|
49
|
+
end
|
|
50
|
+
local entries = redis.call('XRANGE', stream, '(' .. position, '+', 'COUNT', 16)
|
|
51
|
+
local messages = {}
|
|
52
|
+
local bytes = 0
|
|
53
|
+
local id = position
|
|
54
|
+
for _, entry in ipairs(entries) do
|
|
55
|
+
local data = entry[2][2]
|
|
56
|
+
if bytes + string.len(data) > 1048576 then break end
|
|
57
|
+
bytes = bytes + string.len(data)
|
|
58
|
+
id = entry[1]
|
|
59
|
+
table.insert(messages, {id=id, data=data})
|
|
60
|
+
end
|
|
61
|
+
return cjson.encode({generation=generation, id=id, messages=messages})
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import js "redis" as redis
|
|
2
|
+
import js "node:crypto" as crypto
|
|
3
|
+
import js "node:fs" as fs
|
|
4
|
+
import js "node:path" as path
|
|
5
|
+
import js "node:module" as modules
|
|
6
|
+
import js global Buffer
|
|
7
|
+
import js global Promise
|
|
8
|
+
import js global process
|
|
9
|
+
import js global JSON
|
|
10
|
+
import js global RegExp
|
|
11
|
+
import js global Object
|
|
12
|
+
import js global setTimeout
|
|
13
|
+
import js global clearTimeout
|
|
14
|
+
|
|
15
|
+
export class LongpollBroker(settings, routes)
|
|
16
|
+
methods
|
|
17
|
+
open()
|
|
18
|
+
close()
|
|
19
|
+
route(path)
|
|
20
|
+
publish(path, key, data)
|
|
21
|
+
cursor(path, key)
|
|
22
|
+
read(path, key, cursor)
|
|
23
|
+
|
|
24
|
+
LongpollBroker(settings, routes)
|
|
25
|
+
@routes = Object/create(null)
|
|
26
|
+
for routes as item
|
|
27
|
+
if item.kind == "longpoll"
|
|
28
|
+
@routes[item.path] = item
|
|
29
|
+
@settings = settings.redis
|
|
30
|
+
@client = null
|
|
31
|
+
@script = null
|
|
32
|
+
if Object/keys(@routes).length > 0 and @settings == null
|
|
33
|
+
throw "Longpoll routes require Redis configuration"
|
|
34
|
+
@root = settings.root
|
|
35
|
+
|
|
36
|
+
LongpollBroker:route(path)
|
|
37
|
+
if Object/hasOwn(@routes, path)
|
|
38
|
+
return @routes[path]
|
|
39
|
+
return null
|
|
40
|
+
|
|
41
|
+
LongpollBroker:open()
|
|
42
|
+
if Object/keys(@routes).length == 0
|
|
43
|
+
return Promise/resolve(null)
|
|
44
|
+
resolver = modules/createRequire(path/join(@root, "package.json"))
|
|
45
|
+
entry = resolver.resolve("@lango-project/lango-server")
|
|
46
|
+
@script = fs/readFileSync(path/join(path/dirname(entry), "../src/longpoll.lua"), "utf8")
|
|
47
|
+
config = @settings
|
|
48
|
+
name = config.connectionEnv
|
|
49
|
+
@client = redis/createClient({
|
|
50
|
+
url: process.env[name]
|
|
51
|
+
disableOfflineQueue: true
|
|
52
|
+
commandsQueueMaxLength: 2048
|
|
53
|
+
socket: {
|
|
54
|
+
connectTimeout: 2000
|
|
55
|
+
reconnectStrategy: 500
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
client = @client
|
|
59
|
+
client.on("error", (error)
|
|
60
|
+
return null
|
|
61
|
+
)
|
|
62
|
+
return bounded(client.connect(), 3000)
|
|
63
|
+
|
|
64
|
+
LongpollBroker:close()
|
|
65
|
+
if @client != null and @client.isOpen
|
|
66
|
+
@client.destroy()
|
|
67
|
+
return null
|
|
68
|
+
|
|
69
|
+
LongpollBroker:publish(path, key, data)
|
|
70
|
+
body = JSON/stringify(data)
|
|
71
|
+
if !is_string(body) or Buffer/byteLength(body) > 262144
|
|
72
|
+
return Promise/reject("Longpoll message must be JSON within 262144 bytes")
|
|
73
|
+
return execute("publish", path, key, null, body)
|
|
74
|
+
|
|
75
|
+
LongpollBroker:cursor(path, key)
|
|
76
|
+
return execute("cursor", path, key, null, "")
|
|
77
|
+
|
|
78
|
+
LongpollBroker:read(path, key, cursor)
|
|
79
|
+
return execute("read", path, key, cursor, "")
|
|
80
|
+
|
|
81
|
+
LongpollBroker:execute(operation, path, key, cursor, body)
|
|
82
|
+
item = route(path)
|
|
83
|
+
if item == null
|
|
84
|
+
return Promise/reject("Unknown longpoll path")
|
|
85
|
+
if !is_string(key) or key == "" or Buffer/byteLength(key) > 1024
|
|
86
|
+
return Promise/reject("Longpoll key must contain 1 to 1024 bytes")
|
|
87
|
+
if @client == null or !@client.isReady
|
|
88
|
+
return Promise/reject("RedisUnavailable")
|
|
89
|
+
hash = crypto/createHash("sha256")
|
|
90
|
+
hash.update(to_json([@settings.namespace, path, key]))
|
|
91
|
+
channel = hash.digest("hex")
|
|
92
|
+
prefix = "lango:longpoll:{${channel}}"
|
|
93
|
+
position = {
|
|
94
|
+
generation: ""
|
|
95
|
+
id: "0-0"
|
|
96
|
+
}
|
|
97
|
+
if cursor != null
|
|
98
|
+
position = decode(cursor, channel)
|
|
99
|
+
if position == null
|
|
100
|
+
return Promise/resolve({
|
|
101
|
+
resyncRequired: true
|
|
102
|
+
})
|
|
103
|
+
pending = @client.eval(@script, {
|
|
104
|
+
keys: ["${prefix}:stream", "${prefix}:meta"]
|
|
105
|
+
arguments: [operation, crypto/randomUUID(), "${item.retentionMs}", "${item.maxMessages}", position.generation, position.id, body]
|
|
106
|
+
})
|
|
107
|
+
return chain bounded(pending, 3000)
|
|
108
|
+
then(raw)
|
|
109
|
+
capture channel
|
|
110
|
+
capture operation
|
|
111
|
+
result = JSON/parse(raw)
|
|
112
|
+
if result.resyncRequired == true
|
|
113
|
+
return result
|
|
114
|
+
result.cursor = encode(channel, result.generation, result.id)
|
|
115
|
+
if operation != "read"
|
|
116
|
+
return result.cursor
|
|
117
|
+
messages = []
|
|
118
|
+
if is_array(result.messages)
|
|
119
|
+
for result.messages as message
|
|
120
|
+
messages.add({
|
|
121
|
+
id: encode(channel, result.generation, message.id)
|
|
122
|
+
data: JSON/parse(message.data)
|
|
123
|
+
})
|
|
124
|
+
return {
|
|
125
|
+
messages: messages
|
|
126
|
+
cursor: result.cursor
|
|
127
|
+
resyncRequired: false
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
encode(channel, generation, id)
|
|
131
|
+
buffer = Buffer/from(to_json([channel, generation, id]))
|
|
132
|
+
return buffer.toString("base64url")
|
|
133
|
+
|
|
134
|
+
decode(cursor, channel)
|
|
135
|
+
if !is_string(cursor) or cursor.length > 512
|
|
136
|
+
return null
|
|
137
|
+
try
|
|
138
|
+
buffer = Buffer/from(cursor, "base64url")
|
|
139
|
+
parts = from_json(buffer.toString("utf8"))
|
|
140
|
+
if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])
|
|
141
|
+
return null
|
|
142
|
+
pattern = new RegExp("^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$")
|
|
143
|
+
if !pattern.test(parts[2]) or parts[2].length > 40
|
|
144
|
+
return null
|
|
145
|
+
return {
|
|
146
|
+
generation: parts[1]
|
|
147
|
+
id: parts[2]
|
|
148
|
+
}
|
|
149
|
+
catch error
|
|
150
|
+
return null
|
|
151
|
+
|
|
152
|
+
bounded(pending, ms)
|
|
153
|
+
expired = Promise/withResolvers()
|
|
154
|
+
fail = ()
|
|
155
|
+
capture expired
|
|
156
|
+
expired.reject("RedisUnavailable")
|
|
157
|
+
timer = setTimeout(fail, ms)
|
|
158
|
+
return chain Promise/race([pending, expired.promise])
|
|
159
|
+
finally
|
|
160
|
+
capture timer
|
|
161
|
+
clearTimeout(timer)
|