@lango-project/lango-server 0.0.0-stage → 0.1.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.
Files changed (105) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +431 -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 +69 -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 +44 -0
  41. package/dist/cli/endpoint.mjs.map +1 -0
  42. package/dist/cli/options.mjs +165 -0
  43. package/dist/cli/options.mjs.map +1 -0
  44. package/dist/cli/postgres_adapter.mjs +166 -0
  45. package/dist/cli/postgres_adapter.mjs.map +1 -0
  46. package/dist/cli/routes.mjs +233 -0
  47. package/dist/cli/routes.mjs.map +1 -0
  48. package/dist/cli/server.mjs +572 -0
  49. package/dist/cli/server.mjs.map +1 -0
  50. package/dist/cli/sqlite_adapter.mjs +163 -0
  51. package/dist/cli/sqlite_adapter.mjs.map +1 -0
  52. package/dist/database.mjs +101 -0
  53. package/dist/database.mjs.map +1 -0
  54. package/dist/database_options.mjs +83 -0
  55. package/dist/database_options.mjs.map +1 -0
  56. package/dist/database_scope.mjs +82 -0
  57. package/dist/database_scope.mjs.map +1 -0
  58. package/dist/endpoint.mjs +44 -0
  59. package/dist/endpoint.mjs.map +1 -0
  60. package/dist/group.mjs +75 -0
  61. package/dist/group.mjs.map +1 -0
  62. package/dist/library.mjs +6 -0
  63. package/dist/library.mjs.map +1 -0
  64. package/dist/options.mjs +165 -0
  65. package/dist/options.mjs.map +1 -0
  66. package/dist/postgres_adapter.mjs +166 -0
  67. package/dist/postgres_adapter.mjs.map +1 -0
  68. package/dist/postgres_worker.mjs +119 -0
  69. package/dist/postgres_worker.mjs.map +1 -0
  70. package/dist/response.mjs +62 -0
  71. package/dist/response.mjs.map +1 -0
  72. package/dist/routes.mjs +233 -0
  73. package/dist/routes.mjs.map +1 -0
  74. package/dist/runtime.mjs +475 -0
  75. package/dist/runtime.mjs.map +1 -0
  76. package/dist/server.mjs +568 -0
  77. package/dist/server.mjs.map +1 -0
  78. package/dist/sqlite_adapter.mjs +163 -0
  79. package/dist/sqlite_adapter.mjs.map +1 -0
  80. package/dist/token.mjs +106 -0
  81. package/dist/token.mjs.map +1 -0
  82. package/dist/tokens.mjs +76 -0
  83. package/dist/tokens.mjs.map +1 -0
  84. package/dist/worker.mjs +57 -0
  85. package/dist/worker.mjs.map +1 -0
  86. package/package.json +39 -4
  87. package/src/body_reader.lango +113 -0
  88. package/src/builder.lango +53 -0
  89. package/src/database.lango +66 -0
  90. package/src/database_options.lango +57 -0
  91. package/src/database_scope.lango +59 -0
  92. package/src/endpoint.lango +23 -0
  93. package/src/group.lango +47 -0
  94. package/src/library.lango +10 -0
  95. package/src/options.lango +128 -0
  96. package/src/postgres_adapter.lango +138 -0
  97. package/src/postgres_worker.lango +114 -0
  98. package/src/response.lango +42 -0
  99. package/src/routes.lango +160 -0
  100. package/src/runtime.lango +320 -0
  101. package/src/server.lango +432 -0
  102. package/src/sqlite_adapter.lango +127 -0
  103. package/src/token.lango +70 -0
  104. package/src/tokens.lango +70 -0
  105. package/src/worker.lango +43 -0
