@lango-project/lango-server 0.1.2 → 0.2.0

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.
@@ -38,7 +38,7 @@ export function options(root, supplied = null) {
38
38
  __requireArity(arguments.length, [0], "options");
39
39
  root = __boundary(root);
40
40
  supplied = __boundary(supplied);
41
- let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 1048576, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
41
+ let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 2097152, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
42
42
  if (__requireBoolean(supplied !== null)) {
43
43
  for (const [key, value] of __entries(supplied)) {
44
44
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(result, key)))) || __requireBoolean(key === "root"))) {
@@ -115,7 +115,7 @@ export function deployment(directory) {
115
115
  }
116
116
  seen.push(name);
117
117
  if (name === "static") {
118
- attributes(tag, ["path", "directory", "index"]);
118
+ attributes(tag, ["path", "directory", "index", "fallback", "runtime"]);
119
119
  settings.static = __normalize(tag.attributes());
120
120
  continue;
121
121
  } else if (name === "http") {
@@ -1 +1 @@
1
- {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 1048576\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
1
+ {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 2097152\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
@@ -3,6 +3,7 @@ import * as path from "node:path";
3
3
  import * as files from "serve-static";
4
4
  import {
5
5
  hostGlobal as __hostGlobal,
6
+ hostGlobalCall as __hostGlobalCall,
6
7
  isNumber as __isNumber,
7
8
  isString as __isString,
8
9
  isBool as __isBool,
@@ -21,6 +22,7 @@ import {
21
22
  export class StaticFiles {
22
23
  #settings;
23
24
  #serve;
25
+ #runtime;
24
26
  constructor(settings) {
25
27
  __requireArity(arguments.length, [0], "constructor");
26
28
  settings = __boundary(settings);
@@ -28,7 +30,11 @@ export class StaticFiles {
28
30
  if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
29
31
  throw "Static directory must be a directory";
30
32
  }
33
+ if (__requireBoolean(__requireBoolean(__normalize(settings.fallback) !== null) && __requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(path.join(__normalize(settings.directory), __normalize(settings.fallback))))).isFile()))))) {
34
+ throw "Static fallback must be a file";
35
+ }
31
36
  this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
37
+ this.#runtime = __normalize(files.default(__normalize(settings.directory), { index: false, dotfiles: "allow", fallthrough: false, redirect: false }));
32
38
  }
33
39
  receive(req, res, failed) {
34
40
  __requireArity(arguments.length, [0, 1, 2], "receive");
@@ -48,39 +54,88 @@ export class StaticFiles {
48
54
  req.url = `/${__normalize(req.url)}`;
49
55
  }
50
56
  }
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;
57
+ let local = __normalize(__normalize(req.url.split("?"))[0]);
58
+ let decoded = null;
59
+ try {
60
+ decoded = __hostGlobalCall(["decodeURIComponent"], local);
61
+ } catch (error) {
62
+ __call(failed, 400, "InvalidPath");
63
+ return null;
64
+ }
65
+ if (__requireBoolean(__requireBoolean(__normalize(decoded.includes("\\"))) || __requireBoolean(__normalize(decoded.includes(__normalize(__hostGlobal(["String"]).fromCharCode(0))))))) {
66
+ __call(failed, 400, "InvalidPath");
67
+ return null;
68
+ }
69
+ let segments = __normalize(decoded.split("/"));
70
+ let runtime = false;
71
+ for (const [index, segment] of __entries(segments)) {
72
+ if (__requireBoolean(__normalize(segment.startsWith(".")))) {
73
+ if (__requireBoolean(__requireBoolean(__requireBoolean(index === 1) && __requireBoolean(segment === ".lango")) && __requireBoolean(__normalize(this.#settings.runtime)))) {
74
+ runtime = true;
71
75
  } else {
72
- status = 500;
73
- code = "InternalServerError";
76
+ __call(failed, 403, "Forbidden");
77
+ return null;
74
78
  }
75
79
  }
76
- __call(failed, status, code);
80
+ }
81
+ let done = __withArity((error) => {
82
+ error = __boundary(error);
83
+ this.#failure(req, res, failed, error, decoded);
77
84
  return null;
78
85
  }, [0], "closure");
79
86
  let serve = __normalize(this.#serve);
87
+ if (__requireBoolean(runtime)) {
88
+ serve = __normalize(this.#runtime);
89
+ }
80
90
  __call(serve, req, res, done);
81
91
  return null;
82
92
  return null;
83
93
  }
94
+ #failure(req, res, failed, error, pathname = null) {
95
+ __requireArity(arguments.length, [0, 1, 2, 3], "failure");
96
+ req = __boundary(req);
97
+ res = __boundary(res);
98
+ failed = __boundary(failed);
99
+ error = __boundary(error);
100
+ pathname = __boundary(pathname);
101
+ if (__requireBoolean(__normalize(res.headersSent))) {
102
+ __normalize(res.destroy());
103
+ return null;
104
+ }
105
+ let status = 404;
106
+ let code = "NotFound";
107
+ if (__requireBoolean(error !== null)) {
108
+ if (__normalize(error.status) === 400) {
109
+ status = 400;
110
+ code = "InvalidPath";
111
+ } else if (__normalize(error.status) === 403) {
112
+ status = 403;
113
+ code = "Forbidden";
114
+ } else if (__normalize(error.status) === 416) {
115
+ status = 416;
116
+ code = "RangeNotSatisfiable";
117
+ } else if (__normalize(error.status) === 404) {
118
+ status = 404;
119
+ } else {
120
+ status = 500;
121
+ code = "InternalServerError";
122
+ }
123
+ }
124
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(status === 404) && __requireBoolean(pathname !== null)) && __requireBoolean(__normalize(this.#settings.fallback) !== null)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith("/.lango"))))) && __requireBoolean(__normalize(path.posix.extname(pathname)) === "")) && __requireBoolean(acceptsHTML(req.headers.accept)))) {
125
+ req.url = `/${__normalize(this.#settings.fallback)}`;
126
+ let done = __withArity((error) => {
127
+ error = __boundary(error);
128
+ this.#failure(req, res, failed, error);
129
+ return null;
130
+ }, [0], "closure");
131
+ let serve = __normalize(this.#serve);
132
+ __call(serve, req, res, done);
133
+ return null;
134
+ }
135
+ __call(failed, status, code);
136
+ return null;
137
+ return null;
138
+ }
84
139
  }
85
140
  export function staticOptions(root, spec) {
86
141
  __requireArity(arguments.length, [0, 1], "staticOptions");
@@ -92,7 +147,7 @@ export function staticOptions(root, spec) {
92
147
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
93
148
  throw "static must be a map";
94
149
  }
95
- let allowed = ["path", "directory", "index"];
150
+ let allowed = ["path", "directory", "index", "fallback", "runtime"];
96
151
  for (const [key, value] of __entries(spec)) {
97
152
  if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
98
153
  throw `Unknown static option: ${key}`;
@@ -119,7 +174,48 @@ export function staticOptions(root, spec) {
119
174
  if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
120
175
  throw "Static index must be a file name";
121
176
  }
122
- return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index };
177
+ let fallback = __normalize(spec.fallback);
178
+ if (__requireBoolean(__requireBoolean(fallback !== null) && __requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(fallback))) || __requireBoolean(fallback === "")) || __requireBoolean(__normalize(fallback.startsWith(".")))) || __requireBoolean(__normalize(fallback.includes("/")))) || __requireBoolean(__normalize(fallback.includes("\\")))))) {
179
+ throw "Static fallback must be a file name";
180
+ }
181
+ let runtime = __normalize(spec.runtime);
182
+ if (__requireBoolean(__requireBoolean(runtime === null) || __requireBoolean(runtime === "false"))) {
183
+ runtime = false;
184
+ }
185
+ if (__requireBoolean(runtime === "true")) {
186
+ runtime = true;
187
+ }
188
+ if (__requireBoolean(!__requireBoolean(__isBool(runtime)))) {
189
+ throw "Static runtime must be boolean";
190
+ }
191
+ return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index, fallback: fallback, runtime: runtime };
192
+ return null;
193
+ }
194
+
195
+ function acceptsHTML(value) {
196
+ __requireArity(arguments.length, [0], "acceptsHTML");
197
+ value = __boundary(value);
198
+ if (__requireBoolean(!__requireBoolean(__isString(value)))) {
199
+ return false;
200
+ }
201
+ let zero = new (__hostGlobal(["RegExp"]))("^q\\s*=\\s*0(?:\\.0*)?$", "i");
202
+ for (const range of __normalize(value.split(","))) {
203
+ let parts = __normalize(range.split(";"));
204
+ let media = __normalize(parts[0]);
205
+ let type = __normalize(__normalize(media.trim()).toLowerCase());
206
+ if (__requireBoolean(__requireBoolean(type === "text/html") || __requireBoolean(type === "application/xhtml+xml"))) {
207
+ let allowed = true;
208
+ for (const parameter of __normalize(parts.slice(1))) {
209
+ if (__requireBoolean(__normalize(zero.test(__normalize(parameter.trim()))))) {
210
+ allowed = false;
211
+ }
212
+ }
213
+ if (__requireBoolean(allowed)) {
214
+ return true;
215
+ }
216
+ }
217
+ }
218
+ return false;
123
219
  return null;
124
220
  }
