@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 @@
1
+ {"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n if state.done\n return null\n state.done = true\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"[${record.id}] Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n if args.length != 1\n throw \"Usage: lango-server <application-directory>\"\n server = new Server(args[0])\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAoGA;;;;;;;;;;;;;;;;;AAgXA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,163 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import {
4
+ hostGlobal as __hostGlobal,
5
+ hostGlobalCall as __hostGlobalCall,
6
+ isNumber as __isNumber,
7
+ isString as __isString,
8
+ isBool as __isBool,
9
+ isObject as __isObject,
10
+ isArray as __isArray,
11
+ entries as __entries,
12
+ requireBoolean as __requireBoolean,
13
+ normalize as __normalize,
14
+ finite as __finite,
15
+ numericAdd as __numericAdd,
16
+ boundary as __boundary,
17
+ requireArity as __requireArity,
18
+ } from "./.lango/runtime.mjs";
19
+
20
+ export class SqliteAdapter {
21
+ parameterStyle;
22
+ #connection;
23
+ #depth;
24
+ #state;
25
+ constructor(mod, settings) {
26
+ __requireArity(arguments.length, [0, 1], "constructor");
27
+ mod = __boundary(mod);
28
+ settings = __boundary(settings);
29
+ if (__requireBoolean(__normalize(settings.file) !== ":memory:")) {
30
+ __normalize(fs.mkdirSync(__normalize(path.dirname(__normalize(settings.file))), { recursive: true }));
31
+ }
32
+ this.#connection = __normalize(__hostGlobal(["Reflect"]).construct(__normalize(mod.DatabaseSync), [__normalize(settings.file)]));
33
+ this.#depth = 0;
34
+ this.#state = null;
35
+ this.parameterStyle = "named";
36
+ try {
37
+ __normalize(this.#connection.exec(`PRAGMA busy_timeout=${__normalize(settings.busyTimeoutMs)}`));
38
+ __normalize(this.#connection.exec("PRAGMA foreign_keys=ON"));
39
+ let modeQuery = __normalize(this.#connection.prepare("PRAGMA journal_mode"));
40
+ let mode = __normalize(modeQuery.get());
41
+ if (__requireBoolean(__requireBoolean(__normalize(settings.file) !== ":memory:") && __requireBoolean(__normalize(mode.journal_mode) !== "wal"))) {
42
+ __normalize(this.#connection.exec("PRAGMA journal_mode=WAL"));
43
+ }
44
+ } catch (error) {
45
+ __normalize(this.#connection.close());
46
+ throw "SQLite initialization failed";
47
+ }
48
+ }
49
+ execute(sql, parameters) {
50
+ __requireArity(arguments.length, [0, 1], "execute");
51
+ sql = __boundary(sql);
52
+ parameters = __boundary(parameters);
53
+ let bound = { };
54
+ for (const [name, value] of __entries(parameters)) {
55
+ if (__requireBoolean(__isBool(value))) {
56
+ bound[name] = __hostGlobalCall(["Number"], value);
57
+ } else {
58
+ bound[name] = value;
59
+ }
60
+ }
61
+ let statement = __normalize(this.#connection.prepare(sql));
62
+ __normalize(statement.setReadBigInts(true));
63
+ let columns = __normalize(statement.columns());
64
+ if (__requireBoolean(__normalize(columns.length) > 0)) {
65
+ let records = __normalize(statement.all(bound));
66
+ for (const row of records) {
67
+ for (const [name, value] of __entries(row)) {
68
+ row[name] = normalizeInteger(value);
69
+ }
70
+ }
71
+ return { rows: records, changes: null, lastInsertRowid: null };
72
+ }
73
+ let result = __normalize(statement.run(bound));
74
+ let changes = null;
75
+ let generated = null;
76
+ let operation = __normalize(sql.trim());
77
+ operation = __normalize(operation.toLowerCase());
78
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(operation.startsWith("insert"))) || __requireBoolean(__normalize(operation.startsWith("update")))) || __requireBoolean(__normalize(operation.startsWith("delete")))) || __requireBoolean(__normalize(operation.startsWith("with"))))) {
79
+ changes = normalizeInteger(__normalize(result.changes));
80
+ }
81
+ if (__requireBoolean(__requireBoolean(__normalize(operation.startsWith("insert"))) && __requireBoolean(changes === 1))) {
82
+ generated = normalizeInteger(__normalize(result.lastInsertRowid));
83
+ }
84
+ return { rows: [], changes: changes, lastInsertRowid: generated };
85
+ return null;
86
+ }
87
+ begin() {
88
+ if (__requireBoolean(__requireBoolean(__normalize(this.#depth) === 0) && __requireBoolean(!__requireBoolean(__normalize(this.#connection.isTransaction))))) {
89
+ __normalize(this.#connection.exec("BEGIN"));
90
+ }
91
+ this.#depth = __numericAdd(__normalize(this.#depth), 1);
92
+ if (__requireBoolean(__normalize(this.#state) === null)) {
93
+ this.#state = "active";
94
+ }
95
+ return null;
96
+ return null;
97
+ }
98
+ commit() {
99
+ if (__requireBoolean(__normalize(this.#depth) === 0)) {
100
+ throw new (__hostGlobal(["Error"]))("NoActiveTransaction");
101
+ }
102
+ if (__requireBoolean(__normalize(this.#depth) > 1)) {
103
+ this.#depth = __finite(__normalize(this.#depth) - 1);
104
+ return null;
105
+ }
106
+ if (__requireBoolean(__normalize(this.#state) === "rollback_only")) {
107
+ this.rollback();
108
+ throw new (__hostGlobal(["Error"]))("TransactionRolledBack");
109
+ }
110
+ __normalize(this.#connection.exec("COMMIT"));
111
+ this.#depth = 0;
112
+ this.#state = null;
113
+ return null;
114
+ return null;
115
+ }
116
+ rollback() {
117
+ if (__requireBoolean(__normalize(this.#depth) > 1)) {
118
+ this.#depth = __finite(__normalize(this.#depth) - 1);
119
+ this.#state = "rollback_only";
120
+ return null;
121
+ }
122
+ if (__requireBoolean(__normalize(this.#connection.isTransaction))) {
123
+ __normalize(this.#connection.exec("ROLLBACK"));
124
+ }
125
+ this.#depth = 0;
126
+ this.#state = null;
127
+ return null;
128
+ return null;
129
+ }
130
+ transactionState() {
131
+ if (__requireBoolean(!__requireBoolean(__normalize(this.#connection.isTransaction)))) {
132
+ this.#depth = 0;
133
+ this.#state = null;
134
+ }
135
+ if (__requireBoolean(__requireBoolean(__normalize(this.#connection.isTransaction)) && __requireBoolean(__normalize(this.#state) === null))) {
136
+ return "active";
137
+ }
138
+ return __normalize(this.#state);
139
+ return null;
140
+ }
141
+ close() {
142
+ __loop1: while (__requireBoolean(this.transactionState() !== null)) {
143
+ this.rollback();
144
+ }
145
+ __normalize(this.#connection.close());
146
+ return null;
147
+ return null;
148
+ }
149
+ }
150
+ function normalizeInteger(value) {
151
+ __requireArity(arguments.length, [0], "normalizeInteger");
152
+ value = __boundary(value);
153
+ if (__requireBoolean(__normalize(__hostGlobal(["Object"]).prototype.toString.call(value)) !== "[object BigInt]")) {
154
+ return value;
155
+ }
156
+ let number = __hostGlobalCall(["Number"], value);
157
+ if (__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(number)))) {
158
+ return number;
159
+ }
160
+ return `${value}`;
161
+ return null;
162
+ }
163
+ //# sourceMappingURL=sqlite_adapter.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite_adapter.mjs","sources":["sqlite_adapter.lango"],"sourcesContent":["import js global Error\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Reflect\nimport js global Object\nimport js global Number\n\nexport class SqliteAdapter(mod, settings)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n begin()\n commit()\n rollback()\n transactionState()\n close()\n\nSqliteAdapter(mod, settings)\n if settings.file != \":memory:\"\n fs/mkdirSync(path/dirname(settings.file), {\n recursive: true\n })\n @connection = Reflect/construct(mod.DatabaseSync, [settings.file])\n @depth = 0\n @state = null\n @parameterStyle = \"named\"\n try\n @connection.exec(\"PRAGMA busy_timeout=${settings.busyTimeoutMs}\")\n @connection.exec(\"PRAGMA foreign_keys=ON\")\n modeQuery = @connection.prepare(\"PRAGMA journal_mode\")\n mode = modeQuery.get()\n if settings.file != \":memory:\" and mode.journal_mode != \"wal\"\n @connection.exec(\"PRAGMA journal_mode=WAL\")\n catch error\n @connection.close()\n throw \"SQLite initialization failed\"\n\nSqliteAdapter:execute(sql, parameters)\n bound = {}\n for parameters as name: value\n if is_bool(value)\n bound[name] = Number(value)\n else\n bound[name] = value\n statement = @connection.prepare(sql)\n statement.setReadBigInts(true)\n columns = statement.columns()\n if columns.length > 0\n records = statement.all(bound)\n for records as row\n for row as name: value\n row[name] = normalizeInteger(value)\n return {\n rows: records\n changes: null\n lastInsertRowid: null\n }\n result = statement.run(bound)\n changes = null\n generated = null\n operation = sql.trim()\n operation = operation.toLowerCase()\n if operation.startsWith(\"insert\") or operation.startsWith(\"update\") or operation.startsWith(\"delete\") or operation.startsWith(\"with\")\n changes = normalizeInteger(result.changes)\n if operation.startsWith(\"insert\") and changes == 1\n generated = normalizeInteger(result.lastInsertRowid)\n return {\n rows: []\n changes: changes\n lastInsertRowid: generated\n }\n\nSqliteAdapter:begin()\n if @depth == 0 and !@connection.isTransaction\n @connection.exec(\"BEGIN\")\n @depth = @depth + 1\n if @state == null\n @state = \"active\"\n return null\n\nSqliteAdapter:commit()\n if @depth == 0\n throw new Error(\"NoActiveTransaction\")\n if @depth > 1\n @depth = @depth - 1\n return null\n if @state == \"rollback_only\"\n rollback()\n throw new Error(\"TransactionRolledBack\")\n @connection.exec(\"COMMIT\")\n @depth = 0\n @state = null\n return null\n\nSqliteAdapter:rollback()\n if @depth > 1\n @depth = @depth - 1\n @state = \"rollback_only\"\n return null\n if @connection.isTransaction\n @connection.exec(\"ROLLBACK\")\n @depth = 0\n @state = null\n return null\n\nSqliteAdapter:transactionState()\n if !@connection.isTransaction\n @depth = 0\n @state = null\n if @connection.isTransaction and @state == null\n return \"active\"\n return @state\n\nSqliteAdapter:close()\n loop while transactionState() != null\n rollback()\n @connection.close()\n return null\n\nnormalizeInteger(value)\n if Object/prototype/toString/call(value) != \"[object BigInt]\"\n return value\n number = Number(value)\n if Number/isSafeInteger(number)\n return number\n return \"${value}\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA;;;;;;;;;;;;;;"}
@@ -0,0 +1,125 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as files from "serve-static";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ isNumber as __isNumber,
7
+ isString as __isString,
8
+ isBool as __isBool,
9
+ isObject as __isObject,
10
+ isArray as __isArray,
11
+ entries as __entries,
12
+ requireBoolean as __requireBoolean,
13
+ normalize as __normalize,
14
+ finite as __finite,
15
+ call as __call,
16
+ boundary as __boundary,
17
+ requireArity as __requireArity,
18
+ withArity as __withArity,
19
+ } from "./.lango/runtime.mjs";
20
+
21
+ export class StaticFiles {
22
+ #settings;
23
+ #serve;
24
+ constructor(settings) {
25
+ __requireArity(arguments.length, [0], "constructor");
26
+ settings = __boundary(settings);
27
+ this.#settings = settings;
28
+ if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
29
+ throw "Static directory must be a directory";
30
+ }
31
+ this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
32
+ }
33
+ receive(req, res, failed) {
34
+ __requireArity(arguments.length, [0, 1, 2], "receive");
35
+ req = __boundary(req);
36
+ res = __boundary(res);
37
+ failed = __boundary(failed);
38
+ let mount = __normalize(this.#settings.path);
39
+ let url = __normalize(req.url);
40
+ let pathname = __normalize(__normalize(url.split("?"))[0]);
41
+ if (__requireBoolean(__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(pathname !== mount)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith(`${mount}/`)))))) {
42
+ __call(failed, 404, "NotFound");
43
+ return null;
44
+ }
45
+ if (__requireBoolean(mount !== "/")) {
46
+ req.url = __normalize(url.slice(__normalize(mount.length)));
47
+ if (__requireBoolean(__requireBoolean(__normalize(req.url) === "") || __requireBoolean(__normalize(req.url.startsWith("?"))))) {
48
+ req.url = `/${__normalize(req.url)}`;
49
+ }
50
+ }
51
+ let done = __withArity((error) => {
52
+ error = __boundary(error);
53
+ if (__requireBoolean(__normalize(res.headersSent))) {
54
+ __normalize(res.destroy());
55
+ return null;
56
+ }
57
+ let status = 404;
58
+ let code = "NotFound";
59
+ if (__requireBoolean(error !== null)) {
60
+ if (__normalize(error.status) === 400) {
61
+ status = 400;
62
+ code = "InvalidPath";
63
+ } else if (__normalize(error.status) === 403) {
64
+ status = 403;
65
+ code = "Forbidden";
66
+ } else if (__normalize(error.status) === 416) {
67
+ status = 416;
68
+ code = "RangeNotSatisfiable";
69
+ } else if (__normalize(error.status) === 404) {
70
+ status = 404;
71
+ } else {
72
+ status = 500;
73
+ code = "InternalServerError";
74
+ }
75
+ }
76
+ __call(failed, status, code);
77
+ return null;
78
+ }, [0], "closure");
79
+ let serve = __normalize(this.#serve);
80
+ __call(serve, req, res, done);
81
+ return null;
82
+ return null;
83
+ }
84
+ }
85
+ export function staticOptions(root, spec) {
86
+ __requireArity(arguments.length, [0, 1], "staticOptions");
87
+ root = __boundary(root);
88
+ spec = __boundary(spec);
89
+ if (__requireBoolean(spec === null)) {
90
+ return null;
91
+ }
92
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
93
+ throw "static must be a map";
94
+ }
95
+ let allowed = ["path", "directory", "index"];
96
+ for (const [key, value] of __entries(spec)) {
97
+ if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
98
+ throw `Unknown static option: ${key}`;
99
+ }
100
+ }
101
+ let mount = __normalize(spec.path);
102
+ if (__requireBoolean(mount === null)) {
103
+ mount = "/";
104
+ }
105
+ let pattern = new (__hostGlobal(["RegExp"]))("^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$");
106
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(mount))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(mount)))))) {
107
+ throw "Static path must be an absolute URL prefix";
108
+ }
109
+ if (__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(__normalize(mount.endsWith("/"))))) {
110
+ mount = __normalize(mount.slice(0, __finite(-1)));
111
+ }
112
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.directory)))) || __requireBoolean(__normalize(spec.directory.trim()) === ""))) {
113
+ throw "Static directory is required";
114
+ }
115
+ let index = __normalize(spec.index);
116
+ if (__requireBoolean(index === null)) {
117
+ index = "index.html";
118
+ }
119
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
120
+ throw "Static index must be a file name";
121
+ }
122
+ return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index };
123
+ return null;
124
+ }
125
+ //# sourceMappingURL=static_files.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n done = (error)\n capture res\n capture failed\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n failed(status, code)\n serve = @serve\n serve(req, res, done)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,101 @@
1
+ import { DatabaseScope } from "./database_scope.mjs";
2
+ import { SqliteAdapter } from "./sqlite_adapter.mjs";
3
+ import { PostgresAdapter } from "./postgres_adapter.mjs";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ contextGet as __contextGet,
7
+ contextSet as __contextSet,
8
+ contextRestore as __contextRestore,
9
+ requireBoolean as __requireBoolean,
10
+ normalize as __normalize,
11
+ boundary as __boundary,
12
+ query as __query,
13
+ requireArity as __requireArity,
14
+ withArity as __withArity,
15
+ } from "./.lango/runtime.mjs";
16
+
17
+ export class Database {
18
+ #root;
19
+ #settings;
20
+ #adapter;
21
+ constructor(settings, root = null) {
22
+ __requireArity(arguments.length, [0], "constructor");
23
+ settings = __boundary(settings);
24
+ root = __boundary(root);
25
+ this.#root = root;
26
+ this.#settings = settings;
27
+ this.#adapter = null;
28
+ }
29
+ open() {
30
+ if (__requireBoolean(__normalize(this.#settings) === null)) {
31
+ return __normalize(__hostGlobal(["Promise"]).resolve(null));
32
+ }
33
+ let name = "node:sqlite";
34
+ if (__requireBoolean(__normalize(this.#settings.type) === "postgresql")) {
35
+ name = "node:worker_threads";
36
+ }
37
+ return import(name).then(__withArity((mod) => {
38
+ const __contextScope = [];
39
+ try {
40
+ mod = __boundary(mod);
41
+ if (__requireBoolean(__normalize(this.#settings.type) === "sqlite")) {
42
+ this.#adapter = new SqliteAdapter(mod, __normalize(this.#settings));
43
+ } else {
44
+ this.#adapter = new PostgresAdapter(mod, __normalize(this.#settings), __normalize(this.#root));
45
+ }
46
+ __contextScope.push(__contextSet("db", this.scope()));
47
+ try {
48
+ let query = __query("select 1", []);
49
+ __normalize(query.execute());
50
+ } finally {
51
+ __normalize(__contextGet("db").finish());
52
+ }
53
+ return null;
54
+ return null;
55
+ } finally {
56
+ __contextRestore(__contextScope);
57
+ }
58
+ }, [0], "closure")).catch(__withArity((error) => {
59
+ const __contextScope = [];
60
+ try {
61
+ error = __boundary(error);
62
+ __normalize(__contextGet("log").err(`Database startup failed: ${error}`));
63
+ this.close();
64
+ throw "Database startup failed; check configuration, compiler version and driver installation";
65
+ return null;
66
+ } finally {
67
+ __contextRestore(__contextScope);
68
+ }
69
+ }, [0], "closure"));
70
+ return null;
71
+ }
72
+ scope() {
73
+ if (__requireBoolean(__normalize(this.#adapter) === null)) {
74
+ return null;
75
+ }
76
+ return new DatabaseScope(__normalize(this.#adapter));
77
+ return null;
78
+ }
79
+ close() {
80
+ if (__requireBoolean(__normalize(this.#adapter) !== null)) {
81
+ __normalize(this.#adapter.close());
82
+ this.#adapter = null;
83
+ }
84
+ return null;
85
+ return null;
86
+ }
87
+ }
88
+ export function prepareDatabase(settings) {
89
+ __requireArity(arguments.length, [0], "prepareDatabase");
90
+ settings = __boundary(settings);
91
+ if (__requireBoolean(__requireBoolean(__requireBoolean(settings === null) || __requireBoolean(__normalize(settings.type) !== "sqlite")) || __requireBoolean(__normalize(settings.file) === ":memory:"))) {
92
+ return __normalize(__hostGlobal(["Promise"]).resolve(null));
93
+ }
94
+ let database = new Database(settings);
95
+ return __normalize(database.open()).finally(() => {
96
+ __normalize(database.close());
97
+ return null;
98
+ });
99
+ return null;
100
+ }
101
+ //# sourceMappingURL=database.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings)\n if settings == null or settings.type != \"sqlite\" or settings.file == \":memory:\"\n return Promise/resolve(null)\n database = new Database(settings)\n return chain database.open()\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;"}
@@ -0,0 +1,83 @@
1
+ import * as path from "node:path";
2
+ import {
3
+ hostGlobal as __hostGlobal,
4
+ hostGlobalCall as __hostGlobalCall,
5
+ isNumber as __isNumber,
6
+ isString as __isString,
7
+ isBool as __isBool,
8
+ isObject as __isObject,
9
+ isArray as __isArray,
10
+ entries as __entries,
11
+ requireBoolean as __requireBoolean,
12
+ normalize as __normalize,
13
+ boundary as __boundary,
14
+ requireArity as __requireArity,
15
+ } from "./.lango/runtime.mjs";
16
+
17
+ export function databaseOptions(root, spec, workers) {
18
+ __requireArity(arguments.length, [0, 1, 2], "databaseOptions");
19
+ root = __boundary(root);
20
+ spec = __boundary(spec);
21
+ workers = __boundary(workers);
22
+ let file;
23
+ if (__requireBoolean(spec === null)) {
24
+ return null;
25
+ }
26
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
27
+ throw "Database configuration must be a map";
28
+ }
29
+ let allowed = [];
30
+ if (__normalize(spec.type) === "sqlite") {
31
+ allowed = ["type", "file", "busyTimeoutMs"];
32
+ } else if (__normalize(spec.type) === "postgresql") {
33
+ allowed = ["type", "connectionEnv", "queryTimeoutMs", "connectTimeoutSeconds"];
34
+ } else {
35
+ throw "Database type must be sqlite or postgresql";
36
+ }
37
+ for (const [key, value] of __entries(spec)) {
38
+ if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
39
+ throw `Unknown database option: ${key}`;
40
+ }
41
+ }
42
+ if (__requireBoolean(__normalize(spec.type) === "sqlite")) {
43
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.file)))) || __requireBoolean(__normalize(spec.file) === ""))) {
44
+ throw "SQLite database file is required";
45
+ }
46
+ file = __normalize(spec.file);
47
+ if (__requireBoolean(__requireBoolean(file === ":memory:") && __requireBoolean(workers !== 1))) {
48
+ throw "An in-memory SQLite database requires exactly one worker";
49
+ }
50
+ if (__requireBoolean(file !== ":memory:")) {
51
+ file = __normalize(path.resolve(root, file));
52
+ }
53
+ return { type: "sqlite", file: file, busyTimeoutMs: positive(__normalize(spec.busyTimeoutMs), 5000) };
54
+ }
55
+ let name = __normalize(spec.connectionEnv);
56
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(name))) || __requireBoolean(name === "")) || __requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(__hostGlobal(["process"]).env), name)))))) {
57
+ throw "PostgreSQL connectionEnv must name an existing environment variable";
58
+ }
59
+ let connection = __normalize(__hostGlobal(["process"]).env[name]);
60
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(connection))) || __requireBoolean(__requireBoolean(!__requireBoolean(__normalize(connection.startsWith("postgresql://")))) && __requireBoolean(!__requireBoolean(__normalize(connection.startsWith("postgres://"))))))) {
61
+ throw "PostgreSQL connectionEnv must contain a PostgreSQL connection URL";
62
+ }
63
+ return { type: "postgresql", connection: connection, queryTimeoutMs: positive(__normalize(spec.queryTimeoutMs), 5000), connectTimeoutSeconds: positive(__normalize(spec.connectTimeoutSeconds), 5) };
64
+ return null;
65
+ }
66
+
67
+ function positive(value, fallback) {
68
+ __requireArity(arguments.length, [0, 1], "positive");
69
+ value = __boundary(value);
70
+ fallback = __boundary(fallback);
71
+ if (__requireBoolean(value === null)) {
72
+ return fallback;
73
+ }
74
+ if (__requireBoolean(__isString(value))) {
75
+ value = __hostGlobalCall(["Number"], value);
76
+ }
77
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(value)))) || __requireBoolean(value < 1)) || __requireBoolean(value > 2147483647))) {
78
+ throw "Database timeout must be a positive integer within the timer limit";
79
+ }
80
+ return value;
81
+ return null;
82
+ }
83
+ //# sourceMappingURL=database_options.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database_options.mjs","sources":["database_options.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport databaseOptions(root, spec, workers)\n\ndatabaseOptions(root, spec, workers)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Database configuration must be a map\"\n allowed = []\n switch spec.type\n case \"sqlite\"\n allowed = [\"type\", \"file\", \"busyTimeoutMs\"]\n case \"postgresql\"\n allowed = [\"type\", \"connectionEnv\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"]\n else\n throw \"Database type must be sqlite or postgresql\"\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown database option: ${key}\"\n if spec.type == \"sqlite\"\n if !is_string(spec.file) or spec.file == \"\"\n throw \"SQLite database file is required\"\n file = spec.file\n if file == \":memory:\" and workers != 1\n throw \"An in-memory SQLite database requires exactly one worker\"\n if file != \":memory:\"\n file = path/resolve(root, file)\n return {\n type: \"sqlite\"\n file: file\n busyTimeoutMs: positive(spec.busyTimeoutMs, 5000)\n }\n name = spec.connectionEnv\n if !is_string(name) or name == \"\" or !Object/hasOwn(process.env, name)\n throw \"PostgreSQL connectionEnv must name an existing environment variable\"\n connection = process.env[name]\n if !is_string(connection) or (!connection.startsWith(\"postgresql://\") and !connection.startsWith(\"postgres://\"))\n throw \"PostgreSQL connectionEnv must contain a PostgreSQL connection URL\"\n return {\n type: \"postgresql\"\n connection: connection\n queryTimeoutMs: positive(spec.queryTimeoutMs, 5000)\n connectTimeoutSeconds: positive(spec.connectTimeoutSeconds, 5)\n }\n\npositive(value, fallback)\n if value == null\n return fallback\n if is_string(value)\n value = Number(value)\n if !Number/isSafeInteger(value) or value < 1 or value > 2147483647\n throw \"Database timeout must be a positive integer within the timer limit\"\n return value\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,82 @@
1
+ import {
2
+ hostGlobal as __hostGlobal,
3
+ contextGet as __contextGet,
4
+ contextSet as __contextSet,
5
+ contextRestore as __contextRestore,
6
+ requireBoolean as __requireBoolean,
7
+ normalize as __normalize,
8
+ boundary as __boundary,
9
+ requireArity as __requireArity,
10
+ } from "./.lango/runtime.mjs";
11
+
12
+ export class DatabaseScope {
13
+ parameterStyle;
14
+ #adapter;
15
+ #closed;
16
+ constructor(adapter) {
17
+ __requireArity(arguments.length, [0], "constructor");
18
+ adapter = __boundary(adapter);
19
+ this.#adapter = adapter;
20
+ this.#closed = false;
21
+ this.parameterStyle = __normalize(adapter.parameterStyle);
22
+ }
23
+ execute(sql, parameters) {
24
+ __requireArity(arguments.length, [0, 1], "execute");
25
+ sql = __boundary(sql);
26
+ parameters = __boundary(parameters);
27
+ this.#requireOpen();
28
+ return __normalize(this.#adapter.execute(sql, parameters));
29
+ return null;
30
+ }
31
+ begin() {
32
+ this.#requireOpen();
33
+ return __normalize(this.#adapter.begin());
34
+ return null;
35
+ }
36
+ commit() {
37
+ this.#requireOpen();
38
+ return __normalize(this.#adapter.commit());
39
+ return null;
40
+ }
41
+ rollback() {
42
+ this.#requireOpen();
43
+ return __normalize(this.#adapter.rollback());
44
+ return null;
45
+ }
46
+ transactionState() {
47
+ this.#requireOpen();
48
+ return __normalize(this.#adapter.transactionState());
49
+ return null;
50
+ }
51
+ #requireOpen() {
52
+ if (__requireBoolean(__normalize(this.#closed))) {
53
+ throw new (__hostGlobal(["Error"]))("DatabaseScopeClosed");
54
+ }
55
+ return null;
56
+ return null;
57
+ }
58
+ finish() {
59
+ const __contextScope = [];
60
+ try {
61
+ if (__requireBoolean(__normalize(this.#closed))) {
62
+ return false;
63
+ }
64
+ this.#closed = true;
65
+ let dirty = false;
66
+ try {
67
+ __loop1: while (__requireBoolean(__normalize(this.#adapter.transactionState()) !== null)) {
68
+ dirty = true;
69
+ __normalize(this.#adapter.rollback());
70
+ }
71
+ } catch (error) {
72
+ __normalize(__contextGet("log").err("Database cleanup failed; retiring worker"));
73
+ __normalize(__hostGlobal(["process"]).exit(1));
74
+ }
75
+ return dirty;
76
+ return null;
77
+ } finally {
78
+ __contextRestore(__contextScope);
79
+ }
80
+ }
81
+ }
82
+ //# sourceMappingURL=database_scope.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database_scope.mjs","sources":["database_scope.lango"],"sourcesContent":["import js global Error\nimport js global Object\nimport js global process\n\nexport class DatabaseScope(adapter)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n begin()\n commit()\n rollback()\n transactionState()\n finish()\n\nDatabaseScope(adapter)\n @adapter = adapter\n @closed = false\n @parameterStyle = adapter.parameterStyle\n\nDatabaseScope:execute(sql, parameters)\n requireOpen()\n return @adapter.execute(sql, parameters)\n\nDatabaseScope:begin()\n requireOpen()\n return @adapter.begin()\n\nDatabaseScope:commit()\n requireOpen()\n return @adapter.commit()\n\nDatabaseScope:rollback()\n requireOpen()\n return @adapter.rollback()\n\nDatabaseScope:transactionState()\n requireOpen()\n return @adapter.transactionState()\n\nDatabaseScope:requireOpen()\n if @closed\n throw new Error(\"DatabaseScopeClosed\")\n return null\n\nDatabaseScope:finish()\n if @closed\n return false\n @closed = true\n dirty = false\n try\n loop while @adapter.transactionState() != null\n dirty = true\n @adapter.rollback()\n catch error\n context log\n log.err(\"Database cleanup failed; retiring worker\")\n process.exit(1)\n return dirty\n"],"names":[],"mappings":";;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}