@@ -0,0 +1,160 @@
1
+ import "./options"
2
+ contains(items, value)
3
+ import js "node:fs" as fs
4
+ import js "node:path" as path
5
+ import js "node:module" as modules
6
+ import "./options"
7
+ attributes(tag, allowed)
8
+ import "./endpoint"
9
+ class Endpoint
10
+
11
+ export class Routes(root)
12
+ methods
13
+ endpoint(spec)
14
+ include(spec, auth = null)
15
+ xml(file)
16
+ definitions()
17
+ events()
18
+ event(spec)
19
+
20
+ Routes(root)
21
+ @root = path/resolve(root)
22
+ @items = []
23
+ @events = {}
24
+
25
+ Routes:endpoint(spec)
26
+ item = new Endpoint(spec)
27
+ for @items as other
28
+ if other.path == item.path
29
+ throw "Duplicate endpoint: ${item.path}"
30
+ @items.add({
31
+ path: item.path
32
+ module: resolveModule(item.module, @root)
33
+ handler: item.handler
34
+ auth: item.auth
35
+ })
36
+ return @this
37
+
38
+ Routes:event(spec)
39
+ if !contains(["register", "validate", "request"], spec.name)
40
+ throw "Unknown event: ${spec.name}"
41
+ if spec.name in @events
42
+ throw "Duplicate event: ${spec.name}"
43
+ if !is_string(spec.handler) or spec.handler == ""
44
+ throw "Event handler is required"
45
+ @events[spec.name] = {
46
+ module: resolveModule(spec.module, @root)
47
+ handler: spec.handler
48
+ }
49
+ return @this
50
+
51
+ Routes:include(spec, auth = null)
52
+ includeAt(spec, @root, "", [], auth)
53
+ return @this
54
+
55
+ Routes:xml(file)
56
+ readXml(path/resolve(file), "", @root, [], true)
57
+ return @this
58
+
59
+ Routes:definitions()
60
+ return from_json(to_json(@items))
61
+
62
+ Routes:events()
63
+ return from_json(to_json(@events))
64
+
65
+ resolveModule(name, directory)
66
+ if !is_string(name) or name == "" or name.startsWith("node:")
67
+ throw "Application module is required"
68
+ resolver = modules/createRequire(path/join(directory, "package.json"))
69
+ resolved = resolver.resolve(name)
70
+ if !path/isAbsolute(resolved)
71
+ throw "Application module must resolve to a file: ${name}"
72
+ return resolved
73
+
74
+ joinPath(prefix, suffix)
75
+ if !is_string(suffix) or !suffix.startsWith("/")
76
+ throw "Route path must begin with /"
77
+ if prefix == "" or prefix == "/"
78
+ return suffix
79
+ if suffix == "/"
80
+ return "${prefix}/"
81
+ return "${prefix}${suffix}"
82
+
83
+ Routes:includeAt(spec, directory, prefix, stack, inheritedAuth = null)
84
+ if !is_string(spec.module) or spec.module == "" or spec.module.startsWith(".") or spec.module.startsWith("/") or spec.module.startsWith("node:")
85
+ throw "Include requires an npm package name"
86
+ mount = spec.path
87
+ if mount == null
88
+ mount = "/"
89
+ if !is_string(mount)
90
+ throw "Include path must be a string"
91
+ if mount.includes("*") or mount.includes("//") or mount.includes("?") or mount.includes("#") or mount.includes("\\")
92
+ throw "Invalid include prefix"
93
+ if mount.endsWith("/") and mount != "/"
94
+ mount = mount.slice(0, -1)
95
+ combined = joinPath(prefix, mount)
96
+ if combined == "/"
97
+ combined = ""
98
+ file = resolveModule("${spec.module}/routes.xml", directory)
99
+ readXml(file, combined, path/dirname(file), stack, false, inheritedAuth)
100
+ return null
101
+
102
+ Routes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null)
103
+ real = fs/realpathSync(file)
104
+ if stack.includes(real)
105
+ throw "Route include cycle: ${real}"
106
+ root = xml2obj(fs/readFileSync(real, "utf8"))
107
+ if root.tag() != "routes"
108
+ throw "Expected routes root: ${real}"
109
+ attributes(root, [])
110
+ nextStack = stack.slice()
111
+ nextStack.add(real)
112
+ collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents)
113
+ return null
114
+
115
+ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents)
116
+ if parent.innerText().trim() != ""
117
+ throw "Route XML cannot contain text"
118
+ for parent.children() as tag
119
+ spec = tag.attributes()
120
+ mod = spec.module
121
+ auth = spec.auth
122
+ if mod == null
123
+ mod = inheritedModule
124
+ if auth == null
125
+ auth = inheritedAuth
126
+ switch tag.tag()
127
+ case "endpoint"
128
+ attributes(tag, ["path", "module", "handler", "auth"])
129
+ leaf(tag)
130
+ endpoint({
131
+ path: joinPath(prefix, spec.path)
132
+ module: resolveModule(mod, directory)
133
+ handler: spec.handler
134
+ auth: auth
135
+ })
136
+ case "group"
137
+ attributes(tag, ["path", "module", "auth"])
138
+ collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false)
139
+ case "include"
140
+ attributes(tag, ["module", "path"])
141
+ leaf(tag)
142
+ includeAt(spec, directory, prefix, stack, auth)
143
+ case "event"
144
+ attributes(tag, ["name", "module", "handler"])
145
+ leaf(tag)
146
+ if !allowEvents
147
+ throw "Events are only allowed in the application's root routes.xml"
148
+ event({
149
+ name: spec.name
150
+ module: resolveModule(spec.module, directory)
151
+ handler: spec.handler
152
+ })
153
+ else
154
+ throw "Unknown routes element: ${tag.tag()}"
155
+ return null
156
+
157
+ leaf(tag)
158
+ if tag.children().length != 0 or tag.innerText().trim() != ""
159
+ throw "Expected an empty ${tag.tag()} element"
160
+ return null
@@ -0,0 +1,320 @@
1
+ import "./database"
2
+ class Database
3
+ import js global Promise
4
+ import js global JSON
5
+ import js global Object
6
+ import js global Date
7
+ import js "node:worker_threads" as threads
8
+ import "./token"
9
+ class Token
10
+ import "./tokens"
11
+ class Tokens
12
+ import "./response"
13
+ class Response
14
+
15
+ export class Runtime(definition)
16
+ methods
17
+ preload()
18
+ handle(task)
19
+ close()
20
+
21
+ Runtime(definition)
22
+ @definition = definition
23
+ @routes = []
24
+ @events = {}
25
+ @tokens = new Tokens(definition.settings)
26
+ @modules = {}
27
+ @database = new Database(definition.settings.database, definition.settings.root)
28
+
29
+ Runtime:preload()
30
+ definitions = @definition.routes
31
+ pending = @database.open()
32
+ for definitions as route
33
+ pending = prepareRoute(pending, route)
34
+ events = @definition.events
35
+ for events as name: target
36
+ pending = prepareEvent(pending, name, target)
37
+ return chain pending
38
+ catch(error)
39
+ close()
40
+ throw error
41
+
42
+ Runtime:close()
43
+ @database.close()
44
+ return null
45
+
46
+ Runtime:prepareRoute(pending, route)
47
+ return chain pending
48
+ then(ignored)
49
+ capture route
50
+ return target(route)
51
+ then(handler)
52
+ capture route
53
+ @routes.add({
54
+ path: route.path
55
+ auth: route.auth
56
+ handler: handler
57
+ })
58
+ return null
59
+
60
+ Runtime:prepareEvent(pending, name, spec)
61
+ return chain pending
62
+ then(ignored)
63
+ capture spec
64
+ return target(spec)
65
+ then(handler)
66
+ capture name
67
+ @events[name] = handler
68
+ return null
69
+
70
+ Runtime:target(spec)
71
+ file = spec.module
72
+ if file in @modules
73
+ return Promise/resolve(exported(@modules[file], spec.handler))
74
+ return chain import_module(file)
75
+ then(mod)
76
+ capture file
77
+ capture spec
78
+ @modules[file] = mod
79
+ return exported(mod, spec.handler)
80
+
81
+ exported(mod, name)
82
+ if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)
83
+ throw "Handler is not exported: ${name}"
84
+ return mod[name]
85
+
86
+ Runtime:match(path)
87
+ best = null
88
+ length = -1
89
+ for @routes as route
90
+ if route.path == path
91
+ return route
92
+ if route.path.endsWith("/*")
93
+ prefix = route.path.slice(0, -1)
94
+ if path.startsWith(prefix) and prefix.length > length
95
+ best = route
96
+ length = prefix.length
97
+ return best
98
+
99
+ Runtime:handle(task)
100
+ Object/freeze(task.request.headers)
101
+ context request = Object/freeze(task.request)
102
+ context response = new Response()
103
+ context log
104
+ fresh = request.headers.authorization == null
105
+ claims = null
106
+ try
107
+ if fresh
108
+ claims = @tokens.create()
109
+ else
110
+ claims = @tokens.read(request.headers.authorization)
111
+ catch error
112
+ return failure(401, "Unauthorized")
113
+ route = match(request.path)
114
+ if route == null
115
+ return failure(404, "RouteNotFound")
116
+ input = null
117
+ try
118
+ input = JSON/parse(task.body)
119
+ if !is_object(input) or is_array(input)
120
+ return failure(400, "InputMustBeObject")
121
+ catch error
122
+ return failure(400, "InvalidJson")
123
+ context token = new Token(claims)
124
+ context db = @database.scope()
125
+ return chain Promise/resolve(null)
126
+ then(ignored)
127
+ capture request
128
+ capture response
129
+ capture token
130
+ capture log
131
+ capture db
132
+ capture fresh
133
+ capture input
134
+ if fresh
135
+ return event("register", input)
136
+ return validate()
137
+ then(validatedAt)
138
+ capture request
139
+ capture response
140
+ capture token
141
+ capture log
142
+ capture db
143
+ capture route
144
+ capture input
145
+ capture claims
146
+ capture fresh
147
+ if !fresh and is_number(validatedAt)
148
+ stampValidation(claims, validatedAt)
149
+ if route.auth != "anonymous" and !token.hasAuth(route.auth)
150
+ throw {
151
+ status: 401
152
+ error: "Unauthorized"
153
+ }
154
+ handler = route.handler
155
+ return handler(input)
156
+ then(output)
157
+ capture request
158
+ capture response
159
+ capture token
160
+ capture log
161
+ capture db
162
+ capture task
163
+ capture claims
164
+ body = JSON/stringify(output)
165
+ if !is_string(body)
166
+ throw "Handler result is not JSON serializable"
167
+ closeScope(db, true)
168
+ result = response.result(body)
169
+ updated = token.snapshot()
170
+ updated.validatedAt = claims.validatedAt
171
+ result.headers["x-lango-token"] = @tokens.sign(updated)
172
+ if @definition.settings.requestEvent and "request" in @events
173
+ return audit(request.id, result, task.body, body, updated)
174
+ return result
175
+ catch(error)
176
+ capture request
177
+ capture log
178
+ capture db
179
+ closeScope(db, false)
180
+ if error == "TokenExpired" or (is_object(error) and error.status == 401)
181
+ return failure(401, "Unauthorized")
182
+ log.err("[${request.id}] Request failed")
183
+ return failure(500, "InternalServerError")
184
+ finally
185
+ capture db
186
+ closeScope(db, false)
187
+
188
+ Runtime:event(name, input)
189
+ if !(name in @events)
190
+ return null
191
+ context request
192
+ context response
193
+ context token
194
+ context log
195
+ context db
196
+ handler = @events[name]
197
+ threads/parentPort/postMessage({
198
+ kind: "event"
199
+ id: request.id
200
+ })
201
+ return chain Promise/resolve(null)
202
+ then(ignored)
203
+ capture request
204
+ capture response
205
+ capture token
206
+ capture log
207
+ capture db
208
+ capture handler
209
+ capture input
210
+ return handler(input)
211
+ finally
212
+ capture request
213
+ capture threads
214
+ threads/parentPort/postMessage({
215
+ kind: "handler"
216
+ id: request.id
217
+ })
218
+
219
+ Runtime:validate()
220
+ context db
221
+ context token
222
+ context response
223
+ context request
224
+ context log
225
+ claims = token.snapshot()
226
+ if !("validate" in @events) or Date/now() - claims.validatedAt < 1000
227
+ return null
228
+ original = JSON/stringify(claims)
229
+ context token = new Token(claims, true)
230
+ return chain Promise/resolve(null)
231
+ then(ignored)
232
+ capture token
233
+ capture response
234
+ capture request
235
+ capture log
236
+ capture db
237
+ return event("validate", null)
238
+ then(valid)
239
+ capture token
240
+ capture original
241
+ capture claims
242
+ if !is_bool(valid)
243
+ throw "Validate must return boolean"
244
+ if !valid
245
+ throw {
246
+ status: 401
247
+ error: "Unauthorized"
248
+ }
249
+ if JSON/stringify(token.snapshot()) != original
250
+ throw "Validate cannot change the token"
251
+ claims.validatedAt = Date/now()
252
+ return claims.validatedAt
253
+
254
+ Runtime:audit(id, result, input, output, claims)
255
+ context db = @database.scope()
256
+ context request
257
+ context log
258
+ context token = new Token(claims, true)
259
+ context response = Object/freeze({})
260
+ metadata = {
261
+ input: input
262
+ output: output
263
+ status: result.status
264
+ }
265
+ threads/parentPort/postMessage({
266
+ kind: "prepared"
267
+ id: id
268
+ result: result
269
+ })
270
+ return chain Promise/resolve(null)
271
+ then(ignored)
272
+ capture token
273
+ capture request
274
+ capture response
275
+ capture log
276
+ capture db
277
+ capture metadata
278
+ return event("request", Object/freeze(metadata))
279
+ then(ignored)
280
+ capture db
281
+ closeScope(db, true)
282
+ return null
283
+ catch(error)
284
+ capture log
285
+ capture db
286
+ closeScope(db, false)
287
+ log.err("Request event failed")
288
+ return null
289
+ then(ignored)
290
+ capture result
291
+ return result
292
+ finally
293
+ capture db
294
+ closeScope(db, false)
295
+
296
+ failure(status, code)
297
+ headers = {
298
+ "content-type": "application/json; charset=utf-8"
299
+ "cache-control": "no-store"
300
+ }
301
+ if status == 401
302
+ headers["www-authenticate"] = "Bearer"
303
+ return {
304
+ status: status
305
+ headers: headers
306
+ body: JSON/stringify({
307
+ error: code
308
+ })
309
+ }
310
+
311
+ stampValidation(claims, validatedAt)
312
+ claims.validatedAt = validatedAt
313
+ return null
314
+
315
+ closeScope(db, strict)
316
+ if db != null
317
+ dirty = db.finish()
318
+ if dirty and strict
319
+ throw "UnclosedTransaction"
320
+ return null