125
221
  //# sourceMappingURL=static_files.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/options.mjs CHANGED
@@ -38,7 +38,7 @@ export function options(root, supplied = null) {
38
38
  __requireArity(arguments.length, [0], "options");
39
39
  root = __boundary(root);
40
40
  supplied = __boundary(supplied);
41
- let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 1048576, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
41
+ let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 2097152, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
42
42
  if (__requireBoolean(supplied !== null)) {
43
43
  for (const [key, value] of __entries(supplied)) {
44
44
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(result, key)))) || __requireBoolean(key === "root"))) {
@@ -115,7 +115,7 @@ export function deployment(directory) {
115
115
  }
116
116
  seen.push(name);
117
117
  if (name === "static") {
118
- attributes(tag, ["path", "directory", "index"]);
118
+ attributes(tag, ["path", "directory", "index", "fallback", "runtime"]);
119
119
  settings.static = __normalize(tag.attributes());
120
120
  continue;
121
121
  } else if (name === "http") {
@@ -1 +1 @@
1
- {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 1048576\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
1
+ {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 2097152\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
package/dist/runtime.mjs CHANGED
@@ -43,7 +43,12 @@ export class Runtime {
43
43
  constructor(definition) {
44
44
  __requireArity(arguments.length, [0], "constructor");
45
45
  definition = __boundary(definition);
46
- this.#serverContext = new ServerContext(__normalize(definition.routes));
46
+ let refresh = __withArity((tokens) => {
47
+ tokens = __boundary(tokens);
48
+ return this.refreshTokens(tokens);
49
+ return null;
50
+ }, [0], "closure");
51
+ this.#serverContext = new ServerContext(__normalize(definition.routes), refresh);
47
52
  this.#definition = definition;
48
53
  this.#routes = [];
49
54
  this.#events = { };
@@ -262,6 +267,7 @@ export class Runtime {
262
267
  validatedAt = __boundary(validatedAt);
263
268
  if (__requireBoolean(__requireBoolean(!__requireBoolean(fresh)) && __requireBoolean(__isNumber(validatedAt)))) {
264
269
  stampValidation(claims, validatedAt);
270
+ __normalize(__contextGet("token").renew());
265
271
  }
266
272
  if (__requireBoolean(__requireBoolean(__normalize(route.auth) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasAuth(__normalize(route.auth))))))) {
267
273
  throw { status: 401, error: "Unauthorized" };
@@ -315,7 +321,7 @@ export class Runtime {
315
321
  let result = __normalize(__contextGet("response").result(body));
316
322
  let updated = this.#tokenClaims(__contextGet("token"), claims, __normalize(result.status) < 400);
317
323
  result.headers["x-lango-token"] = __normalize(this.#tokens.sign(updated));
318
- if (__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.requestEvent)) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
324
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(task.internal) !== true) && __requireBoolean(__normalize(this.#definition.settings.requestEvent))) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
319
325
  return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
320
326
  }
321
327
  return result;
@@ -372,6 +378,70 @@ export class Runtime {
372
378
  return updated;
373
379
  return null;
374
380
  }
381
+ refreshTokens(tokens) {
382
+ const __contextScope = [];
383
+ try {
384
+ __requireArity(arguments.length, [0], "refreshTokens");
385
+ tokens = __boundary(tokens);
386
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isArray(tokens))) || __requireBoolean(__normalize(tokens.length) === 0)) || __requireBoolean(__normalize(tokens.length) > 64))) {
387
+ throw "Token refresh requires 1 to 64 tokens";
388
+ }
389
+ let seen = [];
390
+ for (const encoded of tokens) {
391
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(encoded))) || __requireBoolean(encoded === "")) || __requireBoolean(__normalize(encoded.length) > 16384)) || __requireBoolean(__normalize(seen.includes(encoded))))) {
392
+ throw "Invalid refresh token";
393
+ }
394
+ seen.push(encoded);
395
+ }
396
+ let owner = __normalize(__contextGet("token").clientId);
397
+ let results = [];
398
+ let pending = __normalize(__hostGlobal(["Promise"]).resolve(null));
399
+ for (const encoded of tokens) {
400
+ let child = __normalize(__hostGlobal(["Object"]).assign({ }, __contextGet("request"), { headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(__contextGet("request").headers), { authorization: `Bearer ${encoded}` })) }));
401
+ pending = this.#refreshOne(pending, results, encoded, owner, child);
402
+ }
403
+ return pending.then(__withArity((ignored) => {
404
+ ignored = __boundary(ignored);
405
+ return results;
406
+ return null;
407
+ }, [0], "closure"));
408
+ return null;
409
+ } finally {
410
+ __contextRestore(__contextScope);
411
+ }
412
+ }
413
+ #refreshOne(pending, results, encoded, owner, child) {
414
+ __requireArity(arguments.length, [0, 1, 2, 3, 4], "refreshOne");
415
+ pending = __boundary(pending);
416
+ results = __boundary(results);
417
+ encoded = __boundary(encoded);
418
+ owner = __boundary(owner);
419
+ child = __boundary(child);
420
+ return pending.then(__withArity((ignored) => {
421
+ ignored = __boundary(ignored);
422
+ let checked = null;
423
+ try {
424
+ checked = __normalize(this.#tokens.read(`Bearer ${encoded}`));
425
+ } catch (error) {
426
+ return failure(401, "Unauthorized");
427
+ }
428
+ if (__requireBoolean(__normalize(checked.clientId) !== owner)) {
429
+ return failure(401, "Unauthorized");
430
+ }
431
+ return this.handle({ request: child, body: "{}", internal: true });
432
+ return null;
433
+ }, [0], "closure")).then(__withArity((result) => {
434
+ result = __boundary(result);
435
+ let updated = null;
436
+ if (__requireBoolean(__normalize(result.status) < 400)) {
437
+ updated = result.headers["x-lango-token"];
438
+ }
439
+ __add(results, { previous: encoded, token: updated, status: __normalize(result.status) });
440
+ return null;
441
+ return null;
442
+ }, [0], "closure"));
443
+ return null;
444
+ }
375
445
  #event(name, input) {
