@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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +710 -2
- package/dist/.lango/bignumber.mjs +3119 -0
- package/dist/.lango/runtime.mjs +683 -0
- package/dist/.lango/xmldom/conventions.js +429 -0
- package/dist/.lango/xmldom/dom-parser.js +591 -0
- package/dist/.lango/xmldom/dom.js +3759 -0
- package/dist/.lango/xmldom/entities.js +2171 -0
- package/dist/.lango/xmldom/errors.js +205 -0
- package/dist/.lango/xmldom/grammar.js +559 -0
- package/dist/.lango/xmldom/index.js +41 -0
- package/dist/.lango/xmldom/package.json +1 -0
- package/dist/.lango/xmldom/sax.js +983 -0
- package/dist/.lango/xmldom.LICENSE.md +8 -0
- package/dist/body_reader.mjs +179 -0
- package/dist/body_reader.mjs.map +1 -0
- package/dist/builder.mjs +84 -0
- package/dist/builder.mjs.map +1 -0
- package/dist/cli/.lango/bignumber.mjs +3119 -0
- package/dist/cli/.lango/runtime.mjs +683 -0
- package/dist/cli/.lango/xmldom/conventions.js +429 -0
- package/dist/cli/.lango/xmldom/dom-parser.js +591 -0
- package/dist/cli/.lango/xmldom/dom.js +3759 -0
- package/dist/cli/.lango/xmldom/entities.js +2171 -0
- package/dist/cli/.lango/xmldom/errors.js +205 -0
- package/dist/cli/.lango/xmldom/grammar.js +559 -0
- package/dist/cli/.lango/xmldom/index.js +41 -0
- package/dist/cli/.lango/xmldom/package.json +1 -0
- package/dist/cli/.lango/xmldom/sax.js +983 -0
- package/dist/cli/.lango/xmldom.LICENSE.md +8 -0
- package/dist/cli/body_reader.mjs +179 -0
- package/dist/cli/body_reader.mjs.map +1 -0
- package/dist/cli/database.mjs +101 -0
- package/dist/cli/database.mjs.map +1 -0
- package/dist/cli/database_options.mjs +83 -0
- package/dist/cli/database_options.mjs.map +1 -0
- package/dist/cli/database_scope.mjs +82 -0
- package/dist/cli/database_scope.mjs.map +1 -0
- package/dist/cli/endpoint.mjs +50 -0
- package/dist/cli/endpoint.mjs.map +1 -0
- package/dist/cli/longpoll_broker.mjs +214 -0
- package/dist/cli/longpoll_broker.mjs.map +1 -0
- package/dist/cli/longpoll_options.mjs +102 -0
- package/dist/cli/longpoll_options.mjs.map +1 -0
- package/dist/cli/longpoll_session.mjs +135 -0
- package/dist/cli/longpoll_session.mjs.map +1 -0
- package/dist/cli/middleware.mjs +25 -0
- package/dist/cli/middleware.mjs.map +1 -0
- package/dist/cli/options.mjs +177 -0
- package/dist/cli/options.mjs.map +1 -0
- package/dist/cli/postgres_adapter.mjs +166 -0
- package/dist/cli/postgres_adapter.mjs.map +1 -0
- package/dist/cli/routes.mjs +297 -0
- package/dist/cli/routes.mjs.map +1 -0
- package/dist/cli/server.mjs +792 -0
- package/dist/cli/server.mjs.map +1 -0
- package/dist/cli/sqlite_adapter.mjs +163 -0
- package/dist/cli/sqlite_adapter.mjs.map +1 -0
- package/dist/cli/static_files.mjs +125 -0
- package/dist/cli/static_files.mjs.map +1 -0
- package/dist/database.mjs +101 -0
- package/dist/database.mjs.map +1 -0
- package/dist/database_options.mjs +83 -0
- package/dist/database_options.mjs.map +1 -0
- package/dist/database_scope.mjs +82 -0
- package/dist/database_scope.mjs.map +1 -0
- package/dist/endpoint.mjs +50 -0
- package/dist/endpoint.mjs.map +1 -0
- package/dist/group.mjs +91 -0
- package/dist/group.mjs.map +1 -0
- package/dist/library.mjs +6 -0
- package/dist/library.mjs.map +1 -0
- package/dist/longpoll_broker.mjs +214 -0
- package/dist/longpoll_broker.mjs.map +1 -0
- package/dist/longpoll_options.mjs +102 -0
- package/dist/longpoll_options.mjs.map +1 -0
- package/dist/longpoll_session.mjs +135 -0
- package/dist/longpoll_session.mjs.map +1 -0
- package/dist/middleware.mjs +25 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/options.mjs +177 -0
- package/dist/options.mjs.map +1 -0
- package/dist/postgres_adapter.mjs +166 -0
- package/dist/postgres_adapter.mjs.map +1 -0
- package/dist/postgres_worker.mjs +119 -0
- package/dist/postgres_worker.mjs.map +1 -0
- package/dist/response.mjs +62 -0
- package/dist/response.mjs.map +1 -0
- package/dist/routes.mjs +297 -0
- package/dist/routes.mjs.map +1 -0
- package/dist/runtime.mjs +549 -0
- package/dist/runtime.mjs.map +1 -0
- package/dist/server.mjs +788 -0
- package/dist/server.mjs.map +1 -0
- package/dist/server_context.mjs +78 -0
- package/dist/server_context.mjs.map +1 -0
- package/dist/sqlite_adapter.mjs +163 -0
- package/dist/sqlite_adapter.mjs.map +1 -0
- package/dist/static_files.mjs +125 -0
- package/dist/static_files.mjs.map +1 -0
- package/dist/token.mjs +106 -0
- package/dist/token.mjs.map +1 -0
- package/dist/tokens.mjs +76 -0
- package/dist/tokens.mjs.map +1 -0
- package/dist/worker.mjs +57 -0
- package/dist/worker.mjs.map +1 -0
- package/package.json +44 -4
- package/src/body_reader.lango +113 -0
- package/src/builder.lango +64 -0
- package/src/database.lango +66 -0
- package/src/database_options.lango +57 -0
- package/src/database_scope.lango +59 -0
- package/src/endpoint.lango +30 -0
- package/src/group.lango +61 -0
- package/src/library.lango +10 -0
- package/src/longpoll.lua +61 -0
- package/src/longpoll_broker.lango +161 -0
- package/src/longpoll_options.lango +79 -0
- package/src/longpoll_session.lango +90 -0
- package/src/middleware.lango +10 -0
- package/src/options.lango +144 -0
- package/src/postgres_adapter.lango +138 -0
- package/src/postgres_worker.lango +114 -0
- package/src/response.lango +42 -0
- package/src/routes.lango +224 -0
- package/src/runtime.lango +382 -0
- package/src/server.lango +597 -0
- package/src/server_context.lango +58 -0
- package/src/sqlite_adapter.lango +127 -0
- package/src/static_files.lango +90 -0
- package/src/token.lango +70 -0
- package/src/tokens.lango +70 -0
- 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,78 @@
|
|
|
1
|
+
import * as threads from "node:worker_threads";
|
|
2
|
+
import {
|
|
3
|
+
hostGlobal as __hostGlobal,
|
|
4
|
+
hostGlobalCall as __hostGlobalCall,
|
|
5
|
+
fromJson as __fromJson,
|
|
6
|
+
toJson as __toJson,
|
|
7
|
+
requireBoolean as __requireBoolean,
|
|
8
|
+
normalize as __normalize,
|
|
9
|
+
call as __call,
|
|
10
|
+
boundary as __boundary,
|
|
11
|
+
requireArity as __requireArity,
|
|
12
|
+
withArity as __withArity,
|
|
13
|
+
} from "./.lango/runtime.mjs";
|
|
14
|
+
|
|
15
|
+
export class ServerContext {
|
|
16
|
+
constructor() {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
publish(path, key, data) {
|
|
20
|
+
__requireArity(arguments.length, [0, 1, 2], "publish");
|
|
21
|
+
path = __boundary(path);
|
|
22
|
+
key = __boundary(key);
|
|
23
|
+
data = __boundary(data);
|
|
24
|
+
return invoke("publish", path, key, data);
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
cursor(path, key) {
|
|
28
|
+
__requireArity(arguments.length, [0, 1], "cursor");
|
|
29
|
+
path = __boundary(path);
|
|
30
|
+
key = __boundary(key);
|
|
31
|
+
return invoke("cursor", path, key, null);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function invoke(operation, path, key, data) {
|
|
36
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "invoke");
|
|
37
|
+
operation = __boundary(operation);
|
|
38
|
+
path = __boundary(path);
|
|
39
|
+
key = __boundary(key);
|
|
40
|
+
data = __boundary(data);
|
|
41
|
+
let channel = new threads.MessageChannel();
|
|
42
|
+
let port = __normalize(channel.port1);
|
|
43
|
+
let remote = __normalize(channel.port2);
|
|
44
|
+
let pending = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
|
|
45
|
+
resolve = __boundary(resolve);
|
|
46
|
+
reject = __boundary(reject);
|
|
47
|
+
__normalize(port.once("message", __withArity((message) => {
|
|
48
|
+
message = __boundary(message);
|
|
49
|
+
if (__requireBoolean(__normalize(message.ok))) {
|
|
50
|
+
__call(resolve, __normalize(message.value));
|
|
51
|
+
} else {
|
|
52
|
+
__call(reject, "Longpoll operation failed");
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}, [0], "closure")));
|
|
56
|
+
return null;
|
|
57
|
+
}, [0, 1], "closure"));
|
|
58
|
+
let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
|
|
59
|
+
let fail = () => {
|
|
60
|
+
__normalize(expired.reject("Longpoll operation timed out"));
|
|
61
|
+
return null;
|
|
62
|
+
};
|
|
63
|
+
let timer = __hostGlobalCall(["setTimeout"], fail, 4000);
|
|
64
|
+
try {
|
|
65
|
+
__normalize(threads.parentPort.postMessage({ kind: "longpoll", operation: operation, path: path, key: key, data: __fromJson(__toJson(data)), port: remote }, [remote]));
|
|
66
|
+
} catch (error) {
|
|
67
|
+
__normalize(port.close());
|
|
68
|
+
__hostGlobalCall(["clearTimeout"], timer);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
|
|
72
|
+
__hostGlobalCall(["clearTimeout"], timer);
|
|
73
|
+
__normalize(port.close());
|
|
74
|
+
return null;
|
|
75
|
+
});
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=server_context.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class ServerContext()\n methods\n publish(path, key, data)\n cursor(path, key)\n\nServerContext()\n return null\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/token.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { contains } from "./options.mjs";
|
|
2
|
+
import {
|
|
3
|
+
hostGlobal as __hostGlobal,
|
|
4
|
+
fromJson as __fromJson,
|
|
5
|
+
toJson as __toJson,
|
|
6
|
+
isNumber as __isNumber,
|
|
7
|
+
isString as __isString,
|
|
8
|
+
isBool as __isBool,
|
|
9
|
+
isObject as __isObject,
|
|
10
|
+
isArray as __isArray,
|
|
11
|
+
requireBoolean as __requireBoolean,
|
|
12
|
+
normalize as __normalize,
|
|
13
|
+
boundary as __boundary,
|
|
14
|
+
requireArity as __requireArity,
|
|
15
|
+
} from "./.lango/runtime.mjs";
|
|
16
|
+
|
|
17
|
+
export class Token {
|
|
18
|
+
clientId;
|
|
19
|
+
auth;
|
|
20
|
+
expiresAt;
|
|
21
|
+
#claims;
|
|
22
|
+
#readonly;
|
|
23
|
+
constructor(claims, readonly = false) {
|
|
24
|
+
__requireArity(arguments.length, [0], "constructor");
|
|
25
|
+
claims = __boundary(claims);
|
|
26
|
+
readonly = __boundary(readonly);
|
|
27
|
+
this.#claims = __fromJson(__toJson(claims));
|
|
28
|
+
this.#readonly = readonly;
|
|
29
|
+
this.clientId = __normalize(claims.clientId);
|
|
30
|
+
this.auth = __normalize(claims.auth);
|
|
31
|
+
this.expiresAt = __normalize(claims.exp);
|
|
32
|
+
}
|
|
33
|
+
AddAuth(permission) {
|
|
34
|
+
__requireArity(arguments.length, [0], "AddAuth");
|
|
35
|
+
permission = __boundary(permission);
|
|
36
|
+
this.#writable();
|
|
37
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(permission))) || __requireBoolean(__normalize(permission.trim()) === "")) || __requireBoolean(__normalize(permission.includes(","))))) {
|
|
38
|
+
throw "Permission must be a nonempty name without commas";
|
|
39
|
+
}
|
|
40
|
+
permission = __normalize(permission.trim());
|
|
41
|
+
if (__requireBoolean(!__requireBoolean(this.hasAuth(permission)))) {
|
|
42
|
+
if (__requireBoolean(__normalize(this.auth) === "")) {
|
|
43
|
+
this.auth = permission;
|
|
44
|
+
} else {
|
|
45
|
+
this.auth = `${__normalize(this.auth)}, ${permission}`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return this;
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
clearAuth() {
|
|
52
|
+
this.#writable();
|
|
53
|
+
this.auth = "";
|
|
54
|
+
return this;
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
hasAuth(permission) {
|
|
58
|
+
__requireArity(arguments.length, [0], "hasAuth");
|
|
59
|
+
permission = __boundary(permission);
|
|
60
|
+
for (const name of __normalize(this.auth.split(","))) {
|
|
61
|
+
if (__requireBoolean(__normalize(name.trim()) === permission)) {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
get(name) {
|
|
69
|
+
__requireArity(arguments.length, [0], "get");
|
|
70
|
+
name = __boundary(name);
|
|
71
|
+
if (__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(this.#claims), name))))) {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
return __fromJson(__toJson(__normalize(this.#claims[name])));
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
set(name, value) {
|
|
78
|
+
__requireArity(arguments.length, [0, 1], "set");
|
|
79
|
+
name = __boundary(name);
|
|
80
|
+
value = __boundary(value);
|
|
81
|
+
this.#writable();
|
|
82
|
+
if (__requireBoolean(contains(["clientId", "auth", "iat", "exp", "iss", "aud", "validatedAt", "nbf", "__proto__", "constructor", "prototype"], name))) {
|
|
83
|
+
throw `Reserved token field: ${name}`;
|
|
84
|
+
}
|
|
85
|
+
this.#claims[name] = __fromJson(__toJson(value));
|
|
86
|
+
return this;
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
snapshot() {
|
|
90
|
+
let claims = __fromJson(__toJson(__normalize(this.#claims)));
|
|
91
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(this.clientId) !== __normalize(claims.clientId)) || __requireBoolean(__normalize(this.expiresAt) !== __normalize(claims.exp))) || __requireBoolean(!__requireBoolean(__isString(__normalize(this.auth)))))) {
|
|
92
|
+
throw "Token identity and expiry cannot be changed";
|
|
93
|
+
}
|
|
94
|
+
claims.auth = __normalize(this.auth);
|
|
95
|
+
return claims;
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
#writable() {
|
|
99
|
+
if (__requireBoolean(__normalize(this.#readonly))) {
|
|
100
|
+
throw "Token is read-only during this event";
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=token.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId\n auth\n expiresAt\n methods\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n\nToken:AddAuth(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasAuth(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearAuth()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasAuth(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/tokens.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import * as jwt from "jsonwebtoken";
|
|
2
|
+
import * as crypto from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
hostGlobal as __hostGlobal,
|
|
5
|
+
isNumber as __isNumber,
|
|
6
|
+
isString as __isString,
|
|
7
|
+
isBool as __isBool,
|
|
8
|
+
isObject as __isObject,
|
|
9
|
+
isArray as __isArray,
|
|
10
|
+
requireBoolean as __requireBoolean,
|
|
11
|
+
normalize as __normalize,
|
|
12
|
+
finite as __finite,
|
|
13
|
+
numericAdd as __numericAdd,
|
|
14
|
+
boundary as __boundary,
|
|
15
|
+
requireArity as __requireArity,
|
|
16
|
+
} from "./.lango/runtime.mjs";
|
|
17
|
+
|
|
18
|
+
export class Tokens {
|
|
19
|
+
#settings;
|
|
20
|
+
constructor(settings) {
|
|
21
|
+
__requireArity(arguments.length, [0], "constructor");
|
|
22
|
+
settings = __boundary(settings);
|
|
23
|
+
this.#settings = settings;
|
|
24
|
+
}
|
|
25
|
+
create() {
|
|
26
|
+
let settings = __normalize(this.#settings);
|
|
27
|
+
let now = __normalize(__hostGlobal(["Math"]).floor(__finite(__normalize(__hostGlobal(["Date"]).now()) / 1000)));
|
|
28
|
+
return { clientId: __normalize(crypto.randomUUID()), auth: "", iat: now, exp: __numericAdd(now, __normalize(settings.ttlSeconds)), iss: __normalize(settings.issuer), aud: __normalize(settings.audience), validatedAt: __normalize(__hostGlobal(["Date"]).now()) };
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
read(header) {
|
|
32
|
+
__requireArity(arguments.length, [0], "read");
|
|
33
|
+
header = __boundary(header);
|
|
34
|
+
let settings = __normalize(this.#settings);
|
|
35
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(header))) || __requireBoolean(__normalize(header.length) > 16384)) || __requireBoolean(__normalize(__normalize(header.slice(0, 7)).toLowerCase()) !== "bearer ")) || __requireBoolean(__normalize(header.length) === 7))) {
|
|
36
|
+
throw "InvalidToken";
|
|
37
|
+
}
|
|
38
|
+
let encoded = __normalize(header.slice(7));
|
|
39
|
+
let decoded = __normalize(jwt.default.decode(encoded, { complete: true }));
|
|
40
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(decoded))) || __requireBoolean(!__requireBoolean(__isObject(__normalize(decoded.header)))))) {
|
|
41
|
+
throw "InvalidToken";
|
|
42
|
+
}
|
|
43
|
+
let head = __normalize(decoded.header);
|
|
44
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(head.alg) !== "HS256") || __requireBoolean(__normalize(head.typ) !== "JWT")) || __requireBoolean(!__requireBoolean(__isString(__normalize(head.kid))))) || __requireBoolean(__normalize(head.crit) !== null)) || __requireBoolean(__normalize(head.b64) !== null))) {
|
|
45
|
+
throw "InvalidToken";
|
|
46
|
+
}
|
|
47
|
+
let keys = __normalize(settings.keys);
|
|
48
|
+
if (__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(keys, __normalize(head.kid)))))) {
|
|
49
|
+
throw "InvalidToken";
|
|
50
|
+
}
|
|
51
|
+
let claims = __normalize(jwt.default.verify(encoded, __normalize(keys[__normalize(head.kid)]), { algorithms: ["HS256"], issuer: __normalize(settings.issuer), audience: __normalize(settings.audience) }));
|
|
52
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(claims))) || __requireBoolean(!__requireBoolean(__isString(__normalize(claims.clientId))))) || __requireBoolean(__normalize(claims.clientId) === "")) || __requireBoolean(!__requireBoolean(__isString(__normalize(claims.auth)))))) {
|
|
53
|
+
throw "InvalidToken";
|
|
54
|
+
}
|
|
55
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.iat))))) || __requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.exp)))))) || __requireBoolean(__normalize(claims.exp) <= __normalize(claims.iat))) || __requireBoolean(__finite(__normalize(claims.exp) - __normalize(claims.iat)) > __normalize(settings.ttlSeconds))) || __requireBoolean(__finite(__normalize(claims.iat) * 1000) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
56
|
+
throw "InvalidToken";
|
|
57
|
+
}
|
|
58
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) < __finite(__normalize(claims.iat) * 1000))) || __requireBoolean(__normalize(claims.validatedAt) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
59
|
+
throw "InvalidToken";
|
|
60
|
+
}
|
|
61
|
+
return claims;
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
sign(claims) {
|
|
65
|
+
__requireArity(arguments.length, [0], "sign");
|
|
66
|
+
claims = __boundary(claims);
|
|
67
|
+
let settings = __normalize(this.#settings);
|
|
68
|
+
if (__requireBoolean(__finite(__normalize(claims.exp) * 1000) <= __normalize(__hostGlobal(["Date"]).now()))) {
|
|
69
|
+
throw "TokenExpired";
|
|
70
|
+
}
|
|
71
|
+
let keys = __normalize(settings.keys);
|
|
72
|
+
return __normalize(jwt.default.sign(claims, __normalize(keys[__normalize(settings.activeKeyId)]), { algorithm: "HS256", header: { typ: "JWT", kid: __normalize(settings.activeKeyId) } }));
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=tokens.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < claims.iat * 1000 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|