@lango-project/lango-server 0.2.2 → 0.2.3

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 (106) hide show
  1. package/README.md +239 -27
  2. package/dist/.lango/runtime.mjs +16 -0
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/cli/.lango/runtime.mjs +16 -0
  6. package/dist/cli/body_reader.mjs +15 -14
  7. package/dist/cli/body_reader.mjs.map +1 -1
  8. package/dist/cli/client_identity.mjs +250 -0
  9. package/dist/cli/client_identity.mjs.map +1 -0
  10. package/dist/cli/database.mjs +23 -8
  11. package/dist/cli/database.mjs.map +1 -1
  12. package/dist/cli/endpoint.mjs +11 -7
  13. package/dist/cli/endpoint.mjs.map +1 -1
  14. package/dist/cli/longpoll_broker.mjs +9 -8
  15. package/dist/cli/longpoll_broker.mjs.map +1 -1
  16. package/dist/cli/longpoll_options.mjs +8 -7
  17. package/dist/cli/longpoll_options.mjs.map +1 -1
  18. package/dist/cli/longpoll_session.mjs +11 -10
  19. package/dist/cli/longpoll_session.mjs.map +1 -1
  20. package/dist/cli/options.mjs +29 -3
  21. package/dist/cli/options.mjs.map +1 -1
  22. package/dist/cli/origin.mjs +87 -0
  23. package/dist/cli/origin.mjs.map +1 -0
  24. package/dist/cli/policy.mjs +121 -0
  25. package/dist/cli/policy.mjs.map +1 -0
  26. package/dist/cli/postgres_adapter.mjs +3 -2
  27. package/dist/cli/postgres_adapter.mjs.map +1 -1
  28. package/dist/cli/routes.mjs +33 -17
  29. package/dist/cli/routes.mjs.map +1 -1
  30. package/dist/cli/server.mjs +84 -80
  31. package/dist/cli/server.mjs.map +1 -1
  32. package/dist/cli/static_files.mjs +5 -4
  33. package/dist/cli/static_files.mjs.map +1 -1
  34. package/dist/client_identity.mjs +250 -0
  35. package/dist/client_identity.mjs.map +1 -0
  36. package/dist/database.mjs +23 -8
  37. package/dist/database.mjs.map +1 -1
  38. package/dist/endpoint.mjs +11 -7
  39. package/dist/endpoint.mjs.map +1 -1
  40. package/dist/group.mjs +34 -16
  41. package/dist/group.mjs.map +1 -1
  42. package/dist/http_failure.mjs +9 -2
  43. package/dist/http_failure.mjs.map +1 -1
  44. package/dist/longpoll_broker.mjs +9 -8
  45. package/dist/longpoll_broker.mjs.map +1 -1
  46. package/dist/longpoll_options.mjs +8 -7
  47. package/dist/longpoll_options.mjs.map +1 -1
  48. package/dist/longpoll_session.mjs +11 -10
  49. package/dist/longpoll_session.mjs.map +1 -1
  50. package/dist/options.mjs +29 -3
  51. package/dist/options.mjs.map +1 -1
  52. package/dist/origin.mjs +87 -0
  53. package/dist/origin.mjs.map +1 -0
  54. package/dist/policy.mjs +121 -0
  55. package/dist/policy.mjs.map +1 -0
  56. package/dist/postgres_adapter.mjs +3 -2
  57. package/dist/postgres_adapter.mjs.map +1 -1
  58. package/dist/postgres_worker.mjs +15 -14
  59. package/dist/postgres_worker.mjs.map +1 -1
  60. package/dist/response.mjs +1 -1
  61. package/dist/response.mjs.map +1 -1
  62. package/dist/route_info.mjs +1 -1
  63. package/dist/route_info.mjs.map +1 -1
  64. package/dist/routes.mjs +33 -17
  65. package/dist/routes.mjs.map +1 -1
  66. package/dist/runtime.mjs +227 -112
  67. package/dist/runtime.mjs.map +1 -1
  68. package/dist/server.mjs +84 -80
  69. package/dist/server.mjs.map +1 -1
  70. package/dist/server_context.mjs +21 -9
  71. package/dist/server_context.mjs.map +1 -1
  72. package/dist/static_files.mjs +5 -4
  73. package/dist/static_files.mjs.map +1 -1
  74. package/dist/token.mjs +34 -7
  75. package/dist/token.mjs.map +1 -1
  76. package/dist/tokens.mjs +11 -2
  77. package/dist/tokens.mjs.map +1 -1
  78. package/dist/worker.mjs +7 -6
  79. package/dist/worker.mjs.map +1 -1
  80. package/docs/security.md +420 -0
  81. package/examples/security/README.md +160 -0
  82. package/examples/security/deploy.xml +12 -0
  83. package/examples/security/handlers.lango +610 -0
  84. package/examples/security/package.json +19 -0
  85. package/examples/security/passwords.lango +61 -0
  86. package/examples/security/routes.xml +14 -0
  87. package/examples/security/schema.lango +91 -0
  88. package/examples/security/setup.lango +30 -0
  89. package/package.json +12 -6
  90. package/src/client_identity.lango +184 -0
  91. package/src/database.lango +15 -4
  92. package/src/endpoint.lango +12 -5
  93. package/src/group.lango +25 -21
  94. package/src/http_failure.lango +9 -5
  95. package/src/longpoll_options.lango +11 -5
  96. package/src/options.lango +34 -1
  97. package/src/origin.lango +56 -0
  98. package/src/policy.lango +84 -0
  99. package/src/response.lango +1 -1
  100. package/src/route_info.lango +2 -0
  101. package/src/routes.lango +30 -15
  102. package/src/runtime.lango +131 -80
  103. package/src/server.lango +6 -2
  104. package/src/server_context.lango +10 -2
  105. package/src/token.lango +26 -5
  106. package/src/tokens.lango +10 -3
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\nimport \"./request_identity\"\n requestIdentity(id, token)\nimport \"./error_details\"\n errorDetails(error)\n errorMessage(error)\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n @serverContext = new ServerContext(definition.routes, refresh)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n trace(\"Worker ${threads.threadId}: preparing database, middleware, routes and events\")\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n trace(\"Worker ${threads.threadId}: resolving ${file} export ${spec.handler}\")\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n trace(\"${requestIdentity(request.id, token)} Matched route ${matched.route.path}; fresh=${fresh}\")\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n trace(\"${requestIdentity(request.id, token)} Invoking handler; middleware=${route.middleware != null}\")\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n trace(\"${requestIdentity(request.id, token)} Handler completed; serializing response\")\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n trace(\"${requestIdentity(request.id, token)} Request completed status=${result.status}\")\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n capture token\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n log.warn(\"${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized\")\n return failure(401, \"Unauthorized\")\n log.err(\"${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n trace(\"${requestIdentity(request.id, token)} Running event ${name}\")\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n logIdentity: requestIdentity(id, token)\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n capture request\n capture token\n closeScope(db, false)\n log.err(\"${requestIdentity(request.id, token)} Request event failed: ${errorDetails(error)}\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA;;;;;;;;;;;AAmVA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport \"./route_info\"\n routeInfo(definitions)\nimport js global Number\nimport \"./client_identity\"\n class ClientIdentity\nimport \"./origin\"\n originAllowed(spec, request)\nimport \"./trace\"\n trace(message)\nimport \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\nimport \"./request_identity\"\n requestIdentity(id, token)\nimport \"./error_details\"\n errorDetails(error)\n errorMessage(error)\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n rotate = ()\n return rotateClient()\n @serverContext = new ServerContext(definition.routes, refresh, rotate)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n @clients = null\n if definition.settings.client != null\n @clients = new ClientIdentity(definition.settings.client, @database)\n\nRuntime:preload()\n trace(\"Worker ${threads.threadId}: preparing database, middleware, routes and events\")\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n legacyAuth: route.legacyAuth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n trace(\"Worker ${threads.threadId}: resolving ${file} export ${spec.handler}\")\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n if !originAllowed(@definition.settings.origin, request)\n return failure(403, \"OriginRejected\")\n fresh = request.headers.authorization == null\n claims = null\n try\n if !fresh\n claims = @tokens.read(request.headers.authorization)\n catch error\n log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\n return failure(404, \"RouteNotFound\")\n route = matched.route\n metadata = routeInfo([route])\n selected = Object/freeze(metadata[0])\n context request = Object/freeze(Object/assign({}, request, {\n route: selected\n }))\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context db = @database.scope()\n context clientIdentity = null\n restored = false\n try\n if @clients != null\n context clientIdentity = @clients.begin(claims, @tokens)\n claims = clientIdentity.claims\n fresh = clientIdentity.fresh\n restored = clientIdentity.restored\n if claims == null\n claims = @tokens.create()\n catch error\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n log.err(\"[${request.id}] Client identity failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n return process(task, route, input, claims, fresh, restored)\n\nRuntime:rotateClient()\n context clientIdentity\n if @clients == null or clientIdentity == null\n throw \"Managed client identity is unavailable\"\n if clientIdentity.closed\n throw \"Client identity scope is closed\"\n clientIdentity.rotate = true\n return null\n\nRuntime:signResponse(claims)\n context clientIdentity\n context response\n if @clients == null\n return @tokens.sign(claims)\n return @clients.publish(clientIdentity, claims, response, @tokens)\n\nRuntime:process(task, route, input, claims, fresh, restored)\n context request\n context response\n context log\n context db\n context token = new Token(claims)\n trace(\"${requestIdentity(request.id, token)} Matched route ${route.path}; fresh=${fresh}\")\n return chain Promise/resolve(null)\n then(ignored)\n capture fresh\n capture restored\n capture input\n if fresh\n registration = Object/assign({}, input, {\n ip: request.remoteAddress\n userAgent: request.headers[\"user-agent\"]\n })\n return event(\"register\", registration)\n return validate(restored)\n then(validatedAt)\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.policy != \"anonymous\" and !token.hasPolicy(route.policy)\n if route.legacyAuth\n response.reject(401, \"Unauthorized\")\n if route.policy == \"login\" or !token.hasPolicy(\"login\")\n needLogin(route, 401, \"LoginRequired\")\n response.reject(403, \"Forbidden\")\n if route.reauthSeconds > 0\n authenticatedAt = token.get(\"authenticatedAt\")\n now = Date/now()\n if !Number/isSafeInteger(authenticatedAt) or authenticatedAt < 0 or authenticatedAt > now\n needLogin(route, 403, \"ReauthenticationRequired\")\n if now - authenticatedAt >= route.reauthSeconds * 1000\n needLogin(route, 403, \"ReauthenticationRequired\")\n expected = request.headers[\"x-lango-expected-user\"]\n if expected != null and expected != to_json(token.get(\"userId\"))\n response.reject(409, \"IdentityChanged\")\n if route.kind == \"longpoll\"\n return null\n trace(\"${requestIdentity(request.id, token)} Invoking handler; middleware=${route.middleware != null}\")\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture crypto\n capture task\n capture claims\n encoded = null\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = signResponse(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n trace(\"${requestIdentity(request.id, token)} Handler completed; serializing response\")\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n encoded = signResponse(updated)\n result = response.result(body)\n result.headers[\"x-lango-token\"] = encoded\n if result.status < 400 and authenticationChanged(claims, updated)\n result.headers[\"x-lango-auth-change\"] = \"v1:${crypto/randomUUID()}\"\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n trace(\"${requestIdentity(request.id, token)} Request completed status=${result.status}\")\n return result\n catch(error)\n capture HttpFailure\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n log.warn(\"${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized\")\n return failure(401, \"Unauthorized\")\n log.err(\"${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n finally\n context clientIdentity\n if clientIdentity != null\n clientIdentity.closed = true\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context request\n context token\n identity = \"[${request.id}]\"\n if token != null\n identity = requestIdentity(request.id, token)\n trace(\"${identity} Running event ${name}\")\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture handler\n capture input\n return handler(input)\n finally\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate(force = false)\n context token\n claims = token.snapshot()\n if !force and Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n return event(\"validate\", null)\n then(valid)\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n logIdentity: requestIdentity(id, token)\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n closeScope(db, true)\n return null\n catch(error)\n closeScope(db, false)\n log.err(\"${requestIdentity(request.id, token)} Request event failed: ${errorDetails(error)}\")\n return null\n then(ignored)\n capture result\n return result\n finally\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n\nneedLogin(route, status, reason)\n context request\n context token\n throw new HttpFailure(status, reason, {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n \"x-lango-need-login\": \"1\"\n }, {\n reason: reason\n path: request.path\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n userId: token.get(\"userId\")\n })\n\nauthenticationChanged(previous, current)\n context clientIdentity\n if clientIdentity != null and clientIdentity.rotate\n return true\n for [\"auth\", \"userId\", \"grantId\", \"authenticatedAt\"] as name\n if to_json(previous[name]) != to_json(current[name])\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHA;;;;;;;;;;;AA8VA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;;;;;;;;;"}
package/dist/server.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { resolvePolicies } from "./policy.mjs";
1
2
  import { trace, responseLog } from "./trace.mjs";
