@rank-lang/server-runtime
v0.3.1
Published
Rank server runtime workspace package
Readme
@rank-lang/server-runtime
Helpers for loading and validating Rank server entrypoints.
Install
npm install @rank-lang/server-runtimeAPI
loadRankServerApp(entry, cwd?, options?)
Loads a Rank entry module through @rank-lang/compiler, validates the server-specific exports, and returns either:
{ ok: true, app }{ ok: false, diagnostic }
Validation rules:
pub mainmust existpub mainmust be a function valuepub mainmust accept zero or one parameters- when
pub mainaccepts one parameter, it must be typed asstd::Runtime::ExecutionContext<Routes> - optional
pub configmust be an object literal or zero-argument function
The success result contains:
entryPath: resolved absolute entry pathmoduleGraph: loaded compiler module graph configured for serve-time evaluationhasConfig: whetherpub configwas presentmainDeclaration: validatedpub maindeclarationconfigDeclaration: validatedpub configdeclaration when present
prepareServeRuntime(options)
Normalizes host and port options, loads the server app, and returns either:
{ ok: true, runtime, note }{ ok: false, diagnostic }
runtime exposes:
app: the loadedRankServerApphost,port: resolved listener coordinatesshutdownGracePeriodMs: resolved grace period (ms)defaultResponseFormat: resolved response format frompub configmaxRequestBodyBytes: resolved body size limit frompub configrequestTimeoutMs: resolved request deadline frompub configdispatch(request): dispatch aServeRequestInputand get aServeDispatchResultclose(): shut down provider runtime state
ServeRequestInput shape:
method: HTTP method stringpath: request pathheaders?: header mapbody?: raw request body stringremoteAddress?: client IPrequestId?: forwarded toreq.ctx.request_idtimeReceived?: forwarded toreq.ctx.time_received
ServeDispatchResult shape: { status, headers, body }.
Options (ServeRuntimeOptions):
entry: path to the.rankserver entrypointcwd?: working directory for resolvingentry(default:process.cwd())host?: bind host (default:localhost)port?: bind port (default:0, OS-assigned)shutdownGracePeriodMs?: drain timeout before force-close. Defaults to30_000dev?: enable verbose error detail strings in runtime-generated responsesfrozenLockfile?: fail if provider lockfile would be updatedoffline?: disable network access during provider resolutionproviderCapabilities?: override allowed provider capabilitiesallowedHttpHosts?: override allowed outbound HTTP hostsallowedEnvPatterns?: override allowed env var patternsproviderTimeoutMs?: override provider invocation timeout
startServeRuntime(options)
Accepts the same options as prepareServeRuntime. Starts a Node HTTP listener and returns either:
{ ok: true, runtime, note }{ ok: false, diagnostic }
runtime extends PreparedServeRuntime with:
server: the bound Node HTTP serverurl: the bound listener URLstop(): stops accepting new connections, closes idle keep-alives, waits up toshutdownGracePeriodMs, then force-closes remaining connections before shutting down provider runtime state
Current execution scope:
- exact method/path route matching plus match-prefixed path params
- synthesized
404and405before handler execution HTTP::AppConfig.allowedOrigins/allowCredentialssynthesize CORS preflightOPTIONSresponses and attach matching CORS headers to ordinary responses for admitted origins;maxRequestBodyBytescaps request body size (default1_048_576)- route-local query, JSON body, header, and cookie validation before handler execution
- route-local API-key auth execution for named routes whose executable auth metadata is supplied inline on
HTTP::ApiKeyAuth<T> { ... }; same-named value binding probing remains available as a compatibility fallback req.params,req.query,req.body,req.headers,req.cookies, andreq.ctx.request_id/req.ctx.time_receivedmaterialization- authenticated routes also materialize
req.authafter successful verifier execution - response serialization for
json,yaml, andtext - compatible explicit
content-typeoverrides are preserved; conflicting ones fail with a structured runtime error - ordinary redirect responses work through status plus
locationheaders with no special helper type - manual
set-cookieheaders are rejected when typedcookiesoutput is also present - request deadlines are enforced through
requestTimeoutMs options.dev === trueadds verbosedetailstrings to runtime-generated validation and request-shape error responses while keeping opaque internal500s unchanged- graceful shutdown stops accepting new connections, closes idle keep-alives, rejects late-arriving requests with a structured
503once draining begins, and force-closes remaining connections aftershutdownGracePeriodMs - the host exposes a reserved readiness endpoint at
/.well-known/rank/ready, returning200 { ok: true, state: "ready" }while serving and503 RUNTIME_DRAININGonce shutdown has begun - zero-arg
pub configEnv<T> {}reads are filtered through the admittedallow-envview before listener startup - undeclared incoming headers and cookies are ignored unless the route contract declares a rest field
- bare
allow-env = ["*"]emits a visible startup warning before serving begins
Example
import { startServeRuntime } from "@rank-lang/server-runtime";
const started = await startServeRuntime({
entry: "src/server.rank",
port: 3000,
});
if (!started.ok) {
throw new Error(started.diagnostic);
}
console.log(started.note);
await started.runtime.stop();Development
npm run build -w @rank-lang/server-runtime
npm run test -w @rank-lang/server-runtime
npm run typecheck -w @rank-lang/server-runtimePublishing
Build the package first, then publish from the workspace root:
npm run build -w @rank-lang/server-runtime
npm publish -w @rank-lang/server-runtime