376
446
  const __contextScope = [];
377
447
  try {
@@ -418,9 +488,12 @@ export class Runtime {
418
488
  const __contextScope = [];
419
489
  try {
420
490
  let claims = __normalize(__contextGet("token").snapshot());
421
- if (__requireBoolean(__requireBoolean(!__requireBoolean(__includes("validate", __normalize(this.#events)))) || __requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000))) {
491
+ if (__requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000)) {
422
492
  return null;
423
493
  }
494
+ if (__requireBoolean(!__requireBoolean(__includes("validate", __normalize(this.#events))))) {
495
+ return __normalize(__hostGlobal(["Date"]).now());
496
+ }
424
497
  let original = __normalize(__hostGlobal(["JSON"]).stringify(claims));
425
498
  __contextScope.push(__contextSet("token", new Token(claims, true)));
426
499
  return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n\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;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n @serverContext = new ServerContext(definition.routes, refresh)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n return failure(401, \"Unauthorized\")\n log.err(\"[${request.id}] Request failed\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n closeScope(db, false)\n log.err(\"Request event failed\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA;;;;;;;;;;;AAuUA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
@@ -15,12 +15,25 @@ import {
15
15
 
16
16
  export class ServerContext {
17
17
  #routes;
18
- constructor(definitions = null) {
18
+ #refresh;
19
+ constructor(definitions = null, refresh = null) {
19
20
  definitions = __boundary(definitions);
21
+ refresh = __boundary(refresh);
20
22
  if (__requireBoolean(definitions === null)) {
21
23
  definitions = [];
22
24
  }
23
25
  this.#routes = routeInfo(definitions);
26
+ this.#refresh = refresh;
27
+ }
28
+ refreshTokens(tokens) {
29
+ __requireArity(arguments.length, [0], "refreshTokens");
30
+ tokens = __boundary(tokens);
31
+ if (__requireBoolean(__normalize(this.#refresh) === null)) {
32
+ throw "Token refresh is unavailable";
33
+ }
34
+ let refresh = __normalize(this.#refresh);
35
+ return __call(refresh, tokens);
36
+ return null;
24
37
  }
25
38
  routes() {
26
39
  return __fromJson(__toJson(__normalize(this.#routes)));
@@ -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\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
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, refresh = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n refreshTokens(tokens)\n\nServerContext(definitions = null, refresh = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n @refresh = refresh\n\nServerContext:refreshTokens(tokens)\n if @refresh == null\n throw \"Token refresh is unavailable\"\n refresh = @refresh\n return refresh(tokens)\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}