2
3
  import { LongpollBroker } from "./longpoll_broker.mjs";
3
4
  import { LongpollSession } from "./longpoll_session.mjs";
@@ -18,6 +19,7 @@ import {
18
19
  contextGet as __contextGet,
19
20
  contextSet as __contextSet,
20
21
  contextRestore as __contextRestore,
22
+ bindContexts as __bindContexts,
21
23
  fromJson as __fromJson,
22
24
  toJson as __toJson,
23
25
  isNumber as __isNumber,
@@ -72,6 +74,8 @@ export class Server {
72
74
  throw "Use Server(directory) or Builder.build()";
73
75
  }
74
76
  this.#definition = __fromJson(__toJson(definition));
77
+ let settings = __normalize(this.#definition.settings);
78
+ resolvePolicies(__normalize(this.#definition.routes), __normalize(settings.policies));
75
79
  this.#broker = new LongpollBroker(__normalize(this.#definition.settings), __normalize(this.#definition.routes));
76
80
  this.#polls = __normalize(__hostGlobal(["Object"]).create(null));
77
81
  this.#state = "new";
@@ -129,22 +133,22 @@ export class Server {
129
133
  return __normalize(__hostGlobal(["Promise"]).reject(error));
130
134
  }
131
135
  }
132
- return __normalize(this.#broker.open()).then(__withArity((ignored) => {
136
+ return __normalize(this.#broker.open()).then(__withArity(__bindContexts((ignored) => {
133
137
  ignored = __boundary(ignored);
134
- return prepareDatabase(__normalize(settings.database));
138
+ return prepareDatabase(__normalize(settings.database), __normalize(settings.root), __normalize(settings.client));
135
139
  return null;
136
- }, [0], "closure")).then(__withArity((ignored) => {
140
+ }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
137
141
  ignored = __boundary(ignored);
138
142
  let resolver = __normalize(modules.createRequire(__normalize(path.join(__normalize(settings.root), "package.json"))));
139
143
  let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
140
144
  this.#pool = new piscina.Piscina({ filename: __normalize(path.join(__normalize(path.dirname(entry)), "worker.mjs")), name: "execute", minThreads: __normalize(settings.workers), maxThreads: __normalize(settings.workers), maxQueue: __normalize(settings.maxQueue), concurrentTasksPerWorker: 1, closeTimeout: __normalize(settings.shutdownTimeoutMs), workerData: __normalize(this.#definition) });
141
145
  let pool = __normalize(this.#pool);
142
- __normalize(pool.on("message", __withArity((message) => {
146
+ __normalize(pool.on("message", __withArity(__bindContexts((message) => {
143
147
  message = __boundary(message);
144
148
  this.#messageReceived(message);
145
149
  return null;
146
- }, [0], "closure")));
147
- __normalize(pool.on("error", __withArity((error) => {
150
+ }), [0], "closure")));
151
+ __normalize(pool.on("error", __withArity(__bindContexts((error) => {
148
152
  const __contextScope = [];
149
153
  try {
150
154
  error = __boundary(error);
@@ -154,33 +158,33 @@ export class Server {
154
158
  } finally {
155
159
  __contextRestore(__contextScope);
156
160
  }
157
- }, [0], "closure")));
161
+ }), [0], "closure")));
158
162
  return startupDeadline(__normalize(this.#ready.promise), __normalize(settings.startupTimeoutMs));
159
163
  return null;
160
- }, [0], "closure")).then(__withArity((ignored) => {
164
+ }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
161
165
  ignored = __boundary(ignored);
162
166
  if (__requireBoolean(__normalize(this.#state) !== "starting")) {
163
167
  throw "Server closed during startup";
164
168
  }
165
- let server = new http.Server(__withArity((req, res) => {
169
+ let server = new http.Server(__withArity(__bindContexts((req, res) => {
166
170
  req = __boundary(req);
167
171
  res = __boundary(res);
168
172
  this.#receive(req, res);
169
173
  return null;
170
- }, [0, 1], "closure"));
174
+ }), [0, 1], "closure"));
171
175
  this.#server = server;
172
- __normalize(server.on("connection", __withArity((socket) => {
176
+ __normalize(server.on("connection", __withArity(__bindContexts((socket) => {
173
177
  socket = __boundary(socket);
174
178
  this.#connected(socket);
175
179
  return null;
176
- }, [0], "closure")));
180
+ }), [0], "closure")));
177
181
  server.headersTimeout = __normalize(settings.bodyTimeoutMs);
178
182
  server.requestTimeout = __normalize(settings.bodyTimeoutMs);
179
- let listening = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
183
+ let listening = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve, reject) => {
180
184
  resolve = __boundary(resolve);
181
185
  reject = __boundary(reject);
182
186
  __normalize(server.once("error", reject));
183
- __normalize(server.listen(__normalize(settings.port), __normalize(settings.host), () => {
187
+ __normalize(server.listen(__normalize(settings.port), __normalize(settings.host), __bindContexts(() => {
184
188
  __normalize(server.removeListener("error", reject));
185
189
  if (__requireBoolean(__normalize(this.#state) !== "starting")) {
186
190
  __call(reject, "Server closed during startup");
@@ -190,22 +194,22 @@ export class Server {
190
194
  let address = __normalize(server.address());
191
195
  __call(resolve, { host: __normalize(address.address), port: __normalize(address.port) });
192
196
  return null;
193
- }));
197
+ })));
194
198
  return null;
195
- }, [0, 1], "closure"));
199
+ }), [0, 1], "closure"));
196
200
  return listening;
197
201
  return null;
198
- }, [0], "closure")).catch(__withArity((error) => {
202
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
199
203
  error = __boundary(error);
200
204
  __normalize(this.#broker.close());
201
205
  this.#state = "closed";
202
- return this.#destroyPool().then(__withArity((ignored) => {
206
+ return this.#destroyPool().then(__withArity(__bindContexts((ignored) => {
203
207
  ignored = __boundary(ignored);
204
208
  throw error;
205
209
  return null;
206
- }, [0], "closure"));
210
+ }), [0], "closure"));
207
211
  return null;
