@lango-project/lango-server 0.2.4 → 0.2.6
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/README.md +23 -5
- package/dist/body_reader.mjs.map +1 -1
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/server.mjs +3 -838
- package/dist/cli/server.mjs.map +1 -1
- package/dist/client_identity.mjs.map +1 -1
- package/dist/database.mjs.map +1 -1
- package/dist/database_action.mjs.map +1 -1
- package/dist/database_options.mjs.map +1 -1
- package/dist/database_scope.mjs.map +1 -1
- package/dist/endpoint.mjs.map +1 -1
- package/dist/error_details.mjs.map +1 -1
- package/dist/execution_failure.mjs.map +1 -1
- package/dist/execution_identity.mjs.map +1 -1
- package/dist/execution_log.mjs.map +1 -1
- package/dist/execution_runtime.mjs.map +1 -1
- package/dist/execution_worker.mjs.map +1 -1
- package/dist/executor.mjs.map +1 -1
- package/dist/group.mjs.map +1 -1
- package/dist/http_failure.mjs.map +1 -1
- package/dist/job_configuration.mjs.map +1 -1
- package/dist/job_context.mjs.map +1 -1
- package/dist/library.mjs.map +1 -1
- package/dist/longpoll_broker.mjs.map +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/longpoll_session.mjs.map +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/module_loader.mjs.map +1 -1
- package/dist/options.mjs.map +1 -1
- package/dist/origin.mjs.map +1 -1
- package/dist/policy.mjs.map +1 -1
- package/dist/postgres_adapter.mjs.map +1 -1
- package/dist/postgres_worker.mjs.map +1 -1
- package/dist/queue_provider.mjs.map +1 -1
- package/dist/request_identity.mjs.map +1 -1
- package/dist/response.mjs +1 -1
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +5 -1
- package/dist/route_info.mjs.map +1 -1
- package/dist/route_pattern.mjs.map +1 -1
- package/dist/routes.mjs +27 -4
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +66 -11
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +2 -1
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs.map +1 -1
- package/dist/sqlite_adapter.mjs.map +1 -1
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +4 -1
- package/dist/tokens.mjs.map +1 -1
- package/dist/trace.mjs +6 -1
- package/dist/trace.mjs.map +1 -1
- package/dist/worker.mjs.map +1 -1
- package/docs/browser-sessions.md +96 -0
- package/examples/security/package.json +1 -1
- package/package.json +8 -5
- package/src/response.lango +1 -1
- package/src/route_info.lango +5 -2
- package/src/routes.lango +20 -3
- package/src/runtime.lango +56 -11
- package/src/server.lango +3 -2
- package/src/tokens.lango +4 -0
- package/src/trace.lango +5 -2
- package/dist/cli/.lango/bignumber.mjs +0 -3119
- package/dist/cli/.lango/localization.mjs +0 -108
- package/dist/cli/.lango/runtime.mjs +0 -725
- package/dist/cli/.lango/vendor/i18next.LICENSE +0 -21
- package/dist/cli/.lango/vendor/i18next.mjs +0 -2434
- package/dist/cli/.lango/xmldom/conventions.js +0 -429
- package/dist/cli/.lango/xmldom/dom-parser.js +0 -591
- package/dist/cli/.lango/xmldom/dom.js +0 -3759
- package/dist/cli/.lango/xmldom/entities.js +0 -2171
- package/dist/cli/.lango/xmldom/errors.js +0 -205
- package/dist/cli/.lango/xmldom/grammar.js +0 -559
- package/dist/cli/.lango/xmldom/index.js +0 -41
- package/dist/cli/.lango/xmldom/package.json +0 -1
- package/dist/cli/.lango/xmldom/sax.js +0 -983
- package/dist/cli/.lango/xmldom.LICENSE.md +0 -8
- package/dist/cli/body_reader.mjs +0 -180
- package/dist/cli/body_reader.mjs.map +0 -1
- package/dist/cli/client_identity.mjs +0 -250
- package/dist/cli/client_identity.mjs.map +0 -1
- package/dist/cli/database.mjs +0 -116
- package/dist/cli/database.mjs.map +0 -1
- package/dist/cli/database_options.mjs +0 -83
- package/dist/cli/database_options.mjs.map +0 -1
- package/dist/cli/database_scope.mjs +0 -93
- package/dist/cli/database_scope.mjs.map +0 -1
- package/dist/cli/endpoint.mjs +0 -50
- package/dist/cli/endpoint.mjs.map +0 -1
- package/dist/cli/error_details.mjs +0 -45
- package/dist/cli/error_details.mjs.map +0 -1
- package/dist/cli/longpoll_broker.mjs +0 -215
- package/dist/cli/longpoll_broker.mjs.map +0 -1
- package/dist/cli/longpoll_options.mjs +0 -103
- package/dist/cli/longpoll_options.mjs.map +0 -1
- package/dist/cli/longpoll_session.mjs +0 -136
- package/dist/cli/longpoll_session.mjs.map +0 -1
- package/dist/cli/middleware.mjs +0 -25
- package/dist/cli/middleware.mjs.map +0 -1
- package/dist/cli/options.mjs +0 -214
- package/dist/cli/options.mjs.map +0 -1
- package/dist/cli/origin.mjs +0 -87
- package/dist/cli/origin.mjs.map +0 -1
- package/dist/cli/policy.mjs +0 -121
- package/dist/cli/policy.mjs.map +0 -1
- package/dist/cli/postgres_adapter.mjs +0 -178
- package/dist/cli/postgres_adapter.mjs.map +0 -1
- package/dist/cli/route_pattern.mjs +0 -129
- package/dist/cli/route_pattern.mjs.map +0 -1
- package/dist/cli/routes.mjs +0 -360
- package/dist/cli/routes.mjs.map +0 -1
- package/dist/cli/sqlite_adapter.mjs +0 -163
- package/dist/cli/sqlite_adapter.mjs.map +0 -1
- package/dist/cli/static_files.mjs +0 -224
- package/dist/cli/static_files.mjs.map +0 -1
- package/dist/cli/trace.mjs +0 -53
- package/dist/cli/trace.mjs.map +0 -1
package/dist/policy.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy.mjs","sources":["policy.lango"],"sourcesContent":["import js global Number\nimport js global Object\n\nexport policyOptions(spec)\nexport policyRegistry(spec)\nexport resolvePolicies(routes, registry)\n\npolicyOptions(spec)\n name = spec.policy\n if name != null and spec.auth != null and name != spec.auth\n throw \"Endpoint policy and legacy auth cannot disagree\"\n legacy = name == null\n if name == null\n name = spec.auth\n if name == null\n name = \"login\"\n if !is_string(name) or name.trim() == \"\" or name.includes(\",\")\n throw \"Endpoint policy must name one permission\"\n seconds = spec.reauthSeconds\n if seconds == null\n seconds = 0\n if is_string(seconds)\n if seconds.trim() == \"\"\n throw \"reauthSeconds cannot be empty\"\n seconds = Number(seconds)\n if !Number/isSafeInteger(seconds) or seconds < 0 or seconds > 31536000\n throw \"reauthSeconds must be an integer between 0 and 31536000\"\n if seconds > 0 and name == \"anonymous\"\n throw \"Anonymous policy cannot require password freshness\"\n return {\n name: name\n reauthSeconds: seconds\n explicit: spec.reauthSeconds != null\n legacy: legacy\n }\n\npolicyRegistry(spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Policies must be a map\"\n for spec as key: value\n if key != \"reauthSeconds\" and key != \"items\"\n throw \"Unknown policies option: ${key}\"\n base = policyOptions({\n policy: \"login\"\n reauthSeconds: spec.reauthSeconds\n })\n items = spec.items\n if !is_array(items)\n throw \"Policies require an items array\"\n result = Object/create(null)\n for items as item\n if !is_object(item) or is_array(item)\n throw \"Policy must be a map\"\n for item as key: value\n if key != \"name\" and key != \"reauthSeconds\"\n throw \"Unknown policy option: ${key}\"\n name = item.name\n if !is_string(name) or name.trim() != name or name == \"\" or name == \"anonymous\" or Object/hasOwn(result, name)\n throw \"Invalid or duplicate policy name\"\n seconds = item.reauthSeconds\n if seconds == null\n seconds = base.reauthSeconds\n selected = policyOptions({\n policy: name\n reauthSeconds: seconds\n })\n result[name] = selected.reauthSeconds\n return result\n\nresolvePolicies(routes, registry)\n if registry == null\n return routes\n for routes as route\n if route.policy != \"anonymous\"\n if !Object/hasOwn(registry, route.policy)\n throw \"Undefined route policy: ${route.policy}\"\n maximum = registry[route.policy]\n if route.reauthExplicit and maximum > 0 and (route.reauthSeconds == 0 or route.reauthSeconds > maximum)\n throw \"Route cannot weaken policy freshness: ${route.path}\"\n if !route.reauthExplicit\n route.reauthSeconds = maximum\n return routes\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"policy.mjs","sources":["policy.lango"],"sourcesContent":["import js global Number\nimport js global Object\n\nexport policyOptions(spec)\nexport policyRegistry(spec)\nexport resolvePolicies(routes, registry)\n\npolicyOptions(spec)\n name = spec.policy\n if name != null and spec.auth != null and name != spec.auth\n throw \"Endpoint policy and legacy auth cannot disagree\"\n legacy = name == null\n if name == null\n name = spec.auth\n if name == null\n name = \"login\"\n if !is_string(name) or name.trim() == \"\" or name.includes(\",\")\n throw \"Endpoint policy must name one permission\"\n seconds = spec.reauthSeconds\n if seconds == null\n seconds = 0\n if is_string(seconds)\n if seconds.trim() == \"\"\n throw \"reauthSeconds cannot be empty\"\n seconds = Number(seconds)\n if !Number/isSafeInteger(seconds) or seconds < 0 or seconds > 31536000\n throw \"reauthSeconds must be an integer between 0 and 31536000\"\n if seconds > 0 and name == \"anonymous\"\n throw \"Anonymous policy cannot require password freshness\"\n return {\n name: name\n reauthSeconds: seconds\n explicit: spec.reauthSeconds != null\n legacy: legacy\n }\n\npolicyRegistry(spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Policies must be a map\"\n for spec as key: value\n if key != \"reauthSeconds\" and key != \"items\"\n throw \"Unknown policies option: ${key}\"\n base = policyOptions({\n policy: \"login\"\n reauthSeconds: spec.reauthSeconds\n })\n items = spec.items\n if !is_array(items)\n throw \"Policies require an items array\"\n result = Object/create(null)\n for items as item\n if !is_object(item) or is_array(item)\n throw \"Policy must be a map\"\n for item as key: value\n if key != \"name\" and key != \"reauthSeconds\"\n throw \"Unknown policy option: ${key}\"\n name = item.name\n if !is_string(name) or name.trim() != name or name == \"\" or name == \"anonymous\" or Object/hasOwn(result, name)\n throw \"Invalid or duplicate policy name\"\n seconds = item.reauthSeconds\n if seconds == null\n seconds = base.reauthSeconds\n selected = policyOptions({\n policy: name\n reauthSeconds: seconds\n })\n result[name] = selected.reauthSeconds\n return result\n\nresolvePolicies(routes, registry)\n if registry == null\n return routes\n for routes as route\n if route.policy != \"anonymous\"\n if !Object/hasOwn(registry, route.policy)\n throw \"Undefined route policy: ${route.policy}\"\n maximum = registry[route.policy]\n if route.reauthExplicit and maximum > 0 and (route.reauthSeconds == 0 or route.reauthSeconds > maximum)\n throw \"Route cannot weaken policy freshness: ${route.path}\"\n if !route.reauthExplicit\n route.reauthSeconds = maximum\n return routes\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"6cf55d96fa8144aaed1279736180375ef1213ca80d4f6a2dbe54666933b5f873","outputHash":"10836d87b0d6389cb8d4effc1e439d85e66d25b09ab64c706d220d46b686dcb7","mapHash":"0a47dafc050fd955a0095a89560a643d9d8b5e9200b1cd6af11ee4fdcb96b415"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres_adapter.mjs","sources":["postgres_adapter.lango"],"sourcesContent":["import js \"node:module\" as modules\nimport js \"node:path\" as path\nimport js \"node:worker_threads\" as threads\nimport js global Reflect\nimport js global SharedArrayBuffer\nimport js global Int32Array\nimport js global Atomics\nimport js global Math\nimport js global Error\n\nexport class PostgresAdapter(mod, settings, root)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n invoke(spec, input)\n begin()\n commit()\n rollback()\n transactionState()\n close()\n\nPostgresAdapter(mod, settings, root)\n @closed = false\n @broken = false\n @state = null\n @depth = 0\n @rollbackOnly = false\n @parameterStyle = \"postgresql\"\n @timeout = Math/min(2147483647, settings.queryTimeoutMs + 1000)\n @signal = new Int32Array(new SharedArrayBuffer(4))\n channel = Reflect/construct(mod.MessageChannel, [])\n @port = channel.port1\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @worker = Reflect/construct(mod.Worker, [path/join(path/dirname(entry), \"postgres_worker.mjs\"), {\n workerData: {\n root: root\n settings: settings\n port: channel.port2\n signal: @signal\n }\n transferList: [channel.port2]\n }])\n worker = @worker\n worker.on(\"error\", (error)\n @broken = true\n )\n @worker.unref()\n @port.unref()\n try\n exchange({\n action: \"connect\"\n }, Math/min(2147483647, settings.connectTimeoutSeconds * 1000 + 1000))\n catch error\n close()\n throw new Error(\"PostgreSQL initialization failed\")\n\nPostgresAdapter:exchange(task, timeout)\n if @closed or @broken\n throw new Error(\"PostgreSQL connection is unavailable\")\n Atomics/store(@signal, 0, 0)\n @port.postMessage(task)\n waited = Atomics/wait(@signal, 0, 0, timeout)\n if waited == \"timed-out\"\n @broken = true\n @worker.terminate()\n throw new Error(\"PostgreSQL operation timed out\")\n reply = threads/receiveMessageOnPort(@port)\n if reply == null\n @broken = true\n throw new Error(\"PostgreSQL response was not received\")\n result = reply.message\n @state = result.state\n if result.failed\n @broken = result.dead\n error = new Error(\"PostgreSQL query failed\")\n if result.detail != null\n error = new Error(\"PostgreSQL extension failed: ${result.detail}\")\n error.code = result.code\n error.position = result.position\n error.transactionUnusable = @state == \"failed\"\n throw error\n return result\n\nPostgresAdapter:execute(sql, parameters)\n return exchange({\n action: \"query\"\n sql: sql\n parameters: parameters\n }, @timeout)\n\nPostgresAdapter:invoke(spec, input)\n result = exchange({\n action: \"invoke\"\n spec: spec\n input: input\n }, @timeout)\n return result.value\n\nPostgresAdapter:begin()\n if @depth == 0 and @state == null\n execute(\"BEGIN\", [])\n @depth = @depth + 1\n return null\n\nPostgresAdapter:commit()\n if @depth == 0\n throw new Error(\"NoActiveTransaction\")\n if @depth > 1\n @depth = @depth - 1\n return null\n if @rollbackOnly or @state == \"failed\"\n rollback()\n throw new Error(\"TransactionRolledBack\")\n execute(\"COMMIT\", [])\n @depth = 0\n return null\n\nPostgresAdapter:rollback()\n if @depth > 1\n @depth = @depth - 1\n @rollbackOnly = true\n return null\n if @state != null\n execute(\"ROLLBACK\", [])\n @depth = 0\n @rollbackOnly = false\n return null\n\nPostgresAdapter:transactionState()\n if @broken\n throw new Error(\"PostgreSQL connection is unavailable\")\n if @rollbackOnly and @state != \"failed\"\n return \"rollback_only\"\n return @state\n\nPostgresAdapter:close()\n if @closed\n return null\n try\n if !@broken\n exchange({\n action: \"close\"\n }, @timeout)\n finally\n @closed = true\n @port.close()\n @worker.terminate()\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"postgres_adapter.mjs","sources":["postgres_adapter.lango"],"sourcesContent":["import js \"node:module\" as modules\nimport js \"node:path\" as path\nimport js \"node:worker_threads\" as threads\nimport js global Reflect\nimport js global SharedArrayBuffer\nimport js global Int32Array\nimport js global Atomics\nimport js global Math\nimport js global Error\n\nexport class PostgresAdapter(mod, settings, root)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n invoke(spec, input)\n begin()\n commit()\n rollback()\n transactionState()\n close()\n\nPostgresAdapter(mod, settings, root)\n @closed = false\n @broken = false\n @state = null\n @depth = 0\n @rollbackOnly = false\n @parameterStyle = \"postgresql\"\n @timeout = Math/min(2147483647, settings.queryTimeoutMs + 1000)\n @signal = new Int32Array(new SharedArrayBuffer(4))\n channel = Reflect/construct(mod.MessageChannel, [])\n @port = channel.port1\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @worker = Reflect/construct(mod.Worker, [path/join(path/dirname(entry), \"postgres_worker.mjs\"), {\n workerData: {\n root: root\n settings: settings\n port: channel.port2\n signal: @signal\n }\n transferList: [channel.port2]\n }])\n worker = @worker\n worker.on(\"error\", (error)\n @broken = true\n )\n @worker.unref()\n @port.unref()\n try\n exchange({\n action: \"connect\"\n }, Math/min(2147483647, settings.connectTimeoutSeconds * 1000 + 1000))\n catch error\n close()\n throw new Error(\"PostgreSQL initialization failed\")\n\nPostgresAdapter:exchange(task, timeout)\n if @closed or @broken\n throw new Error(\"PostgreSQL connection is unavailable\")\n Atomics/store(@signal, 0, 0)\n @port.postMessage(task)\n waited = Atomics/wait(@signal, 0, 0, timeout)\n if waited == \"timed-out\"\n @broken = true\n @worker.terminate()\n throw new Error(\"PostgreSQL operation timed out\")\n reply = threads/receiveMessageOnPort(@port)\n if reply == null\n @broken = true\n throw new Error(\"PostgreSQL response was not received\")\n result = reply.message\n @state = result.state\n if result.failed\n @broken = result.dead\n error = new Error(\"PostgreSQL query failed\")\n if result.detail != null\n error = new Error(\"PostgreSQL extension failed: ${result.detail}\")\n error.code = result.code\n error.position = result.position\n error.transactionUnusable = @state == \"failed\"\n throw error\n return result\n\nPostgresAdapter:execute(sql, parameters)\n return exchange({\n action: \"query\"\n sql: sql\n parameters: parameters\n }, @timeout)\n\nPostgresAdapter:invoke(spec, input)\n result = exchange({\n action: \"invoke\"\n spec: spec\n input: input\n }, @timeout)\n return result.value\n\nPostgresAdapter:begin()\n if @depth == 0 and @state == null\n execute(\"BEGIN\", [])\n @depth = @depth + 1\n return null\n\nPostgresAdapter:commit()\n if @depth == 0\n throw new Error(\"NoActiveTransaction\")\n if @depth > 1\n @depth = @depth - 1\n return null\n if @rollbackOnly or @state == \"failed\"\n rollback()\n throw new Error(\"TransactionRolledBack\")\n execute(\"COMMIT\", [])\n @depth = 0\n return null\n\nPostgresAdapter:rollback()\n if @depth > 1\n @depth = @depth - 1\n @rollbackOnly = true\n return null\n if @state != null\n execute(\"ROLLBACK\", [])\n @depth = 0\n @rollbackOnly = false\n return null\n\nPostgresAdapter:transactionState()\n if @broken\n throw new Error(\"PostgreSQL connection is unavailable\")\n if @rollbackOnly and @state != \"failed\"\n return \"rollback_only\"\n return @state\n\nPostgresAdapter:close()\n if @closed\n return null\n try\n if !@broken\n exchange({\n action: \"close\"\n }, @timeout)\n finally\n @closed = true\n @port.close()\n @worker.terminate()\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"2d01956e1fbe9daa54e87b965f7f7a107bfd699e664ed0a70dc37a01fc279aff","outputHash":"b09d20882063933ef7c2fe9c84ecbddaba667f2b290551ea489cc588ec731ca1","mapHash":"a6981427630d0e695e4500f08fa0449adf7c4e399e4ef4c19972be3854970c12"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres_worker.mjs","sources":["postgres_worker.lango"],"sourcesContent":["import js \"pg\" as pg\nimport js \"node:worker_threads\" as threads\nimport js \"node:module\" as modules\nimport js \"node:path\" as path\nimport \"./module_loader\"\n class ModuleLoader\nimport \"./error_details\"\n errorDetails(error)\nimport js global Atomics\nimport js global Math\nimport js global Number\nimport js global Promise\n\n\nglobal state = initialState()\nglobal loader = new ModuleLoader()\nglobal installed = install()\n\ninstall()\n port = threads.workerData.port\n port.on(\"message\", (task)\n return chain Promise/resolve(null)\n then(ignored)\n capture task\n return execute(task)\n then(result)\n reply(result)\n return null\n catch(error)\n capture task\n global state\n sqlError = is_string(error.code) and error.code.length == 5\n if state.transaction != null and (task.action != \"invoke\" or sqlError or state.dead)\n state.transaction = \"failed\"\n if task.action != \"invoke\" and !sqlError\n state.dead = true\n if sqlError and error.code.startsWith(\"08\")\n state.dead = true\n position = null\n detail = null\n if task.action == \"invoke\" and !sqlError\n detail = errorDetails(error)\n if error.position != null\n position = Number/parseInt(error.position, 10)\n reply({\n failed: true\n dead: state.dead\n code: error.code\n position: position\n detail: detail\n state: state.transaction\n })\n return null\n )\n return null\n\nexecute(task)\n global state\n settings = threads.workerData.settings\n switch task.action\n case \"connect\"\n state.client = new pg/Client({\n connectionString: settings.connection\n connectionTimeoutMillis: Math/min(2147483647, settings.connectTimeoutSeconds * 1000)\n statement_timeout: settings.queryTimeoutMs\n application_name: \"lango-server\"\n })\n client = state.client\n client.on(\"error\", (error)\n global state\n state.dead = true\n )\n return chain client.connect()\n then(ignored)\n return success([], null)\n case \"query\"\n return chain state.client.query({\n text: task.sql\n values: task.parameters\n queryMode: \"extended\"\n })\n then(result)\n global state\n switch result.command\n case \"BEGIN\"\n state.transaction = \"active\"\n case \"COMMIT\"\n case \"ROLLBACK\"\n state.transaction = null\n changes = null\n switch result.command\n case \"INSERT\"\n case \"UPDATE\"\n case \"DELETE\"\n case \"MERGE\"\n changes = result.rowCount\n return success(result.rows, changes)\n case \"invoke\"\n return invoke(task)\n case \"close\"\n return chain state.client.end()\n then(ignored)\n return success([], null)\n else\n throw \"Unknown PostgreSQL operation\"\n\ninvoke(task)\n global state\n global loader\n spec = task.spec\n if spec == null or !is_string(spec.module) or spec.module.startsWith(\"node:\") or !is_string(spec.handler)\n throw \"Database extension requires an application module and exported handler\"\n resolver = modules/createRequire(path/join(threads.workerData.root, \"package.json\"))\n file = resolver.resolve(spec.module)\n if !path/isAbsolute(file)\n throw \"Database extension must resolve to an application file\"\n return chain loader.target({\n module: file\n handler: spec.handler\n })\n then(handler)\n capture task\n global state\n client = state.client\n executeSql = (sql, parameters)\n capture client\n return chain client.query(sql, parameters)\n catch(error)\n global state\n if state.transaction != null\n state.transaction = \"failed\"\n throw error\n adapter = {\n executeSql: executeSql\n }\n return handler(adapter, task.input)\n then(value)\n return success([], null, value)\n\nsuccess(rows, changes, value = null)\n global state\n return {\n failed: false\n dead: false\n state: state.transaction\n rows: rows\n changes: changes\n lastInsertRowid: null\n value: value\n }\n\nreply(result)\n port = threads.workerData.port\n signal = threads.workerData.signal\n port.postMessage(result)\n Atomics/store(signal, 0, 1)\n Atomics/notify(signal, 0)\n return null\n\ninitialState()\n return {\n client: null\n transaction: null\n dead: false\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA;;AACA;;AACA;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA;;;;;;;;;AAYA;;;;;;;;;;;;AAQA;;;;;"}
|
|
1
|
+
{"version":3,"file":"postgres_worker.mjs","sources":["postgres_worker.lango"],"sourcesContent":["import js \"pg\" as pg\nimport js \"node:worker_threads\" as threads\nimport js \"node:module\" as modules\nimport js \"node:path\" as path\nimport \"./module_loader\"\n class ModuleLoader\nimport \"./error_details\"\n errorDetails(error)\nimport js global Atomics\nimport js global Math\nimport js global Number\nimport js global Promise\n\n\nglobal state = initialState()\nglobal loader = new ModuleLoader()\nglobal installed = install()\n\ninstall()\n port = threads.workerData.port\n port.on(\"message\", (task)\n return chain Promise/resolve(null)\n then(ignored)\n capture task\n return execute(task)\n then(result)\n reply(result)\n return null\n catch(error)\n capture task\n global state\n sqlError = is_string(error.code) and error.code.length == 5\n if state.transaction != null and (task.action != \"invoke\" or sqlError or state.dead)\n state.transaction = \"failed\"\n if task.action != \"invoke\" and !sqlError\n state.dead = true\n if sqlError and error.code.startsWith(\"08\")\n state.dead = true\n position = null\n detail = null\n if task.action == \"invoke\" and !sqlError\n detail = errorDetails(error)\n if error.position != null\n position = Number/parseInt(error.position, 10)\n reply({\n failed: true\n dead: state.dead\n code: error.code\n position: position\n detail: detail\n state: state.transaction\n })\n return null\n )\n return null\n\nexecute(task)\n global state\n settings = threads.workerData.settings\n switch task.action\n case \"connect\"\n state.client = new pg/Client({\n connectionString: settings.connection\n connectionTimeoutMillis: Math/min(2147483647, settings.connectTimeoutSeconds * 1000)\n statement_timeout: settings.queryTimeoutMs\n application_name: \"lango-server\"\n })\n client = state.client\n client.on(\"error\", (error)\n global state\n state.dead = true\n )\n return chain client.connect()\n then(ignored)\n return success([], null)\n case \"query\"\n return chain state.client.query({\n text: task.sql\n values: task.parameters\n queryMode: \"extended\"\n })\n then(result)\n global state\n switch result.command\n case \"BEGIN\"\n state.transaction = \"active\"\n case \"COMMIT\"\n case \"ROLLBACK\"\n state.transaction = null\n changes = null\n switch result.command\n case \"INSERT\"\n case \"UPDATE\"\n case \"DELETE\"\n case \"MERGE\"\n changes = result.rowCount\n return success(result.rows, changes)\n case \"invoke\"\n return invoke(task)\n case \"close\"\n return chain state.client.end()\n then(ignored)\n return success([], null)\n else\n throw \"Unknown PostgreSQL operation\"\n\ninvoke(task)\n global state\n global loader\n spec = task.spec\n if spec == null or !is_string(spec.module) or spec.module.startsWith(\"node:\") or !is_string(spec.handler)\n throw \"Database extension requires an application module and exported handler\"\n resolver = modules/createRequire(path/join(threads.workerData.root, \"package.json\"))\n file = resolver.resolve(spec.module)\n if !path/isAbsolute(file)\n throw \"Database extension must resolve to an application file\"\n return chain loader.target({\n module: file\n handler: spec.handler\n })\n then(handler)\n capture task\n global state\n client = state.client\n executeSql = (sql, parameters)\n capture client\n return chain client.query(sql, parameters)\n catch(error)\n global state\n if state.transaction != null\n state.transaction = \"failed\"\n throw error\n adapter = {\n executeSql: executeSql\n }\n return handler(adapter, task.input)\n then(value)\n return success([], null, value)\n\nsuccess(rows, changes, value = null)\n global state\n return {\n failed: false\n dead: false\n state: state.transaction\n rows: rows\n changes: changes\n lastInsertRowid: null\n value: value\n }\n\nreply(result)\n port = threads.workerData.port\n signal = threads.workerData.signal\n port.postMessage(result)\n Atomics/store(signal, 0, 1)\n Atomics/notify(signal, 0)\n return null\n\ninitialState()\n return {\n client: null\n transaction: null\n dead: false\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA;;AACA;;AACA;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA;;;;;;;;;AAYA;;;;;;;;;;;;AAQA;;;;;","x_lango_build":{"fingerprint":"5f1a033ebd280c53501bde3241f7d91d6ef3fbb9f429156ce929d802b18f104a","outputHash":"2a24a180c3846f7dd043467b301853e0fc164ad92af493f716139faf7b8ac26e","mapHash":"bb79353e1d011acd4174b953b351e7e4579529e0291f443837c5569741e69aed"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queue_provider.mjs","sources":["queue_provider.lango"],"sourcesContent":["import js \"node:module\" as modules\nimport js \"node:path\" as path\n\nexport queueProvider(root, spec)\n\nqueueProvider(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Queue provider must be a map\"\n allowed = [\"module\", \"handler\", \"options\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown queue provider option: ${key}\"\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\"node:\") or !is_string(spec.handler) or spec.handler == \"\"\n throw \"Queue provider requires a module and exported handler\"\n settings = spec.options\n if settings == null\n settings = {}\n if !is_object(settings) or is_array(settings)\n throw \"Queue provider options must be a map\"\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n file = resolver.resolve(spec.module)\n if !path/isAbsolute(file)\n throw \"Queue provider must resolve to an application file\"\n return {\n module: file\n handler: spec.handler\n options: from_json(to_json(settings))\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"queue_provider.mjs","sources":["queue_provider.lango"],"sourcesContent":["import js \"node:module\" as modules\nimport js \"node:path\" as path\n\nexport queueProvider(root, spec)\n\nqueueProvider(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Queue provider must be a map\"\n allowed = [\"module\", \"handler\", \"options\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown queue provider option: ${key}\"\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\"node:\") or !is_string(spec.handler) or spec.handler == \"\"\n throw \"Queue provider requires a module and exported handler\"\n settings = spec.options\n if settings == null\n settings = {}\n if !is_object(settings) or is_array(settings)\n throw \"Queue provider options must be a map\"\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n file = resolver.resolve(spec.module)\n if !path/isAbsolute(file)\n throw \"Queue provider must resolve to an application file\"\n return {\n module: file\n handler: spec.handler\n options: from_json(to_json(settings))\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"fbae9be51ef15cc946a94e3a193cf4260428e24b355ebeb7f8dbf9b35460c8bd","outputHash":"7b924822c507d160cee46337842664bf36db83792fb8b5c3c4ebd17365cea184","mapHash":"f64f06a53a58267f697302ffa5702bbe4fbb29526f28ca60043a711e4d5a0e44"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request_identity.mjs","sources":["request_identity.lango"],"sourcesContent":["export requestIdentity(id, token)\n\nrequestIdentity(id, token)\n identity = \"[${id}] [clientId=${token.clientId?}]\"\n for [\"sessionId\", \"userId\"] as name\n value = token.get(name)\n if value != null\n identity = \"${identity} [${name}=${value}]\"\n return identity\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"request_identity.mjs","sources":["request_identity.lango"],"sourcesContent":["export requestIdentity(id, token)\n\nrequestIdentity(id, token)\n identity = \"[${id}] [clientId=${token.clientId?}]\"\n for [\"sessionId\", \"userId\"] as name\n value = token.get(name)\n if value != null\n identity = \"${identity} [${name}=${value}]\"\n return identity\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"d0657657971eb7768a16dc2e8f2c13bf0ad5555d5fa31b0ca7f779e03351dd25","outputHash":"f86a377f9647ef98a57b54007024780d72c58637452b72741638a81cec744607","mapHash":"d0cc4f2ec070f60fd9477fcdf4c0434480d44be85af866d68b6cbdb55e927107"}}
|
package/dist/response.mjs
CHANGED
|
@@ -41,7 +41,7 @@ export class Response {
|
|
|
41
41
|
throw "Header name and value must be strings";
|
|
42
42
|
}
|
|
43
43
|
name = __normalize(name.toLowerCase());
|
|
44
|
-
if (__requireBoolean(contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "content-length", "transfer-encoding", "connection", "content-type"], name))) {
|
|
44
|
+
if (__requireBoolean(contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "x-lango-session", "content-length", "transfer-encoding", "connection", "content-type"], name))) {
|
|
45
45
|
throw `Reserved response header: ${name}`;
|
|
46
46
|
}
|
|
47
47
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(name.includes("\\r"))) || __requireBoolean(__normalize(name.includes("\n")))) || __requireBoolean(__normalize(value.includes("\\r")))) || __requireBoolean(__normalize(value.includes("\n"))))) {
|
package/dist/response.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\nimport \"./http_failure\"\n class HttpFailure\nexport class Response()\n methods\n status(code)\n header(name, value)\n result(body)\n reject(status, code)\n\nResponse()\n @status = 200\n @headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n\nResponse:status(code)\n if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304\n throw \"Response requires a JSON-compatible HTTP status\"\n @status = code\n return @this\n\nResponse:header(name, value)\n if !is_string(name) or !is_string(value)\n throw \"Header name and value must be strings\"\n name = name.toLowerCase()\n if contains([\"x-lango-auth-change\", \"x-lango-need-login\", \"x-lango-token\", \"content-length\", \"transfer-encoding\", \"connection\", \"content-type\"], name)\n throw \"Reserved response header: ${name}\"\n if name.includes(\"\\r\") or name.includes(\"\\n\") or value.includes(\"\\r\") or value.includes(\"\\n\")\n throw \"Invalid response header\"\n http/validateHeaderName(name)\n http/validateHeaderValue(name, value)\n @headers[name] = value\n return @this\n\nResponse:result(body)\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: body\n }\n\nResponse:reject(status, code)\n throw new HttpFailure(status, code, @headers)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\nimport \"./http_failure\"\n class HttpFailure\nexport class Response()\n methods\n status(code)\n header(name, value)\n result(body)\n reject(status, code)\n\nResponse()\n @status = 200\n @headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n\nResponse:status(code)\n if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304\n throw \"Response requires a JSON-compatible HTTP status\"\n @status = code\n return @this\n\nResponse:header(name, value)\n if !is_string(name) or !is_string(value)\n throw \"Header name and value must be strings\"\n name = name.toLowerCase()\n if contains([\"x-lango-auth-change\", \"x-lango-need-login\", \"x-lango-token\", \"x-lango-session\", \"content-length\", \"transfer-encoding\", \"connection\", \"content-type\"], name)\n throw \"Reserved response header: ${name}\"\n if name.includes(\"\\r\") or name.includes(\"\\n\") or value.includes(\"\\r\") or value.includes(\"\\n\")\n throw \"Invalid response header\"\n http/validateHeaderName(name)\n http/validateHeaderValue(name, value)\n @headers[name] = value\n return @this\n\nResponse:result(body)\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: body\n }\n\nResponse:reject(status, code)\n throw new HttpFailure(status, code, @headers)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"1cc3420f05e291892d6d4df63acd13f025a33271534cf74f6a0e4e762fd579e9","outputHash":"3e25c50560446ee1efd48dceb212babbf812457232cb3c998b8912e75d91ffde","mapHash":"be06a96b4971a740c4f2bf0aec388b05b16b2673906cc7a7e3819608c4f5b409"}}
|
package/dist/route_info.mjs
CHANGED
|
@@ -14,7 +14,11 @@ export function routeInfo(definitions) {
|
|
|
14
14
|
if (__requireBoolean(kind === null)) {
|
|
15
15
|
kind = "endpoint";
|
|
16
16
|
}
|
|
17
|
-
|
|
17
|
+
let info = { path: __normalize(route.path), kind: kind, auth: __normalize(route.auth), policy: __normalize(route.policy), reauthSeconds: __normalize(route.reauthSeconds), middleware: __normalize(route.middleware) };
|
|
18
|
+
if (__requireBoolean(__normalize(route.bootstrap) === true)) {
|
|
19
|
+
info.bootstrap = true;
|
|
20
|
+
}
|
|
21
|
+
result.push(info);
|
|
18
22
|
}
|
|
19
23
|
return result;
|
|
20
24
|
return null;
|
package/dist/route_info.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route_info.mjs","sources":["route_info.lango"],"sourcesContent":["export routeInfo(definitions)\n\nrouteInfo(definitions)\n result = []\n for definitions as route\n kind = route.kind\n if kind == null\n kind = \"endpoint\"\n
|
|
1
|
+
{"version":3,"file":"route_info.mjs","sources":["route_info.lango"],"sourcesContent":["export routeInfo(definitions)\n\nrouteInfo(definitions)\n result = []\n for definitions as route\n kind = route.kind\n if kind == null\n kind = \"endpoint\"\n info = {\n path: route.path\n kind: kind\n auth: route.auth\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n middleware: route.middleware\n }\n if route.bootstrap == true\n info.bootstrap = true\n result.add(info)\n return result\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"acab80471472ca17afa36f1f72d80013da4495bf4bf9aef41d2fe5ea6fe03a0d","outputHash":"83a4bccf04719bedbe9e9d0399c6f52a36c0f30d986ca62e3acc1119cb7827c8","mapHash":"830c3ea1a77b0f063f82c6fc526684fa164dbe9a3662b010f7d92a8a62f173f0"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route_pattern.mjs","sources":["route_pattern.lango"],"sourcesContent":["import js global RegExp\n\nexport routePattern(path)\nexport matchPath(pattern, path)\nexport moreSpecific(candidate, current)\n\nroutePattern(path)\n if !is_string(path) or !path.startsWith(\"/\") or path.includes(\"?\") or path.includes(\"#\") or path.includes(\"\\\\\") or path.includes(\"//\")\n throw \"Endpoint requires an absolute URL path\"\n if path.includes(\"*\") and (!path.endsWith(\"/*\") or path.indexOf(\"*\") != path.lastIndexOf(\"*\"))\n throw \"Only trailing /* wildcards are supported\"\n segments = path.split(\"/\")\n segments = segments.slice(1)\n wildcard = path.endsWith(\"/*\")\n if wildcard\n segments.pop()\n names = []\n shape = []\n identifier = new RegExp(\"^[A-Za-z_][A-Za-z0-9_]*$\")\n reserved = [\"__proto__\", \"constructor\", \"prototype\"]\n for segments as segment\n if segment.includes(\"{\") or segment.includes(\"}\")\n if !segment.startsWith(\"{\") or !segment.endsWith(\"}\")\n throw \"Path parameters must occupy an entire segment\"\n name = segment.slice(1, -1)\n if !identifier.test(name) or reserved.includes(name)\n throw \"Invalid path parameter name: ${name}\"\n if names.includes(name)\n throw \"Duplicate path parameter: ${name}\"\n names.add(name)\n shape.add(\"{}\")\n else\n shape.add(segment)\n if wildcard\n shape.add(\"*\")\n key = shape.join(\"/\")\n key = \"/${key}\"\n return {\n segments: segments\n wildcard: wildcard\n key: key\n }\n\nmatchPath(pattern, path)\n parts = path.split(\"/\")\n if parts[0] != \"\"\n return null\n parts = parts.slice(1)\n count = pattern.segments.length\n if pattern.wildcard\n if parts.length <= count\n return null\n else\n if parts.length != count\n return null\n parameters = {}\n for pattern.segments as index: segment\n value = parts[index]\n if segment.startsWith(\"{\")\n if value == \"\"\n return null\n name = segment.slice(1, -1)\n parameters[name] = value\n else\n if segment != value\n return null\n return parameters\n\nmoreSpecific(candidate, current)\n if current == null\n return true\n if candidate.wildcard != current.wildcard\n return !candidate.wildcard\n first = candidate.segments\n second = current.segments\n count = first.length\n if second.length < count\n count = second.length\n for range(count) as index\n segment = first[index]\n alternative = second[index]\n literal = !segment.startsWith(\"{\")\n other = !alternative.startsWith(\"{\")\n if literal != other\n return literal\n return first.length > second.length\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"route_pattern.mjs","sources":["route_pattern.lango"],"sourcesContent":["import js global RegExp\n\nexport routePattern(path)\nexport matchPath(pattern, path)\nexport moreSpecific(candidate, current)\n\nroutePattern(path)\n if !is_string(path) or !path.startsWith(\"/\") or path.includes(\"?\") or path.includes(\"#\") or path.includes(\"\\\\\") or path.includes(\"//\")\n throw \"Endpoint requires an absolute URL path\"\n if path.includes(\"*\") and (!path.endsWith(\"/*\") or path.indexOf(\"*\") != path.lastIndexOf(\"*\"))\n throw \"Only trailing /* wildcards are supported\"\n segments = path.split(\"/\")\n segments = segments.slice(1)\n wildcard = path.endsWith(\"/*\")\n if wildcard\n segments.pop()\n names = []\n shape = []\n identifier = new RegExp(\"^[A-Za-z_][A-Za-z0-9_]*$\")\n reserved = [\"__proto__\", \"constructor\", \"prototype\"]\n for segments as segment\n if segment.includes(\"{\") or segment.includes(\"}\")\n if !segment.startsWith(\"{\") or !segment.endsWith(\"}\")\n throw \"Path parameters must occupy an entire segment\"\n name = segment.slice(1, -1)\n if !identifier.test(name) or reserved.includes(name)\n throw \"Invalid path parameter name: ${name}\"\n if names.includes(name)\n throw \"Duplicate path parameter: ${name}\"\n names.add(name)\n shape.add(\"{}\")\n else\n shape.add(segment)\n if wildcard\n shape.add(\"*\")\n key = shape.join(\"/\")\n key = \"/${key}\"\n return {\n segments: segments\n wildcard: wildcard\n key: key\n }\n\nmatchPath(pattern, path)\n parts = path.split(\"/\")\n if parts[0] != \"\"\n return null\n parts = parts.slice(1)\n count = pattern.segments.length\n if pattern.wildcard\n if parts.length <= count\n return null\n else\n if parts.length != count\n return null\n parameters = {}\n for pattern.segments as index: segment\n value = parts[index]\n if segment.startsWith(\"{\")\n if value == \"\"\n return null\n name = segment.slice(1, -1)\n parameters[name] = value\n else\n if segment != value\n return null\n return parameters\n\nmoreSpecific(candidate, current)\n if current == null\n return true\n if candidate.wildcard != current.wildcard\n return !candidate.wildcard\n first = candidate.segments\n second = current.segments\n count = first.length\n if second.length < count\n count = second.length\n for range(count) as index\n segment = first[index]\n alternative = second[index]\n literal = !segment.startsWith(\"{\")\n other = !alternative.startsWith(\"{\")\n if literal != other\n return literal\n return first.length > second.length\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"e6b107976409b75d589924fe9f4106aa3f10b264ea6ee41f218960874ade1d15","outputHash":"f23e79047182dd95bb0a62ca06aac2d8f31ac100a0574bece9eaa3ea963d82f4","mapHash":"6e4499c1aa27aab837169fcf03d5557900e323f1a0ebfcbb1d5c400b4c85910a"}}
|
package/dist/routes.mjs
CHANGED
|
@@ -108,7 +108,7 @@ export class Routes {
|
|
|
108
108
|
throw "Middleware requires a module and exported handler";
|
|
109
109
|
}
|
|
110
110
|
for (const [key, value] of __entries(spec)) {
|
|
111
|
-
if (__requireBoolean(__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler")) && __requireBoolean(key !== "validate"))) {
|
|
111
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler")) && __requireBoolean(key !== "validate")) && __requireBoolean(key !== "bootstrap"))) {
|
|
112
112
|
throw `Unknown middleware option: ${key}`;
|
|
113
113
|
}
|
|
114
114
|
}
|
|
@@ -118,7 +118,21 @@ export class Routes {
|
|
|
118
118
|
if (__requireBoolean(__requireBoolean(__normalize(spec.validate) !== null) && __requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.validate)))) || __requireBoolean(__normalize(spec.validate) === "")))) {
|
|
119
119
|
throw "Middleware validate must name an exported function";
|
|
120
120
|
}
|
|
121
|
+
let bootstrap = __normalize(spec.bootstrap);
|
|
122
|
+
if (__requireBoolean(bootstrap === "true")) {
|
|
123
|
+
bootstrap = true;
|
|
124
|
+
}
|
|
125
|
+
if (__requireBoolean(bootstrap === "false")) {
|
|
126
|
+
bootstrap = false;
|
|
127
|
+
}
|
|
128
|
+
if (__requireBoolean(__requireBoolean(bootstrap !== null) && __requireBoolean(!__requireBoolean(__isBool(bootstrap))))) {
|
|
129
|
+
throw "Middleware bootstrap must be boolean";
|
|
130
|
+
}
|
|
121
131
|
this.#middlewares[name] = { module: resolveModule(__normalize(spec.module), __normalize(this.#root)), handler: __normalize(spec.handler), validate: __normalize(spec.validate) };
|
|
132
|
+
if (__requireBoolean(bootstrap === true)) {
|
|
133
|
+
let middleware = __normalize(this.#middlewares[name]);
|
|
134
|
+
middleware.bootstrap = true;
|
|
135
|
+
}
|
|
122
136
|
return this;
|
|
123
137
|
return null;
|
|
124
138
|
}
|
|
@@ -169,7 +183,16 @@ export class Routes {
|
|
|
169
183
|
return null;
|
|
170
184
|
}
|
|
171
185
|
definitions() {
|
|
172
|
-
|
|
186
|
+
let definitions = __fromJson(__toJson(__normalize(this.#items)));
|
|
187
|
+
for (const route of definitions) {
|
|
188
|
+
if (__requireBoolean(__requireBoolean(__normalize(route.middleware) !== null) && __requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(this.#middlewares), __normalize(route.middleware)))))) {
|
|
189
|
+
let spec = __normalize(this.#middlewares[__normalize(route.middleware)]);
|
|
190
|
+
if (__requireBoolean(__normalize(spec.bootstrap) === true)) {
|
|
191
|
+
route.bootstrap = true;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return definitions;
|
|
173
196
|
return null;
|
|
174
197
|
}
|
|
175
198
|
events() {
|
|
@@ -292,12 +315,12 @@ export class Routes {
|
|
|
292
315
|
leaf(tag);
|
|
293
316
|
this.#includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds);
|
|
294
317
|
} else if (__normalize(tag.tag()) === "middleware") {
|
|
295
|
-
attributes(tag, ["name", "module", "handler", "validate"]);
|
|
318
|
+
attributes(tag, ["name", "module", "handler", "validate", "bootstrap"]);
|
|
296
319
|
leaf(tag);
|
|
297
320
|
if (__requireBoolean(!__requireBoolean(allowEvents))) {
|
|
298
321
|
throw "Middleware declarations are only allowed in the application's root routes.xml";
|
|
299
322
|
}
|
|
300
|
-
this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler), validate: __normalize(spec.validate) });
|
|
323
|
+
this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler), validate: __normalize(spec.validate), bootstrap: __normalize(spec.bootstrap) });
|
|
301
324
|
} else if (__normalize(tag.tag()) === "event") {
|
|
302
325
|
attributes(tag, ["name", "module", "handler"]);
|
|
303
326
|
leaf(tag);
|
package/dist/routes.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n job(spec)\n jobs()\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null, policy = null, reauthSeconds = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @jobs = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n checkPath(item.path)\n @items.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n auth: item.auth\n policy: item.policy\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n middleware: item.middleware\n })\n return @this\n\nRoutes:checkPath(path)\n pattern = routePattern(path)\n for @items as other\n if other.path == path\n throw \"Duplicate endpoint: ${path}\"\n existing = routePattern(other.path)\n if existing.key == pattern.key\n throw \"Conflicting endpoint pattern: ${path}\"\n return null\n\nRoutes:job(spec)\n allowed = [\"path\", \"module\", \"handler\", \"queue\", \"policy\", \"auth\", \"reauthSeconds\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown job route option: ${key}\"\n item = new Endpoint(spec)\n if item.path.includes(\"*\") or item.path.includes(\"{\") or item.path.includes(\"}\")\n throw \"Job routes require an exact path\"\n if !is_string(spec.queue) or spec.queue.trim() != spec.queue or spec.queue == \"\"\n throw \"Job route requires a queue name\"\n for @jobs as other\n if other.path == item.path\n throw \"Duplicate job route: ${item.path}\"\n @jobs.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n queue: spec.queue\n policy: item.policy\n auth: item.auth\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n })\n return @this\n\nRoutes:jobs()\n return from_json(to_json(@jobs))\n\nRoutes:addMiddleware(name, spec)\n middlewareName(name)\n if Object/hasOwn(@middlewares, name)\n throw \"Duplicate middleware: ${name}\"\n if !is_object(spec) or is_array(spec)\n throw \"Middleware requires a module and exported handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\" and key != \"validate\"\n throw \"Unknown middleware option: ${key}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Middleware handler is required\"\n if spec.validate != null and (!is_string(spec.validate) or spec.validate == \"\")\n throw \"Middleware validate must name an exported function\"\n @middlewares[name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n validate: spec.validate\n }\n return @this\n\nRoutes:middlewares()\n return from_json(to_json(@middlewares))\n\nRoutes:longpoll(spec)\n item = longpollOptions(spec)\n checkPath(item.path)\n @items.add(item)\n return @this\n\nRoutes:event(spec)\n if !contains([\"register\", \"validate\", \"request\"], spec.name)\n throw \"Unknown event: ${spec.name}\"\n if spec.name in @events\n throw \"Duplicate event: ${spec.name}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Event handler is required\"\n @events[spec.name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n }\n return @this\n\nRoutes:include(spec, auth = null, policy = null, reauthSeconds = null)\n includeAt(spec, @root, \"\", [], auth, policy, reauthSeconds)\n return @this\n\nRoutes:xml(file)\n readXml(path/resolve(file), \"\", @root, [], true)\n return @this\n\nRoutes:definitions()\n return from_json(to_json(@items))\n\nRoutes:events()\n return from_json(to_json(@events))\n\nresolveModule(name, directory)\n if !is_string(name) or name == \"\" or name.startsWith(\"node:\")\n throw \"Application module is required\"\n resolver = modules/createRequire(path/join(directory, \"package.json\"))\n resolved = resolver.resolve(name)\n if !path/isAbsolute(resolved)\n throw \"Application module must resolve to a file: ${name}\"\n return resolved\n\njoinPath(prefix, suffix)\n if !is_string(suffix) or !suffix.startsWith(\"/\")\n throw \"Route path must begin with /\"\n if prefix == \"\" or prefix == \"/\"\n return suffix\n if suffix == \"/\"\n return \"${prefix}/\"\n return \"${prefix}${suffix}\"\n\nRoutes:includeAt(spec, directory, prefix, stack, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\".\") or spec.module.startsWith(\"/\") or spec.module.startsWith(\"node:\")\n throw \"Include requires an npm package name\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n if !is_string(mount)\n throw \"Include path must be a string\"\n if mount.includes(\"*\") or mount.includes(\"//\") or mount.includes(\"?\") or mount.includes(\"#\") or mount.includes(\"\\\\\")\n throw \"Invalid include prefix\"\n if mount.endsWith(\"/\") and mount != \"/\"\n mount = mount.slice(0, -1)\n combined = joinPath(prefix, mount)\n if combined == \"/\"\n combined = \"\"\n file = resolveModule(\"${spec.module}/routes.xml\", directory)\n readXml(file, combined, path/dirname(file), stack, false, inheritedAuth, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n real = fs/realpathSync(file)\n if stack.includes(real)\n throw \"Route include cycle: ${real}\"\n root = xml2obj(fs/readFileSync(real, \"utf8\"))\n if root.tag() != \"routes\"\n throw \"Expected routes root: ${real}\"\n attributes(root, [])\n nextStack = stack.slice()\n nextStack.add(real)\n collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents, inheritedPolicy = null, inheritedReauthSeconds = null)\n if parent.innerText().trim() != \"\"\n throw \"Route XML cannot contain text\"\n for parent.children() as tag\n spec = tag.attributes()\n mod = spec.module\n auth = spec.auth\n policy = spec.policy\n reauthSeconds = spec.reauthSeconds\n if mod == null\n mod = inheritedModule\n if auth == null and policy == null\n auth = inheritedAuth\n policy = inheritedPolicy\n if reauthSeconds == null\n reauthSeconds = inheritedReauthSeconds\n switch tag.tag()\n case \"job\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"queue\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n job({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n queue: spec.queue\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"endpoint\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"longpoll\"\n attributes(tag, [\"path\", \"auth\", \"policy\", \"reauthSeconds\", \"waitTimeoutMs\", \"retentionMs\", \"maxMessages\", \"fallback\"])\n leaf(tag)\n spec.path = joinPath(prefix, spec.path)\n spec.auth = auth\n spec.policy = policy\n spec.reauthSeconds = reauthSeconds\n if spec.fallback != null\n spec.fallback = joinPath(prefix, spec.fallback)\n longpoll(spec)\n case \"group\"\n attributes(tag, [\"path\", \"module\", \"auth\", \"policy\", \"reauthSeconds\"])\n collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false, policy, reauthSeconds)\n case \"include\"\n attributes(tag, [\"module\", \"path\"])\n leaf(tag)\n includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds)\n case \"middleware\"\n attributes(tag, [\"name\", \"module\", \"handler\", \"validate\"])\n leaf(tag)\n if !allowEvents\n throw \"Middleware declarations are only allowed in the application's root routes.xml\"\n addMiddleware(spec.name, {\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n validate: spec.validate\n })\n case \"event\"\n attributes(tag, [\"name\", \"module\", \"handler\"])\n leaf(tag)\n if !allowEvents\n throw \"Events are only allowed in the application's root routes.xml\"\n event({\n name: spec.name\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n })\n else\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n middleware: tag.tag()\n })\n return null\n\nleaf(tag)\n if tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Expected an empty ${tag.tag()} element\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoIA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;AAoIA;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n job(spec)\n jobs()\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null, policy = null, reauthSeconds = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @jobs = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n checkPath(item.path)\n @items.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n auth: item.auth\n policy: item.policy\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n middleware: item.middleware\n })\n return @this\n\nRoutes:checkPath(path)\n pattern = routePattern(path)\n for @items as other\n if other.path == path\n throw \"Duplicate endpoint: ${path}\"\n existing = routePattern(other.path)\n if existing.key == pattern.key\n throw \"Conflicting endpoint pattern: ${path}\"\n return null\n\nRoutes:job(spec)\n allowed = [\"path\", \"module\", \"handler\", \"queue\", \"policy\", \"auth\", \"reauthSeconds\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown job route option: ${key}\"\n item = new Endpoint(spec)\n if item.path.includes(\"*\") or item.path.includes(\"{\") or item.path.includes(\"}\")\n throw \"Job routes require an exact path\"\n if !is_string(spec.queue) or spec.queue.trim() != spec.queue or spec.queue == \"\"\n throw \"Job route requires a queue name\"\n for @jobs as other\n if other.path == item.path\n throw \"Duplicate job route: ${item.path}\"\n @jobs.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n queue: spec.queue\n policy: item.policy\n auth: item.auth\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n })\n return @this\n\nRoutes:jobs()\n return from_json(to_json(@jobs))\n\nRoutes:addMiddleware(name, spec)\n middlewareName(name)\n if Object/hasOwn(@middlewares, name)\n throw \"Duplicate middleware: ${name}\"\n if !is_object(spec) or is_array(spec)\n throw \"Middleware requires a module and exported handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\" and key != \"validate\" and key != \"bootstrap\"\n throw \"Unknown middleware option: ${key}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Middleware handler is required\"\n if spec.validate != null and (!is_string(spec.validate) or spec.validate == \"\")\n throw \"Middleware validate must name an exported function\"\n bootstrap = spec.bootstrap\n if bootstrap == \"true\"\n bootstrap = true\n if bootstrap == \"false\"\n bootstrap = false\n if bootstrap != null and !is_bool(bootstrap)\n throw \"Middleware bootstrap must be boolean\"\n @middlewares[name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n validate: spec.validate\n }\n if bootstrap == true\n middleware = @middlewares[name]\n middleware.bootstrap = true\n return @this\n\nRoutes:middlewares()\n return from_json(to_json(@middlewares))\n\nRoutes:longpoll(spec)\n item = longpollOptions(spec)\n checkPath(item.path)\n @items.add(item)\n return @this\n\nRoutes:event(spec)\n if !contains([\"register\", \"validate\", \"request\"], spec.name)\n throw \"Unknown event: ${spec.name}\"\n if spec.name in @events\n throw \"Duplicate event: ${spec.name}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Event handler is required\"\n @events[spec.name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n }\n return @this\n\nRoutes:include(spec, auth = null, policy = null, reauthSeconds = null)\n includeAt(spec, @root, \"\", [], auth, policy, reauthSeconds)\n return @this\n\nRoutes:xml(file)\n readXml(path/resolve(file), \"\", @root, [], true)\n return @this\n\nRoutes:definitions()\n definitions = from_json(to_json(@items))\n for definitions as route\n if route.middleware != null and Object/hasOwn(@middlewares, route.middleware)\n spec = @middlewares[route.middleware]\n if spec.bootstrap == true\n route.bootstrap = true\n return definitions\n\nRoutes:events()\n return from_json(to_json(@events))\n\nresolveModule(name, directory)\n if !is_string(name) or name == \"\" or name.startsWith(\"node:\")\n throw \"Application module is required\"\n resolver = modules/createRequire(path/join(directory, \"package.json\"))\n resolved = resolver.resolve(name)\n if !path/isAbsolute(resolved)\n throw \"Application module must resolve to a file: ${name}\"\n return resolved\n\njoinPath(prefix, suffix)\n if !is_string(suffix) or !suffix.startsWith(\"/\")\n throw \"Route path must begin with /\"\n if prefix == \"\" or prefix == \"/\"\n return suffix\n if suffix == \"/\"\n return \"${prefix}/\"\n return \"${prefix}${suffix}\"\n\nRoutes:includeAt(spec, directory, prefix, stack, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\".\") or spec.module.startsWith(\"/\") or spec.module.startsWith(\"node:\")\n throw \"Include requires an npm package name\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n if !is_string(mount)\n throw \"Include path must be a string\"\n if mount.includes(\"*\") or mount.includes(\"//\") or mount.includes(\"?\") or mount.includes(\"#\") or mount.includes(\"\\\\\")\n throw \"Invalid include prefix\"\n if mount.endsWith(\"/\") and mount != \"/\"\n mount = mount.slice(0, -1)\n combined = joinPath(prefix, mount)\n if combined == \"/\"\n combined = \"\"\n file = resolveModule(\"${spec.module}/routes.xml\", directory)\n readXml(file, combined, path/dirname(file), stack, false, inheritedAuth, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n real = fs/realpathSync(file)\n if stack.includes(real)\n throw \"Route include cycle: ${real}\"\n root = xml2obj(fs/readFileSync(real, \"utf8\"))\n if root.tag() != \"routes\"\n throw \"Expected routes root: ${real}\"\n attributes(root, [])\n nextStack = stack.slice()\n nextStack.add(real)\n collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents, inheritedPolicy = null, inheritedReauthSeconds = null)\n if parent.innerText().trim() != \"\"\n throw \"Route XML cannot contain text\"\n for parent.children() as tag\n spec = tag.attributes()\n mod = spec.module\n auth = spec.auth\n policy = spec.policy\n reauthSeconds = spec.reauthSeconds\n if mod == null\n mod = inheritedModule\n if auth == null and policy == null\n auth = inheritedAuth\n policy = inheritedPolicy\n if reauthSeconds == null\n reauthSeconds = inheritedReauthSeconds\n switch tag.tag()\n case \"job\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"queue\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n job({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n queue: spec.queue\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"endpoint\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"longpoll\"\n attributes(tag, [\"path\", \"auth\", \"policy\", \"reauthSeconds\", \"waitTimeoutMs\", \"retentionMs\", \"maxMessages\", \"fallback\"])\n leaf(tag)\n spec.path = joinPath(prefix, spec.path)\n spec.auth = auth\n spec.policy = policy\n spec.reauthSeconds = reauthSeconds\n if spec.fallback != null\n spec.fallback = joinPath(prefix, spec.fallback)\n longpoll(spec)\n case \"group\"\n attributes(tag, [\"path\", \"module\", \"auth\", \"policy\", \"reauthSeconds\"])\n collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false, policy, reauthSeconds)\n case \"include\"\n attributes(tag, [\"module\", \"path\"])\n leaf(tag)\n includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds)\n case \"middleware\"\n attributes(tag, [\"name\", \"module\", \"handler\", \"validate\", \"bootstrap\"])\n leaf(tag)\n if !allowEvents\n throw \"Middleware declarations are only allowed in the application's root routes.xml\"\n addMiddleware(spec.name, {\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n validate: spec.validate\n bootstrap: spec.bootstrap\n })\n case \"event\"\n attributes(tag, [\"name\", \"module\", \"handler\"])\n leaf(tag)\n if !allowEvents\n throw \"Events are only allowed in the application's root routes.xml\"\n event({\n name: spec.name\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n })\n else\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n middleware: tag.tag()\n })\n return null\n\nleaf(tag)\n if tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Expected an empty ${tag.tag()} element\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoJA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;AAqIA;;;;;;;;;;","x_lango_build":{"fingerprint":"1d613ef75a657663394f6ab0fd067983304089a4d797c8b9417d0a0ffee4dc77","outputHash":"fc94fee8e5fcee173be1983460f3e78a072204c860e29a0880b70d5b607be14b","mapHash":"eb129adabe08566fdbe32c54593e363ef211ecd635b49f4f44927e900e031bfc"}}
|
package/dist/runtime.mjs
CHANGED
|
@@ -178,14 +178,21 @@ export class Runtime {
|
|
|
178
178
|
}), [0], "closure")).then(__withArity(__bindContexts((handler) => {
|
|
179
179
|
handler = __boundary(handler);
|
|
180
180
|
let middleware = null;
|
|
181
|
+
let bootstrap = false;
|
|
181
182
|
let name = __normalize(route.middleware);
|
|
182
183
|
if (__requireBoolean(name !== null)) {
|
|
183
184
|
if (__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(this.#middlewares), name))))) {
|
|
184
185
|
throw `Middleware is not registered: ${name}`;
|
|
185
186
|
}
|
|
186
187
|
middleware = __normalize(this.#middlewares[name]);
|
|
188
|
+
let specs = __normalize(this.#definition.middlewares);
|
|
189
|
+
let spec = __normalize(specs[name]);
|
|
190
|
+
bootstrap = __normalize(spec.bootstrap) === true;
|
|
187
191
|
}
|
|
188
|
-
|
|
192
|
+
if (__requireBoolean(__requireBoolean(bootstrap) && __requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(route.policy) !== "anonymous") || __requireBoolean(__normalize(route.reauthSeconds) > 0)) || __requireBoolean(__normalize(route.path.includes("*")))) || __requireBoolean(__normalize(route.path.includes("{")))) || __requireBoolean(__normalize(route.path.includes("}")))))) {
|
|
193
|
+
throw "Bootstrap middleware requires an exact anonymous endpoint without reauthentication";
|
|
194
|
+
}
|
|
195
|
+
__add(this.#routes, { path: __normalize(route.path), pattern: routePattern(__normalize(route.path)), auth: __normalize(route.auth), policy: __normalize(route.policy), reauthSeconds: __normalize(route.reauthSeconds), legacyAuth: __normalize(route.legacyAuth), handler: handler, middleware: middleware, bootstrap: bootstrap });
|
|
189
196
|
return null;
|
|
190
197
|
return null;
|
|
191
198
|
}), [0], "closure"));
|
|
@@ -248,22 +255,38 @@ export class Runtime {
|
|
|
248
255
|
if (__requireBoolean(!__requireBoolean(originAllowed(__normalize(this.#definition.settings.origin), __contextGet("request"))))) {
|
|
249
256
|
return failure(403, "OriginRejected");
|
|
250
257
|
}
|
|
251
|
-
let
|
|
258
|
+
let matched = this.#match(__normalize(__contextGet("request").path));
|
|
259
|
+
let bootstrap = false;
|
|
260
|
+
if (__requireBoolean(matched !== null)) {
|
|
261
|
+
let selectedRoute = __normalize(matched.route);
|
|
262
|
+
bootstrap = __normalize(selectedRoute.bootstrap) === true;
|
|
263
|
+
}
|
|
264
|
+
let authorization = __normalize(__contextGet("request").headers.authorization);
|
|
265
|
+
let hint = __normalize(__contextGet("request").headers["x-lango-startup-token"]);
|
|
266
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(authorization === null) && __requireBoolean(bootstrap)) && __requireBoolean(__normalize(this.#clients) === null)) && __requireBoolean(hint !== null))) {
|
|
267
|
+
authorization = `Bearer ${hint}`;
|
|
268
|
+
}
|
|
269
|
+
let fresh = authorization === null;
|
|
252
270
|
let claims = null;
|
|
253
271
|
try {
|
|
254
272
|
if (__requireBoolean(!__requireBoolean(fresh))) {
|
|
255
|
-
claims = __normalize(this.#tokens.read(
|
|
273
|
+
claims = __normalize(this.#tokens.read(authorization));
|
|
256
274
|
}
|
|
257
275
|
} catch (error) {
|
|
276
|
+
if (__requireBoolean(error === "TokenExpired")) {
|
|
277
|
+
return expiredSession();
|
|
278
|
+
}
|
|
258
279
|
__normalize(__contextGet("log").warn(`[${__normalize(__contextGet("request").id)}] ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization rejected before handler: ${errorMessage(error)}`));
|
|
259
280
|
return failure(401, "Unauthorized");
|
|
260
281
|
}
|
|
261
|
-
let matched = this.#match(__normalize(__contextGet("request").path));
|
|
262
282
|
if (__requireBoolean(matched === null)) {
|
|
263
283
|
trace(`[${__normalize(__contextGet("request").id)}] No route matched ${__normalize(__contextGet("request").path)}`);
|
|
264
284
|
return failure(404, "RouteNotFound");
|
|
265
285
|
}
|
|
266
286
|
let route = __normalize(matched.route);
|
|
287
|
+
if (__requireBoolean(__requireBoolean(hint !== null) && __requireBoolean(!__requireBoolean(bootstrap)))) {
|
|
288
|
+
return failure(400, "InvalidStartupRequest");
|
|
289
|
+
}
|
|
267
290
|
let metadata = routeInfo([route]);
|
|
268
291
|
let selected = __normalize(__hostGlobal(["Object"]).freeze(__normalize(metadata[0])));
|
|
269
292
|
__contextScope.push(__contextSet("request", __normalize(__hostGlobal(["Object"]).freeze(__normalize(__hostGlobal(["Object"]).assign({ }, __contextGet("request"), { route: selected }))))));
|
|
@@ -289,6 +312,11 @@ export class Runtime {
|
|
|
289
312
|
try {
|
|
290
313
|
if (__requireBoolean(__normalize(this.#clients) !== null)) {
|
|
291
314
|
__contextScope.push(__contextSet("clientIdentity", __normalize(this.#clients.begin(claims, __normalize(this.#tokens)))));
|
|
315
|
+
if (__requireBoolean(__requireBoolean(bootstrap) && __requireBoolean(!__requireBoolean(__normalize(__contextGet("clientIdentity").fresh))))) {
|
|
316
|
+
__contextGet("clientIdentity").claims = __normalize(this.#tokens.create(__normalize(__contextGet("clientIdentity").claims.clientId)));
|
|
317
|
+
__contextGet("clientIdentity").claims.clientProof = __normalize(__contextGet("clientIdentity").hash);
|
|
318
|
+
__contextGet("clientIdentity").restored = true;
|
|
319
|
+
}
|
|
292
320
|
claims = __normalize(__contextGet("clientIdentity").claims);
|
|
293
321
|
fresh = __normalize(__contextGet("clientIdentity").fresh);
|
|
294
322
|
restored = __normalize(__contextGet("clientIdentity").restored);
|
|
@@ -474,7 +502,10 @@ export class Runtime {
|
|
|
474
502
|
if (__requireBoolean(__isKindof(error, HttpFailure))) {
|
|
475
503
|
return __normalize(error.result());
|
|
476
504
|
}
|
|
477
|
-
if (__requireBoolean(
|
|
505
|
+
if (__requireBoolean(error === "TokenExpired")) {
|
|
506
|
+
return expiredSession();
|
|
507
|
+
}
|
|
508
|
+
if (__requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401))) {
|
|
478
509
|
__normalize(__contextGet("log").warn(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization or validation rejected: Unauthorized`));
|
|
479
510
|
return failure(401, "Unauthorized");
|
|
480
511
|
}
|
|
@@ -558,12 +589,11 @@ export class Runtime {
|
|
|
558
589
|
child = __boundary(child);
|
|
559
590
|
return pending.then(__withArity(__bindContexts((ignored) => {
|
|
560
591
|
ignored = __boundary(ignored);
|
|
561
|
-
let
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
} catch (error) {
|
|
565
|
-
return failure(401, "Unauthorized");
|
|
592
|
+
let read = this.#readRefreshToken(encoded);
|
|
593
|
+
if (__requireBoolean(__normalize(read.rejection) !== null)) {
|
|
594
|
+
return __normalize(read.rejection);
|
|
566
595
|
}
|
|
596
|
+
let checked = __normalize(read.claims);
|
|
567
597
|
if (__requireBoolean(__normalize(checked.clientId) !== owner)) {
|
|
568
598
|
return failure(401, "Unauthorized");
|
|
569
599
|
}
|
|
@@ -575,12 +605,30 @@ export class Runtime {
|
|
|
575
605
|
if (__requireBoolean(__normalize(result.status) < 400)) {
|
|
576
606
|
updated = result.headers["x-lango-token"];
|
|
577
607
|
}
|
|
578
|
-
|
|
608
|
+
let item = { previous: encoded, token: updated, status: __normalize(result.status) };
|
|
609
|
+
if (__requireBoolean(result.headers["x-lango-session"] === "expired")) {
|
|
610
|
+
item.reason = "SessionExpired";
|
|
611
|
+
}
|
|
612
|
+
__add(results, item);
|
|
579
613
|
return null;
|
|
580
614
|
return null;
|
|
581
615
|
}), [0], "closure"));
|
|
582
616
|
return null;
|
|
583
617
|
}
|
|
618
|
+
#readRefreshToken(encoded) {
|
|
619
|
+
__requireArity(arguments.length, [0], "readRefreshToken");
|
|
620
|
+
encoded = __boundary(encoded);
|
|
621
|
+
try {
|
|
622
|
+
return { claims: __normalize(this.#tokens.read(`Bearer ${encoded}`)) };
|
|
623
|
+
} catch (error) {
|
|
624
|
+
let rejected = failure(401, "Unauthorized");
|
|
625
|
+
if (__requireBoolean(error === "TokenExpired")) {
|
|
626
|
+
rejected = expiredSession();
|
|
627
|
+
}
|
|
628
|
+
return { rejection: rejected };
|
|
629
|
+
}
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
584
632
|
#event(name, input) {
|
|
585
633
|
const __contextScope = [];
|
|
586
634
|
try {
|
|
@@ -756,6 +804,13 @@ function failure(status, code) {
|
|
|
756
804
|
return null;
|
|
757
805
|
}
|
|
758
806
|
|
|
807
|
+
function expiredSession() {
|
|
808
|
+
let result = failure(401, "SessionExpired");
|
|
809
|
+
result.headers["x-lango-session"] = "expired";
|
|
810
|
+
return result;
|
|
811
|
+
return null;
|
|
812
|
+
}
|
|
813
|
+
|
|
759
814
|
function stampValidation(claims, validatedAt) {
|
|
760
815
|
__requireArity(arguments.length, [0, 1], "stampValidation");
|
|
761
816
|
claims = __boundary(claims);
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport \"./module_loader\"\n class ModuleLoader\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 @loader = new ModuleLoader()\n @queueFactory = null\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.queueProvider != null\n pending = prepareQueue(pending)\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:prepareQueue(pending)\n return chain pending\n then(ignored)\n return @loader.target(@definition.queueProvider)\n then(factory)\n @queueFactory = factory\n return null\n\nRuntime:queueSender()\n if @queueFactory == null\n return null\n factory = @queueFactory\n return factory(@definition.queueProvider.options)\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 return @loader.target(spec)\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 sender = null\n try\n sender = queueSender()\n catch error\n closeScope(db, false)\n closeClientScope()\n log.err(\"${requestIdentity(request.id, token)} Queue preparation failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n context queue = sender\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 closeClientScope()\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 sender = null\n try\n sender = queueSender()\n catch error\n closeScope(db, false)\n log.err(\"${requestIdentity(id, token)} Request event queue preparation failed: ${errorDetails(error)}\")\n return result\n context queue = sender\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\ncloseClientScope()\n context clientIdentity\n if clientIdentity != null\n clientIdentity.closed = true\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAueA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport \"./module_loader\"\n class ModuleLoader\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 @loader = new ModuleLoader()\n @queueFactory = null\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.queueProvider != null\n pending = prepareQueue(pending)\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:prepareQueue(pending)\n return chain pending\n then(ignored)\n return @loader.target(@definition.queueProvider)\n then(factory)\n @queueFactory = factory\n return null\n\nRuntime:queueSender()\n if @queueFactory == null\n return null\n factory = @queueFactory\n return factory(@definition.queueProvider.options)\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 bootstrap = false\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 specs = @definition.middlewares\n spec = specs[name]\n bootstrap = spec.bootstrap == true\n if bootstrap and (route.policy != \"anonymous\" or route.reauthSeconds > 0 or route.path.includes(\"*\") or route.path.includes(\"{\") or route.path.includes(\"}\"))\n throw \"Bootstrap middleware requires an exact anonymous endpoint without reauthentication\"\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 bootstrap: bootstrap\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 return @loader.target(spec)\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 matched = match(request.path)\n bootstrap = false\n if matched != null\n selectedRoute = matched.route\n bootstrap = selectedRoute.bootstrap == true\n authorization = request.headers.authorization\n hint = request.headers[\"x-lango-startup-token\"]\n if authorization == null and bootstrap and @clients == null and hint != null\n authorization = \"Bearer ${hint}\"\n fresh = authorization == null\n claims = null\n try\n if !fresh\n claims = @tokens.read(authorization)\n catch error\n if error == \"TokenExpired\"\n return expiredSession()\n log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\n return failure(404, \"RouteNotFound\")\n route = matched.route\n if hint != null and !bootstrap\n return failure(400, \"InvalidStartupRequest\")\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 if bootstrap and !clientIdentity.fresh\n clientIdentity.claims = @tokens.create(clientIdentity.claims.clientId)\n clientIdentity.claims.clientProof = clientIdentity.hash\n clientIdentity.restored = true\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 sender = null\n try\n sender = queueSender()\n catch error\n closeScope(db, false)\n closeClientScope()\n log.err(\"${requestIdentity(request.id, token)} Queue preparation failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n context queue = sender\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\"\n return expiredSession()\n if 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 closeClientScope()\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 read = readRefreshToken(encoded)\n if read.rejection != null\n return read.rejection\n checked = read.claims\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 item = {\n previous: encoded\n token: updated\n status: result.status\n }\n if result.headers[\"x-lango-session\"] == \"expired\"\n item.reason = \"SessionExpired\"\n results.add(item)\n return null\n\nRuntime:readRefreshToken(encoded)\n try\n return {\n claims: @tokens.read(\"Bearer ${encoded}\")\n }\n catch error\n rejected = failure(401, \"Unauthorized\")\n if error == \"TokenExpired\"\n rejected = expiredSession()\n return {\n rejection: rejected\n }\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 sender = null\n try\n sender = queueSender()\n catch error\n closeScope(db, false)\n log.err(\"${requestIdentity(id, token)} Request event queue preparation failed: ${errorDetails(error)}\")\n return result\n context queue = sender\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\nexpiredSession()\n result = failure(401, \"SessionExpired\")\n result.headers[\"x-lango-session\"] = \"expired\"\n return result\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\ncloseClientScope()\n context clientIdentity\n if clientIdentity != null\n clientIdentity.closed = true\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+gBA;;;;;;;;;;;;AAeA;;;;;;;AAKA;;;;;;;;;AAIA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"ce5b9eee4239e54cb7e967316981aaab473f7ca82a933a135d02bddbcfcfb2a3","outputHash":"3671f2f0ffb7593583bcb7025287d83fc98b4a2c973fa34d5540b7e77ee5f5d3","mapHash":"f6165cdc09ce53e3cebed9713f17b08b7271b9c23804a4d4853e79e141afc8e1"}}
|
package/dist/server.mjs
CHANGED
|
@@ -295,7 +295,7 @@ export class Server {
|
|
|
295
295
|
}
|
|
296
296
|
state.done = true;
|
|
297
297
|
if (__requireBoolean(__normalize(res.writableFinished))) {
|
|
298
|
-
responseLog(__normalize(res.langoRequestId), __normalize(req.method), target, __normalize(res.statusCode));
|
|
298
|
+
responseLog(__normalize(res.langoRequestId), __normalize(req.method), target, __normalize(res.statusCode), __normalize(res.langoSession));
|
|
299
299
|
} else {
|
|
300
300
|
trace(`HTTP ${__normalize(req.method)} ${target} connection closed before response completed`);
|
|
301
301
|
}
|
|
@@ -735,6 +735,7 @@ function write(res, result) {
|
|
|
735
735
|
return null;
|
|
736
736
|
}
|
|
737
737
|
try {
|
|
738
|
+
res.langoSession = result.headers["x-lango-session"];
|
|
738
739
|
__normalize(res.writeHead(__normalize(result.status), __normalize(result.headers)));
|
|
739
740
|
__normalize(res.end(__normalize(result.body)));
|
|
740
741
|
} catch (error) {
|