@lango-project/lango-server 0.0.0-stage → 0.1.1

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.
Files changed (134) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +710 -2
  4. package/dist/.lango/bignumber.mjs +3119 -0
  5. package/dist/.lango/runtime.mjs +683 -0
  6. package/dist/.lango/xmldom/conventions.js +429 -0
  7. package/dist/.lango/xmldom/dom-parser.js +591 -0
  8. package/dist/.lango/xmldom/dom.js +3759 -0
  9. package/dist/.lango/xmldom/entities.js +2171 -0
  10. package/dist/.lango/xmldom/errors.js +205 -0
  11. package/dist/.lango/xmldom/grammar.js +559 -0
  12. package/dist/.lango/xmldom/index.js +41 -0
  13. package/dist/.lango/xmldom/package.json +1 -0
  14. package/dist/.lango/xmldom/sax.js +983 -0
  15. package/dist/.lango/xmldom.LICENSE.md +8 -0
  16. package/dist/body_reader.mjs +179 -0
  17. package/dist/body_reader.mjs.map +1 -0
  18. package/dist/builder.mjs +84 -0
  19. package/dist/builder.mjs.map +1 -0
  20. package/dist/cli/.lango/bignumber.mjs +3119 -0
  21. package/dist/cli/.lango/runtime.mjs +683 -0
  22. package/dist/cli/.lango/xmldom/conventions.js +429 -0
  23. package/dist/cli/.lango/xmldom/dom-parser.js +591 -0
  24. package/dist/cli/.lango/xmldom/dom.js +3759 -0
  25. package/dist/cli/.lango/xmldom/entities.js +2171 -0
  26. package/dist/cli/.lango/xmldom/errors.js +205 -0
  27. package/dist/cli/.lango/xmldom/grammar.js +559 -0
  28. package/dist/cli/.lango/xmldom/index.js +41 -0
  29. package/dist/cli/.lango/xmldom/package.json +1 -0
  30. package/dist/cli/.lango/xmldom/sax.js +983 -0
  31. package/dist/cli/.lango/xmldom.LICENSE.md +8 -0
  32. package/dist/cli/body_reader.mjs +179 -0
  33. package/dist/cli/body_reader.mjs.map +1 -0
  34. package/dist/cli/database.mjs +101 -0
  35. package/dist/cli/database.mjs.map +1 -0
  36. package/dist/cli/database_options.mjs +83 -0
  37. package/dist/cli/database_options.mjs.map +1 -0
  38. package/dist/cli/database_scope.mjs +82 -0
  39. package/dist/cli/database_scope.mjs.map +1 -0
  40. package/dist/cli/endpoint.mjs +50 -0
  41. package/dist/cli/endpoint.mjs.map +1 -0
  42. package/dist/cli/longpoll_broker.mjs +214 -0
  43. package/dist/cli/longpoll_broker.mjs.map +1 -0
  44. package/dist/cli/longpoll_options.mjs +102 -0
  45. package/dist/cli/longpoll_options.mjs.map +1 -0
  46. package/dist/cli/longpoll_session.mjs +135 -0
  47. package/dist/cli/longpoll_session.mjs.map +1 -0
  48. package/dist/cli/middleware.mjs +25 -0
  49. package/dist/cli/middleware.mjs.map +1 -0
  50. package/dist/cli/options.mjs +177 -0
  51. package/dist/cli/options.mjs.map +1 -0
  52. package/dist/cli/postgres_adapter.mjs +166 -0
  53. package/dist/cli/postgres_adapter.mjs.map +1 -0
  54. package/dist/cli/routes.mjs +297 -0
  55. package/dist/cli/routes.mjs.map +1 -0
  56. package/dist/cli/server.mjs +792 -0
  57. package/dist/cli/server.mjs.map +1 -0
  58. package/dist/cli/sqlite_adapter.mjs +163 -0
  59. package/dist/cli/sqlite_adapter.mjs.map +1 -0
  60. package/dist/cli/static_files.mjs +125 -0
  61. package/dist/cli/static_files.mjs.map +1 -0
  62. package/dist/database.mjs +101 -0
  63. package/dist/database.mjs.map +1 -0
  64. package/dist/database_options.mjs +83 -0
  65. package/dist/database_options.mjs.map +1 -0
  66. package/dist/database_scope.mjs +82 -0
  67. package/dist/database_scope.mjs.map +1 -0
  68. package/dist/endpoint.mjs +50 -0
  69. package/dist/endpoint.mjs.map +1 -0
  70. package/dist/group.mjs +91 -0
  71. package/dist/group.mjs.map +1 -0
  72. package/dist/library.mjs +6 -0
  73. package/dist/library.mjs.map +1 -0
  74. package/dist/longpoll_broker.mjs +214 -0
  75. package/dist/longpoll_broker.mjs.map +1 -0
  76. package/dist/longpoll_options.mjs +102 -0
  77. package/dist/longpoll_options.mjs.map +1 -0
  78. package/dist/longpoll_session.mjs +135 -0
  79. package/dist/longpoll_session.mjs.map +1 -0
  80. package/dist/middleware.mjs +25 -0
  81. package/dist/middleware.mjs.map +1 -0
  82. package/dist/options.mjs +177 -0
  83. package/dist/options.mjs.map +1 -0
  84. package/dist/postgres_adapter.mjs +166 -0
  85. package/dist/postgres_adapter.mjs.map +1 -0
  86. package/dist/postgres_worker.mjs +119 -0
  87. package/dist/postgres_worker.mjs.map +1 -0
  88. package/dist/response.mjs +62 -0
  89. package/dist/response.mjs.map +1 -0
  90. package/dist/routes.mjs +297 -0
  91. package/dist/routes.mjs.map +1 -0
  92. package/dist/runtime.mjs +549 -0
  93. package/dist/runtime.mjs.map +1 -0
  94. package/dist/server.mjs +788 -0
  95. package/dist/server.mjs.map +1 -0
  96. package/dist/server_context.mjs +78 -0
  97. package/dist/server_context.mjs.map +1 -0
  98. package/dist/sqlite_adapter.mjs +163 -0
  99. package/dist/sqlite_adapter.mjs.map +1 -0
  100. package/dist/static_files.mjs +125 -0
  101. package/dist/static_files.mjs.map +1 -0
  102. package/dist/token.mjs +106 -0
  103. package/dist/token.mjs.map +1 -0
  104. package/dist/tokens.mjs +76 -0
  105. package/dist/tokens.mjs.map +1 -0
  106. package/dist/worker.mjs +57 -0
  107. package/dist/worker.mjs.map +1 -0
  108. package/package.json +44 -4
  109. package/src/body_reader.lango +113 -0
  110. package/src/builder.lango +64 -0
  111. package/src/database.lango +66 -0
  112. package/src/database_options.lango +57 -0
  113. package/src/database_scope.lango +59 -0
  114. package/src/endpoint.lango +30 -0
  115. package/src/group.lango +61 -0
  116. package/src/library.lango +10 -0
  117. package/src/longpoll.lua +61 -0
  118. package/src/longpoll_broker.lango +161 -0
  119. package/src/longpoll_options.lango +79 -0
  120. package/src/longpoll_session.lango +90 -0
  121. package/src/middleware.lango +10 -0
  122. package/src/options.lango +144 -0
  123. package/src/postgres_adapter.lango +138 -0
  124. package/src/postgres_worker.lango +114 -0
  125. package/src/response.lango +42 -0
  126. package/src/routes.lango +224 -0
  127. package/src/runtime.lango +382 -0
  128. package/src/server.lango +597 -0
  129. package/src/server_context.lango +58 -0
  130. package/src/sqlite_adapter.lango +127 -0
  131. package/src/static_files.lango +90 -0
  132. package/src/token.lango +70 -0
  133. package/src/tokens.lango +70 -0
  134. package/src/worker.lango +43 -0