208
- }, [0], "closure"));
212
+ }), [0], "closure"));
209
213
  return null;
210
214
  }
211
215
  #messageReceived(message) {
@@ -250,10 +254,10 @@ export class Server {
250
254
  if (__requireBoolean(__normalize(record.result) === null)) {
251
255
  duration = __normalize(__hostGlobal(["Math"]).min(duration, __finite(__normalize(record.deadline) - __normalize(__hostGlobal(["Date"]).now()))));
252
256
  }
253
- let expired = () => {
257
+ let expired = __bindContexts(() => {
254
258
  this.#expire(record);
255
259
  return null;
256
- };
260
+ });
257
261
  record.timer = __hostGlobalCall(["setTimeout"], expired, __normalize(__hostGlobal(["Math"]).max(1, duration)));
258
262
  return null;
259
263
  return null;
@@ -263,13 +267,13 @@ export class Server {
263
267
  socket = __boundary(socket);
264
268
  let record = { socket: socket, active: 0 };
265
269
  __add(this.#connections, record);
266
- __normalize(socket.once("close", () => {
270
+ __normalize(socket.once("close", __bindContexts(() => {
267
271
  let index = __normalize(this.#connections.indexOf(record));
268
272
  if (__requireBoolean(index >= 0)) {
269
273
  __normalize(this.#connections.splice(index, 1));
270
274
  }
271
275
  return null;
272
- }));
276
+ })));
273
277
  return null;
274
278
  return null;
275
279
  }
@@ -282,7 +286,7 @@ export class Server {
282
286
  if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
283
287
  record.active = __numericAdd(__normalize(record.active), 1);
284
288
  let state = { done: false };
285
- let complete = () => {
289
+ let complete = __bindContexts(() => {
286
290
  if (__requireBoolean(__normalize(state.done))) {
287
291
  return null;
288
292
  }
@@ -298,7 +302,7 @@ export class Server {
298
302
  }
299
303
  return null;
300
304
  return null;
301
- };
305
+ });
302
306
  __normalize(res.once("finish", complete));
303
307
  __normalize(res.once("close", complete));
304
308
  return null;
@@ -312,22 +316,22 @@ export class Server {
312
316
  req = __boundary(req);
313
317
  res = __boundary(res);
314
318
  this.#trackResponse(req, res);
315
- __normalize(req.on("error", __withArity((error) => {
319
+ __normalize(req.on("error", __withArity(__bindContexts((error) => {
316
320
  error = __boundary(error);
317
321
  return null;
318
322
  return null;
319
- }, [0], "closure")));
323
+ }), [0], "closure")));
320
324
  if (__requireBoolean(__normalize(this.#state) !== "running")) {
321
325
  return rejectHttp(req, res, 503, "Unavailable");
322
326
  }
323
327
  trace(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])}`);
324
328
  if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
325
- let failed = __withArity((status, code) => {
329
+ let failed = __withArity(__bindContexts((status, code) => {
326
330
  status = __boundary(status);
327
331
  code = __boundary(code);
328
332
  this.#send(res, failure(status, code));
329
333
  return null;
330
- }, [0, 1], "closure");
334
+ }), [0, 1], "closure");
331
335
  return __normalize(this.#static.receive(req, res, failed));
332
336
  }
333
337
  if (__requireBoolean(__normalize(req.method) !== "POST")) {
@@ -354,17 +358,17 @@ export class Server {
354
358
  if (__requireBoolean(__requireBoolean(__normalize(this.#active) >= __normalize(settings.workers)) && __requireBoolean(__normalize(this.#waiting.length) >= __normalize(settings.maxQueue)))) {
355
359
  return rejectHttp(req, res, 503, "QueueFull");
356
360
  }
357
- let complete = __withArity((body) => {
361
+ let complete = __withArity(__bindContexts((body) => {
358
362
  body = __boundary(body);
359
363
  this.#submit(req, res, body);
360
364
  return null;
361
- }, [0], "closure");
362
- let failed = __withArity((status, code) => {
365
+ }), [0], "closure");
366
+ let failed = __withArity(__bindContexts((status, code) => {
363
367
  status = __boundary(status);
364
368
  code = __boundary(code);
365
369
  this.#send(res, failure(status, code));
366
370
  return null;
367
- }, [0, 1], "closure");
371
+ }), [0, 1], "closure");
368
372
  let reader = new BodyReader(req, res, settings, complete, failed);
369
373
  __normalize(reader.start());
370
374
  return null;
@@ -382,12 +386,12 @@ export class Server {
382
386
  } else {
383
387
  pending = this.#longpoll(req, res, body, route);
384
388
  }
385
- return pending.then(__withArity((result) => {
389
+ return pending.then(__withArity(__bindContexts((result) => {
386
390
  result = __boundary(result);
387
391
  this.#send(res, result);
388
392
  return null;
389
393
  return null;
390
- }, [0], "closure")).catch(__withArity((error) => {
394
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
391
395
  const __contextScope = [];
392
396
  try {
393
397
  error = __boundary(error);
@@ -398,7 +402,7 @@ export class Server {
398
402
  } finally {
399
403
  __contextRestore(__contextScope);
400
404
  }
401
- }, [0], "closure"));
405
+ }), [0], "closure"));
402
406
  return null;
403
407
  }
404
408
  #longpoll(req, res, body, route) {
@@ -410,25 +414,25 @@ export class Server {
410
414
  if (__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#polls))).length) >= __normalize(this.#definition.settings.redis.maxPendingPolls))) {
411
415
  return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "PollLimit")));
412
416
  }
413
- let authorize = __withArity((token, result) => {
417
+ let authorize = __withArity(__bindContexts((token, result) => {
414
418
  token = __boundary(token);
415
419
  result = __boundary(result);
416
420
  return this.#dispatch(req, res, body, true, token, result);
417
421
  return null;
418
- }, [0, 1], "closure");
422
+ }), [0, 1], "closure");
419
423
  let session = new LongpollSession(__normalize(this.#broker), route, authorize, body);
420
424
  let id = __normalize(crypto.randomUUID());
421
425
  this.#polls[id] = session;
422
- let disconnected = () => {
426
+ let disconnected = __bindContexts(() => {
423
427
  __normalize(session.cancel());
424
428
  return null;
425
- };
429
+ });
426
430
  __normalize(res.once("close", disconnected));
427
- return __normalize(session.run()).finally(() => {
431
+ return __normalize(session.run()).finally(__bindContexts(() => {
428
432
  __normalize(res.removeListener("close", disconnected));
429
433
  __normalize(__hostGlobal(["Reflect"]).deleteProperty(__normalize(this.#polls), id));
430
434
  return null;
431
- });
435
+ }));
432
436
  return null;
433
437
  }
434
438
  #brokerMessage(message) {
@@ -447,18 +451,18 @@ export class Server {
447
451
  } catch (error) {
448
452
  pending = __normalize(__hostGlobal(["Promise"]).reject(error));
449
453
  }
450
- return pending.then(__withArity((value) => {
454
+ return pending.then(__withArity(__bindContexts((value) => {
451
455
  value = __boundary(value);
452
456
  brokerReply(port, { ok: true, value: value });
453
457
  return null;
454
- }, [0], "closure")).catch(__withArity((error) => {
458
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
455
459
  error = __boundary(error);
456
460
  brokerReply(port, { ok: false });
457
461
  return null;
458
- }, [0], "closure")).finally(() => {
462
+ }), [0], "closure")).finally(__bindContexts(() => {
459
463
  __normalize(port.close());
460
464
  return null;
461
- });
465
+ }));
462
466
  return null;
463
467
  }
464
468
  #dispatch(req, res, body, authorize = false, token = null, pollResult = null) {
@@ -483,25 +487,25 @@ export class Server {
483
487
  this.#tasks[id] = record;
484
488
  this.#resetDeadline(record, __normalize(settings.requestTimeoutMs));
485
489
  __add(this.#waiting, record);
486
- let disconnected = () => {
490
+ let disconnected = __bindContexts(() => {
487
491
  if (__requireBoolean(!__requireBoolean(__normalize(res.writableEnded)))) {
488
492
  this.#cancel(record);
489
493
  }
490
494
  return null;
491
- };
495
+ });
492
496
  __normalize(res.once("close", disconnected));
493
497
  this.#pump();
494
- return record.completed.promise.catch(__withArity((error) => {
498
+ return record.completed.promise.catch(__withArity(__bindContexts((error) => {
495
499
  error = __boundary(error);
496
500
  if (__requireBoolean(__normalize(record.expired))) {
497
501
  return failure(504, "RequestTimeout");
498
502
  }
499
503
  return failure(500, "InternalServerError");
500
504
  return null;
501
- }, [0], "closure")).finally(() => {
505
+ }), [0], "closure")).finally(__bindContexts(() => {
502
506
  __normalize(res.removeListener("close", disconnected));
503
507
  return null;
504
- });
508
+ }));
505
509
  return null;
506
510
  }
507
511
  #expire(record) {
@@ -546,12 +550,12 @@ export class Server {
546
550
  __requireArity(arguments.length, [0, 1], "settle");
547
551
  record = __boundary(record);
548
552
  pending = __boundary(pending);
549
- return pending.then(__withArity((result) => {
553
+ return pending.then(__withArity(__bindContexts((result) => {
550
554
  result = __boundary(result);
551
555
  this.#finish(record, result, null);
552
556
  return null;
553
557
  return null;
554
- }, [0], "closure")).catch(__withArity((error) => {
558
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
555
559
  const __contextScope = [];
556
560
  try {
557
561
  error = __boundary(error);
@@ -564,11 +568,11 @@ export class Server {
564
568
  } finally {
565
569
  __contextRestore(__contextScope);
566
570
  }
567
- }, [0], "closure")).finally(() => {
571
+ }), [0], "closure")).finally(__bindContexts(() => {
568
572
  this.#active = __finite(__normalize(this.#active) - 1);
569
573
  this.#pump();
570
574
  return null;
571
- });
575
+ }));
572
576
  return null;
573
577
  }
574
578
  #finish(record, result, error) {
@@ -612,21 +616,21 @@ export class Server {
612
616
  for (const [id, session] of __entries(__normalize(this.#polls))) {
613
617
  __normalize(session.cancel());
614
618
  }
615
- let drained = new (__hostGlobal(["Promise"]))(__withArity((resolve) => {
619
+ let drained = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve) => {
616
620
  resolve = __boundary(resolve);
617
621
  let server = __normalize(this.#server);
618
622
  if (__requireBoolean(__requireBoolean(server === null) || __requireBoolean(!__requireBoolean(__normalize(server.listening))))) {
619
623
  __call(resolve, null);
620
624
  } else {
621
- server.close(() => {
625
+ server.close(__bindContexts(() => {
622
626
  __call(resolve, null);
623
627
  return null;
624
- });
628
+ }));
625
629
  }
626
630
  return null;
627
- }, [0], "closure"));
631
+ }), [0], "closure"));
628
632
  let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
629
- let force = () => {
633
+ let force = __bindContexts(() => {
630
634
  this.#destroying = true;
631
635
  for (const record of __normalize(this.#waiting)) {
632
636
  this.#finish(record, null, "Server closed");
@@ -637,17 +641,17 @@ export class Server {
637
641
  }
638
642
  __normalize(expired.reject("Server shutdown timed out"));
639
643
  return null;
640
- };
644
+ });
641
645
  let timer = __hostGlobalCall(["setTimeout"], force, __normalize(this.#definition.settings.shutdownTimeoutMs));
642
- return __normalize(__hostGlobal(["Promise"]).race([drained, __normalize(expired.promise)])).finally(() => {
646
+ return __normalize(__hostGlobal(["Promise"]).race([drained, __normalize(expired.promise)])).finally(__bindContexts(() => {
643
647
  __hostGlobalCall(["clearTimeout"], timer);
644
648
  return this.#destroyPool();
645
649
  return null;
646
- }).finally(() => {
650
+ })).finally(__bindContexts(() => {
647
651
  __normalize(this.#broker.close());
648
652
  this.#state = "closed";
649
653
  return null;
650
- });
654
+ }));
651
655
  return null;
652
656
  }
653
657
  #destroyPool() {
@@ -667,10 +671,10 @@ export class Server {
667
671
  pending = startupDeadline(__normalize(__hostGlobal(["Promise"]).all(tasks)), remaining);
668
672
  }
669
673
  }
670
- return pending.finally(() => {
674
+ return pending.finally(__bindContexts(() => {
671
675
  return __normalize(pool.destroy());
672
676
  return null;
673
- });
677
+ }));
674
678
  return null;
675
679
  }
676
680
  #send(res, result) {
@@ -698,15 +702,15 @@ function startupDeadline(pending, timeout) {
698
702
  pending = __boundary(pending);
699
703
  timeout = __boundary(timeout);
700
704
  let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
701
- let expire = () => {
705
+ let expire = __bindContexts(() => {
702
706
  __normalize(expired.reject("Worker startup timed out"));
703
707
  return null;
704
- };
708
+ });
705
709
  let timer = __hostGlobalCall(["setTimeout"], expire, timeout);
706
- return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
710
+ return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(__bindContexts(() => {
707
711
  __hostGlobalCall(["clearTimeout"], timer);
708
712
  return null;
709
- });
713
+ }));
710
714
  return null;
711
715
  }
712
716
 
@@ -748,10 +752,10 @@ function rejectHttp(req, res, status, code) {
748
752
  status = __boundary(status);
749
753
  code = __boundary(code);
750
754
  __normalize(res.setHeader("Connection", "close"));
751
- __normalize(res.once("finish", () => {
755
+ __normalize(res.once("finish", __bindContexts(() => {
752
756
  __normalize(req.destroy());
753
757
  return null;
754
- }));
758
+ })));
755
759
  __normalize(req.resume());
756
760
  return write(res, failure(status, code));
757
761
  return null;
@@ -780,8 +784,8 @@ export function main(args) {
780
784
  }
781
785
  trace(`Loading server configuration: ${directory}`);
782
786
  let server = new Server(directory);
783
- let stop = () => {
784
- return __normalize(server.close()).catch(__withArity((error) => {
787
+ let stop = __bindContexts(() => {
788
+ return __normalize(server.close()).catch(__withArity(__bindContexts((error) => {
785
789
  const __contextScope = [];
786
790
  try {
787
791
  error = __boundary(error);
@@ -791,12 +795,12 @@ export function main(args) {
791
795
  } finally {
792
796
  __contextRestore(__contextScope);
793
797
  }
794
- }, [0], "closure"));
798
+ }), [0], "closure"));
795
799
  return null;
796
- };
800
+ });
797
801
  __normalize(__hostGlobal(["process"]).once("SIGTERM", stop));
798
802
  __normalize(__hostGlobal(["process"]).once("SIGINT", stop));
799
- return __normalize(server.start()).then(__withArity((address) => {
803
+ return __normalize(server.start()).then(__withArity(__bindContexts((address) => {
800
804
  const __contextScope = [];
801
805
  try {
802
806
  address = __boundary(address);
@@ -806,13 +810,13 @@ export function main(args) {
806
810
  } finally {
807
811
  __contextRestore(__contextScope);
808
812
  }
809
- }, [0], "closure")).catch(__withArity((error) => {
813
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
810
814
  error = __boundary(error);
811
815
  __normalize(__hostGlobal(["process"]).removeListener("SIGTERM", stop));
812
816
  __normalize(__hostGlobal(["process"]).removeListener("SIGINT", stop));
813
817
  throw error;
814
818
  return null;
815
- }, [0], "closure"));
819
+ }), [0], "closure"));
816
820
  return null;
817
821
  }
818
822