@@ -0,0 +1,549 @@
1
+ import { ServerContext } from "./server_context.mjs";
2
+ import { Database } from "./database.mjs";
3
+ import { Token } from "./token.mjs";
4
+ import { Tokens } from "./tokens.mjs";
5
+ import { Response } from "./response.mjs";
6
+ import * as threads from "node:worker_threads";
7
+ import {
8
+ hostGlobal as __hostGlobal,
9
+ contextGet as __contextGet,
10
+ contextSet as __contextSet,
11
+ contextRestore as __contextRestore,
12
+ getClass as __getClass,
13
+ isKindof as __isKindof,
14
+ isNumber as __isNumber,
15
+ isString as __isString,
16
+ isBool as __isBool,
17
+ isObject as __isObject,
18
+ isArray as __isArray,
19
+ includes as __includes,
20
+ entries as __entries,
21
+ add as __add,
22
+ requireBoolean as __requireBoolean,
23
+ normalize as __normalize,
24
+ finite as __finite,
25
+ call as __call,
26
+ boundary as __boundary,
27
+ requireArity as __requireArity,
28
+ withArity as __withArity,
29
+ } from "./.lango/runtime.mjs";
30
+
31
+ export class Runtime {
32
+ #serverContext;
33
+ #definition;
34
+ #routes;
35
+ #events;
36
+ #tokens;
37
+ #modules;
38
+ #middlewares;
39
+ #database;
40
+ constructor(definition) {
41
+ __requireArity(arguments.length, [0], "constructor");
42
+ definition = __boundary(definition);
43
+ this.#serverContext = new ServerContext();
44
+ this.#definition = definition;
45
+ this.#routes = [];
46
+ this.#events = { };
47
+ this.#tokens = new Tokens(__normalize(definition.settings));
48
+ this.#modules = { };
49
+ this.#middlewares = __normalize(__hostGlobal(["Object"]).create(null));
50
+ this.#database = new Database(definition.settings.database, definition.settings.root);
51
+ }
52
+ preload() {
53
+ let definitions = __normalize(this.#definition.routes);
54
+ let pending = __normalize(this.#database.open());
55
+ if (__requireBoolean(__normalize(this.#definition.middlewares) !== null)) {
56
+ for (const [name, spec] of __entries(__normalize(this.#definition.middlewares))) {
57
+ pending = this.#prepareMiddleware(pending, name, spec);
58
+ }
59
+ }
60
+ for (const route of definitions) {
61
+ pending = this.#prepareRoute(pending, route);
62
+ }
63
+ let events = __normalize(this.#definition.events);
64
+ for (const [name, target] of __entries(events)) {
65
+ pending = this.#prepareEvent(pending, name, target);
66
+ }
67
+ return pending.catch(__withArity((error) => {
68
+ error = __boundary(error);
69
+ this.close();
70
+ throw error;
71
+ return null;
72
+ }, [0], "closure"));
73
+ return null;
74
+ }
75
+ close() {
76
+ __normalize(this.#database.close());
77
+ return null;
78
+ return null;
79
+ }
80
+ #prepareMiddleware(pending, name, spec) {
81
+ __requireArity(arguments.length, [0, 1, 2], "prepareMiddleware");
82
+ pending = __boundary(pending);
83
+ name = __boundary(name);
84
+ spec = __boundary(spec);
85
+ return pending.then(__withArity((ignored) => {
86
+ ignored = __boundary(ignored);
87
+ return this.#target(spec);
88
+ return null;
89
+ }, [0], "closure")).then(__withArity((handler) => {
90
+ handler = __boundary(handler);
91
+ this.#middlewares[name] = handler;
92
+ return null;
93
+ return null;
94
+ }, [0], "closure"));
95
+ return null;
96
+ }
97
+ #prepareRoute(pending, route) {
98
+ __requireArity(arguments.length, [0, 1], "prepareRoute");
99
+ pending = __boundary(pending);
100
+ route = __boundary(route);
101
+ if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
102
+ __add(this.#routes, route);
103
+ return pending;
104
+ }
105
+ return pending.then(__withArity((ignored) => {
106
+ ignored = __boundary(ignored);
107
+ return this.#target(route);
108
+ return null;
109
+ }, [0], "closure")).then(__withArity((handler) => {
110
+ handler = __boundary(handler);
111
+ let middleware = null;
112
+ let name = __normalize(route.middleware);
113
+ if (__requireBoolean(name !== null)) {
114
+ if (__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(this.#middlewares), name))))) {
115
+ throw `Middleware is not registered: ${name}`;
116
+ }
117
+ middleware = __normalize(this.#middlewares[name]);
118
+ }
119
+ __add(this.#routes, { path: __normalize(route.path), auth: __normalize(route.auth), handler: handler, middleware: middleware });
120
+ return null;
121
+ return null;
122
+ }, [0], "closure"));
123
+ return null;
124
+ }
125
+ #prepareEvent(pending, name, spec) {
126
+ __requireArity(arguments.length, [0, 1, 2], "prepareEvent");
127
+ pending = __boundary(pending);
128
+ name = __boundary(name);
129
+ spec = __boundary(spec);
130
+ return pending.then(__withArity((ignored) => {
131
+ ignored = __boundary(ignored);
132
+ return this.#target(spec);
133
+ return null;
134
+ }, [0], "closure")).then(__withArity((handler) => {
135
+ handler = __boundary(handler);
136
+ this.#events[name] = handler;
137
+ return null;
138
+ return null;
139
+ }, [0], "closure"));
140
+ return null;
141
+ }
142
+ #target(spec) {
143
+ __requireArity(arguments.length, [0], "target");
144
+ spec = __boundary(spec);
145
+ let file = __normalize(spec.module);
146
+ if (__requireBoolean(__includes(file, __normalize(this.#modules)))) {
147
+ return __normalize(__hostGlobal(["Promise"]).resolve(exported(__normalize(this.#modules[file]), __normalize(spec.handler))));
148
+ }
149
+ return import(file).then(__withArity((mod) => {
150
+ mod = __boundary(mod);
151
+ this.#modules[file] = mod;
152
+ return exported(mod, __normalize(spec.handler));
153
+ return null;
154
+ }, [0], "closure"));
155
+ return null;
156
+ }
157
+ #match(path) {
158
+ __requireArity(arguments.length, [0], "match");
159
+ path = __boundary(path);
160
+ let best = null;
161
+ let length = __finite(-1);
162
+ for (const route of __normalize(this.#routes)) {
163
+ if (__requireBoolean(__normalize(route.path) === path)) {
164
+ return route;
165
+ }
166
+ if (__requireBoolean(__normalize(route.path.endsWith("/*")))) {
167
+ let prefix = __normalize(route.path.slice(0, __finite(-1)));
168
+ if (__requireBoolean(__requireBoolean(__normalize(path.startsWith(prefix))) && __requireBoolean(__normalize(prefix.length) > length))) {
169
+ best = route;
170
+ length = __normalize(prefix.length);
171
+ }
172
+ }
173
+ }
174
+ return best;
175
+ return null;
176
+ }
177
+ handle(task) {
178
+ const __contextScope = [];
179
+ try {
180
+ __requireArity(arguments.length, [0], "handle");
181
+ task = __boundary(task);
182
+ __normalize(__hostGlobal(["Object"]).freeze(task.request.headers));
183
+ __contextScope.push(__contextSet("server", __normalize(this.#serverContext)));
184
+ __contextScope.push(__contextSet("request", __normalize(__hostGlobal(["Object"]).freeze(__normalize(task.request)))));
185
+ __contextScope.push(__contextSet("response", new Response()));
186
+ let fresh = __normalize(__contextGet("request").headers.authorization) === null;
187
+ let claims = null;
188
+ try {
189
+ if (__requireBoolean(fresh)) {
190
+ claims = __normalize(this.#tokens.create());
191
+ } else {
192
+ claims = __normalize(this.#tokens.read(__normalize(__contextGet("request").headers.authorization)));
193
+ }
194
+ } catch (error) {
195
+ return failure(401, "Unauthorized");
196
+ }
197
+ let route = this.#match(__normalize(__contextGet("request").path));
198
+ if (__requireBoolean(route === null)) {
199
+ return failure(404, "RouteNotFound");
200
+ }
201
+ let input = null;
202
+ try {
203
+ input = __normalize(__hostGlobal(["JSON"]).parse(__normalize(task.body)));
204
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(input))) || __requireBoolean(__isArray(input)))) {
205
+ return failure(400, "InputMustBeObject");
206
+ }
207
+ } catch (error) {
208
+ return failure(400, "InvalidJson");
209
+ }
210
+ __contextScope.push(__contextSet("token", new Token(claims)));
211
+ __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
212
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
213
+ const __contextScope = [];
214
+ try {
215
+ __contextScope.push(__contextSet("server", __capturedContext0));
216
+ __contextScope.push(__contextSet("request", __capturedContext1));
217
+ __contextScope.push(__contextSet("response", __capturedContext2));
218
+ __contextScope.push(__contextSet("token", __capturedContext3));
219
+ __contextScope.push(__contextSet("log", __capturedContext4));
220
+ __contextScope.push(__contextSet("db", __capturedContext5));
221
+ ignored = __boundary(ignored);
222
+ if (__requireBoolean(fresh)) {
223
+ return this.#event("register", input);
224
+ }
225
+ return this.#validate();
226
+ return null;
227
+ } finally {
228
+ __contextRestore(__contextScope);
229
+ }
230
+ })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (validatedAt) => {
231
+ const __contextScope = [];
232
+ try {
233
+ __contextScope.push(__contextSet("server", __capturedContext0));
234
+ __contextScope.push(__contextSet("request", __capturedContext1));
235
+ __contextScope.push(__contextSet("response", __capturedContext2));
236
+ __contextScope.push(__contextSet("token", __capturedContext3));
237
+ __contextScope.push(__contextSet("log", __capturedContext4));
238
+ __contextScope.push(__contextSet("db", __capturedContext5));
239
+ validatedAt = __boundary(validatedAt);
240
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(fresh)) && __requireBoolean(__isNumber(validatedAt)))) {
241
+ stampValidation(claims, validatedAt);
242
+ }
243
+ if (__requireBoolean(__requireBoolean(__normalize(route.auth) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasAuth(__normalize(route.auth))))))) {
244
+ throw { status: 401, error: "Unauthorized" };
245
+ }
246
+ if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
247
+ return null;
248
+ }
249
+ let handler = __normalize(route.handler);
250
+ let middleware = __normalize(route.middleware);
251
+ if (__requireBoolean(middleware !== null)) {
252
+ return __call(middleware, handler, __normalize(__contextGet("request").path), input);
253
+ }
254
+ return __call(handler, input);
255
+ return null;
256
+ } finally {
257
+ __contextRestore(__contextScope);
258
+ }
259
+ })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (output) => {
260
+ const __contextScope = [];
261
+ try {
262
+ __contextScope.push(__contextSet("server", __capturedContext0));
263
+ __contextScope.push(__contextSet("request", __capturedContext1));
264
+ __contextScope.push(__contextSet("response", __capturedContext2));
265
+ __contextScope.push(__contextSet("token", __capturedContext3));
266
+ __contextScope.push(__contextSet("log", __capturedContext4));
267
+ __contextScope.push(__contextSet("db", __capturedContext5));
268
+ output = __boundary(output);
269
+ if (__requireBoolean(__normalize(task.authorize) === true)) {
270
+ closeScope(__contextGet("db"), true);
271
+ let authorizedClaims = __normalize(__contextGet("token").snapshot());
272
+ authorizedClaims.validatedAt = __normalize(claims.validatedAt);
273
+ let encoded = __normalize(this.#tokens.sign(authorizedClaims));
274
+ if (__requireBoolean(__normalize(task.pollResult) === null)) {
275
+ return { status: 200, authorization: encoded };
276
+ }
277
+ if (__requireBoolean(task.pollResult.resyncRequired)) {
278
+ __normalize(__contextGet("response").status(409));
279
+ }
280
+ let pollBody = __normalize(__hostGlobal(["JSON"]).stringify(__normalize(task.pollResult)));
281
+ let pollResponse = __normalize(__contextGet("response").result(pollBody));
282
+ pollResponse.headers["x-lango-token"] = encoded;
283
+ if (__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.requestEvent)) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
284
+ return this.#audit(__normalize(__contextGet("request").id), pollResponse, __normalize(task.body), pollBody, authorizedClaims);
285
+ }
286
+ return pollResponse;
287
+ }
288
+ let body = __normalize(__hostGlobal(["JSON"]).stringify(output));
289
+ if (__requireBoolean(!__requireBoolean(__isString(body)))) {
290
+ throw "Handler result is not JSON serializable";
291
+ }
292
+ closeScope(__contextGet("db"), true);
293
+ let result = __normalize(__contextGet("response").result(body));
294
+ let updated = __normalize(__contextGet("token").snapshot());
295
+ updated.validatedAt = __normalize(claims.validatedAt);
296
+ result.headers["x-lango-token"] = __normalize(this.#tokens.sign(updated));
297
+ if (__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.requestEvent)) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
298
+ return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
299
+ }
300
+ return result;
301
+ return null;
302
+ } finally {
303
+ __contextRestore(__contextScope);
304
+ }
305
+ })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3) => (error) => {
306
+ const __contextScope = [];
307
+ try {
308
+ __contextScope.push(__contextSet("server", __capturedContext0));
309
+ __contextScope.push(__contextSet("request", __capturedContext1));
310
+ __contextScope.push(__contextSet("log", __capturedContext2));
311
+ __contextScope.push(__contextSet("db", __capturedContext3));
312
+ error = __boundary(error);
313
+ closeScope(__contextGet("db"), false);
314
+ if (__requireBoolean(__requireBoolean(error === "TokenExpired") || __requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401)))) {
315
+ return failure(401, "Unauthorized");
316
+ }
317
+ __normalize(__contextGet("log").err(`[${__normalize(__contextGet("request").id)}] Request failed`));
318
+ return failure(500, "InternalServerError");
319
+ return null;
320
+ } finally {
321
+ __contextRestore(__contextScope);
322
+ }
323
+ })(__contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db")), [0], "closure")).finally(((__capturedContext0) => () => {
324
+ const __contextScope = [];
325
+ try {
326
+ __contextScope.push(__contextSet("db", __capturedContext0));
327
+ closeScope(__contextGet("db"), false);
328
+ return null;
329
+ } finally {
330
+ __contextRestore(__contextScope);
331
+ }
332
+ })(__contextGet("db")));
333
+ return null;
334
+ } finally {
335
+ __contextRestore(__contextScope);
336
+ }
337
+ }
338
+ #event(name, input) {
339
+ const __contextScope = [];
340
+ try {
341
+ __requireArity(arguments.length, [0, 1], "event");
342
+ name = __boundary(name);
343
+ input = __boundary(input);
344
+ if (__requireBoolean(!__requireBoolean(__includes(name, __normalize(this.#events))))) {
345
+ return null;
346
+ }
347
+ let handler = __normalize(this.#events[name]);
348
+ __normalize(threads.parentPort.postMessage({ kind: "event", id: __normalize(__contextGet("request").id) }));
349
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
350
+ const __contextScope = [];
351
+ try {
352
+ __contextScope.push(__contextSet("server", __capturedContext0));
353
+ __contextScope.push(__contextSet("request", __capturedContext1));
354
+ __contextScope.push(__contextSet("response", __capturedContext2));
355
+ __contextScope.push(__contextSet("token", __capturedContext3));
356
+ __contextScope.push(__contextSet("log", __capturedContext4));
357
+ __contextScope.push(__contextSet("db", __capturedContext5));
358
+ ignored = __boundary(ignored);
359
+ return __call(handler, input);
360
+ return null;
361
+ } finally {
362
+ __contextRestore(__contextScope);
363
+ }
364
+ })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).finally(((__capturedContext0, __capturedContext1) => () => {
365
+ const __contextScope = [];
366
+ try {
367
+ __contextScope.push(__contextSet("server", __capturedContext0));
368
+ __contextScope.push(__contextSet("request", __capturedContext1));
369
+ __normalize(threads.parentPort.postMessage({ kind: "handler", id: __normalize(__contextGet("request").id) }));
370
+ return null;
371
+ } finally {
372
+ __contextRestore(__contextScope);
373
+ }
374
+ })(__contextGet("server"), __contextGet("request")));
375
+ return null;
376
+ } finally {
377
+ __contextRestore(__contextScope);
378
+ }
379
+ }
380
+ #validate() {
381
+ const __contextScope = [];
382
+ try {
383
+ let claims = __normalize(__contextGet("token").snapshot());
384
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__includes("validate", __normalize(this.#events)))) || __requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000))) {
385
+ return null;
386
+ }
387
+ let original = __normalize(__hostGlobal(["JSON"]).stringify(claims));
388
+ __contextScope.push(__contextSet("token", new Token(claims, true)));
389
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
390
+ const __contextScope = [];
391
+ try {
392
+ __contextScope.push(__contextSet("token", __capturedContext0));
393
+ __contextScope.push(__contextSet("response", __capturedContext1));
394
+ __contextScope.push(__contextSet("server", __capturedContext2));
395
+ __contextScope.push(__contextSet("request", __capturedContext3));
396
+ __contextScope.push(__contextSet("log", __capturedContext4));
397
+ __contextScope.push(__contextSet("db", __capturedContext5));
398
+ ignored = __boundary(ignored);
399
+ return this.#event("validate", null);
400
+ return null;
401
+ } finally {
402
+ __contextRestore(__contextScope);
403
+ }
404
+ })(__contextGet("token"), __contextGet("response"), __contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0) => (valid) => {
405
+ const __contextScope = [];
406
+ try {
407
+ __contextScope.push(__contextSet("token", __capturedContext0));
408
+ valid = __boundary(valid);
409
+ if (__requireBoolean(!__requireBoolean(__isBool(valid)))) {
410
+ throw "Validate must return boolean";
411
+ }
412
+ if (__requireBoolean(!__requireBoolean(valid))) {
413
+ throw { status: 401, error: "Unauthorized" };
414
+ }
415
+ if (__requireBoolean(__normalize(__hostGlobal(["JSON"]).stringify(__normalize(__contextGet("token").snapshot()))) !== original)) {
416
+ throw "Validate cannot change the token";
417
+ }
418
+ claims.validatedAt = __normalize(__hostGlobal(["Date"]).now());
419
+ return __normalize(claims.validatedAt);
420
+ return null;
421
+ } finally {
422
+ __contextRestore(__contextScope);
423
+ }
424
+ })(__contextGet("token")), [0], "closure"));
425
+ return null;
426
+ } finally {
427
+ __contextRestore(__contextScope);
428
+ }
429
+ }
430
+ #audit(id, result, input, output, claims) {
431
+ const __contextScope = [];
432
+ try {
433
+ __requireArity(arguments.length, [0, 1, 2, 3, 4], "audit");
434
+ id = __boundary(id);
435
+ result = __boundary(result);
436
+ input = __boundary(input);
437
+ output = __boundary(output);
438
+ claims = __boundary(claims);
439
+ __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
440
+ __contextScope.push(__contextSet("token", new Token(claims, true)));
441
+ __contextScope.push(__contextSet("response", __normalize(__hostGlobal(["Object"]).freeze({ }))));
442
+ let metadata = { input: input, output: output, status: __normalize(result.status) };
443
+ __normalize(threads.parentPort.postMessage({ kind: "prepared", id: id, result: result }));
444
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
445
+ const __contextScope = [];
446
+ try {
447
+ __contextScope.push(__contextSet("token", __capturedContext0));
448
+ __contextScope.push(__contextSet("server", __capturedContext1));
449
+ __contextScope.push(__contextSet("request", __capturedContext2));
450
+ __contextScope.push(__contextSet("response", __capturedContext3));
451
+ __contextScope.push(__contextSet("log", __capturedContext4));
452
+ __contextScope.push(__contextSet("db", __capturedContext5));
453
+ ignored = __boundary(ignored);
454
+ return this.#event("request", __normalize(__hostGlobal(["Object"]).freeze(metadata)));
455
+ return null;
456
+ } finally {
457
+ __contextRestore(__contextScope);
458
+ }
459
+ })(__contextGet("token"), __contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0) => (ignored) => {
460
+ const __contextScope = [];
461
+ try {
462
+ __contextScope.push(__contextSet("db", __capturedContext0));
463
+ ignored = __boundary(ignored);
464
+ closeScope(__contextGet("db"), true);
465
+ return null;
466
+ return null;
467
+ } finally {
468
+ __contextRestore(__contextScope);
469
+ }
470
+ })(__contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1) => (error) => {
471
+ const __contextScope = [];
472
+ try {
473
+ __contextScope.push(__contextSet("log", __capturedContext0));
474
+ __contextScope.push(__contextSet("db", __capturedContext1));
475
+ error = __boundary(error);
476
+ closeScope(__contextGet("db"), false);
477
+ __normalize(__contextGet("log").err("Request event failed"));
478
+ return null;
479
+ return null;
480
+ } finally {
481
+ __contextRestore(__contextScope);
482
+ }
483
+ })(__contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity((ignored) => {
484
+ ignored = __boundary(ignored);
485
+ return result;
486
+ return null;
487
+ }, [0], "closure")).finally(((__capturedContext0) => () => {
488
+ const __contextScope = [];
489
+ try {
490
+ __contextScope.push(__contextSet("db", __capturedContext0));
491
+ closeScope(__contextGet("db"), false);
492
+ return null;
493
+ } finally {
494
+ __contextRestore(__contextScope);
495
+ }
496
+ })(__contextGet("db")));
497
+ return null;
498
+ } finally {
499
+ __contextRestore(__contextScope);
500
+ }
501
+ }
502
+ }
503
+ function exported(mod, name) {
504
+ __requireArity(arguments.length, [0, 1], "exported");
505
+ mod = __boundary(mod);
506
+ name = __boundary(name);
507
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(mod, name)))) || __requireBoolean(!__requireBoolean(__isKindof(__normalize(mod[name]), Function))))) {
508
+ throw `Handler is not exported: ${name}`;
509
+ }
510
+ return __normalize(mod[name]);
511
+ return null;
512
+ }
513
+
514
+ function failure(status, code) {
515
+ __requireArity(arguments.length, [0, 1], "failure");
516
+ status = __boundary(status);
517
+ code = __boundary(code);
518
+ let headers = { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" };
519
+ if (__requireBoolean(status === 401)) {
520
+ headers["www-authenticate"] = "Bearer";
521
+ }
522
+ return { status: status, headers: headers, body: __normalize(__hostGlobal(["JSON"]).stringify({ error: code })) };
523
+ return null;
524
+ }
525
+
526
+ function stampValidation(claims, validatedAt) {
527
+ __requireArity(arguments.length, [0, 1], "stampValidation");
528
+ claims = __boundary(claims);
529
+ validatedAt = __boundary(validatedAt);
530
+ claims.validatedAt = validatedAt;
531
+ return null;
532
+ return null;
533
+ }
534
+
535
+ function closeScope(db, strict) {
536
+ __requireArity(arguments.length, [0, 1], "closeScope");
537
+ db = __boundary(db);
538
+ strict = __boundary(strict);
539
+ let dirty;
540
+ if (__requireBoolean(db !== null)) {
541
+ dirty = __normalize(db.finish());
542
+ if (__requireBoolean(__requireBoolean(dirty) && __requireBoolean(strict))) {
543
+ throw "UnclosedTransaction";
544
+ }
545
+ }
546
+ return null;
547
+ return null;
548
+ }
549
+ //# sourceMappingURL=runtime.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n\nRuntime(definition)\n @serverContext = new ServerContext()\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @middlewares[name] = handler\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n @routes.add(route)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n length = -1\n for @routes as route\n if route.path == path\n return route\n if route.path.endsWith(\"/*\")\n prefix = route.path.slice(0, -1)\n if path.startsWith(prefix) and prefix.length > length\n best = route\n length = prefix.length\n return best\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n return failure(401, \"Unauthorized\")\n route = match(request.path)\n if route == null\n return failure(404, \"RouteNotFound\")\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n context token = new Token(claims)\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = token.snapshot()\n authorizedClaims.validatedAt = claims.validatedAt\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n closeScope(db, false)\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n return failure(401, \"Unauthorized\")\n log.err(\"[${request.id}] Request failed\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if !(\"validate\" in @events) or Date/now() - claims.validatedAt < 1000\n return null\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n closeScope(db, false)\n log.err(\"Request event failed\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA;;;;;;;;;;;AA0PA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}