@lunora/platform-node is the Node host: the @lunora/platform contracts
(ShardHost, SocketHost, ShardDirectory, ShardKvStore, SchedulerHost)
implemented over better-sqlite3 and an in-process registry, plus .global()
tables over @lunora/sql-store, workflows over @visulima/workflow, and object
storage on the local filesystem.
import { createNodePlatform } from "@lunora/platform-node";
const platform = createNodePlatform({ path: "./shard.sqlite3" });
// …or with the emulated tiers bound. Each is a declaration: omit it and the
// corresponding member is `undefined` rather than an empty host.
const full = createNodePlatform({
crons: LUNORA_CRONS, // from _generated/crons.ts; the whole declared set
// The per-shard handler: crons, scheduled jobs and fan-out reach the app through it.
// `shardDoFor` returns the one ShardDO you keep per shard (see `liveStreams`).
onFetch: (request, shard) => shardDoFor(shard).fetch(request),
globalTablesPath: "./.lunora/global.sqlite3", // → platform.globalTables, its own file
objectStorageDirectory: "./.lunora/bucket", // → platform.objectStorage
onQueueBatch: dispatchQueueBatch, // required alongside `queues`
path: "./shard.sqlite3",
queues: { emails }, // → platform.queues
workflows: { orderPipeline }, // → platform.workflows, runs in the same SQLite file
});Status
Experimental, and not a shipping target. There is no lunora dev --target node; this package ships no dev server. A @lunora/config deploy driver
(node) does exist, but provision is a reporting step, not a writing one: it
tells you, once, which declared features this target cannot serve, and it has
no toolchain to shell out to (no wrangler-equivalent), because there is
nothing remote to deploy to, tail logs from, or store secrets in.
lunora deploy --target node deploys to a container build context instead:
a bundled server.mjs whose generated entry composes this package around the
app's worker entry (every Durable Object binding, crons: LUNORA_CRONS,
createNodeSecretBindings over the secrets_store_secrets[] names, and
createNodeHyperdrive from DATABASE_URL), a Dockerfile on a pinned Node LTS
image that compiles better-sqlite3 and runs as a non-root user, and a README
listing the environment it reads. The SQLite files live under
LUNORA_DATA_DIR (/data in the image), which is the volume to mount. See
lunora deploy in the CLI docs.
Its API snapshot is gated at the experimental tier
(scripts/api-snapshot.js): a diff here is a public-API change and must be
reviewed as one. This package is Experimental: the snapshot records how its surface
moves, and carries no SemVer promise until the package graduates
(ROADMAP.md's graduation bar).
scripts/check-roadmap-tiers.js fails the install if the roadmap and the
snapshot tier ever disagree.
Read the table below as an honest self-rating, not an invitation to run production traffic on it.
Capability matrix
Reproduced from NODE_CAPABILITIES in @lunora/platform
(packages/platform/src/capabilities/node.ts). This is the same matrix codegen
gates ctx.* surfaces on, not a second copy of it.
pnpm run lint:node-capabilities-docs fails if this table and the source
disagree.
| Feature | Level | Notes |
|---|---|---|
shardedState | emulated | One better-sqlite3 database per shard key, one process — no distributed placement or failover. Shard keys are percent-encoded into basenames with A-Z escaped, so Tenant and tenant stay two databases on a case-insensitive volume (APFS, NTFS) rather than folding into one. There is also no input gate: Cloudflare defers every other dispatch for the span of a mutation, whereas this host can only refuse — SQL issued from another task while a transaction is open throws a retryable SHARD_UNAVAILABLE (503) rather than reading rows that are about to roll back, so a read that merely arrived mid-mutation is retried instead of failing the request |
globalTables | emulated | The @lunora/sql-store core on its own SQLite file via the reference sqliteDialect — full store semantics, but one node with no replication |
websocketHibernation | emulated | Socket registry with attachments/tags persisted to SQLite, and createNodeSocketHost can rehydrate a row into a handle — but restoreSocket is not a SocketHost member and neither createNodePlatform nor createNodeShardRegistry surfaces it, so nothing composed here reassociates a reconnecting client; the conformance host is its only caller. Nothing is ever actually evicted from memory either, so this is durability without hibernation's memory saving and without its rehydration |
workerLoaders | unsupported | No isolate loader: Node has no V8-isolate sandbox for untrusted code, and a node:vm context is not a security boundary |
typedWebSockets | emulated | Rooms and defineWebSocket routes take real network clients: createNodeHttpServer completes the WebSocket handshake through the worker, and the embedder binds the shard with bindShardSockets so inbound frames and closes reach the shard. The socket registry is one process, so a route's broadcast does not fan out to another process, and nothing reassociates a reconnecting client, so a room's membership does not survive a restart |
liveStreams | emulated | Served in this process, by the same ShardDO live handlers Cloudflare runs: connect, subscribe and publish reach the shard through the in-process registry, and createNodeHttpServer streams the SSE body back unbuffered, so a frame reaches the client as it is published. A client that disconnects cancels the body, which drops the subscriber. ctx.live.publish from an HTTP action reaches the subscribers of the shard it names. The embedder composes it: createWorker over createNodeShardNamespace(registry.directory), with one ShardDO kept per shard for the life of the process, since a ShardDO built per request loses its subscribers. A queue consumer's ctx.live comes from the worker's queue export: createWorker's queue(batch, env, ctx) builds the publisher over the same shard forwarding the HTTP action uses, and createNodePlatform's onQueueBatch is the seam that batch is delivered through. A scheduled job's publish takes the same in-process path but is not exercised on this host. Emulated, not native, because the subscriber registry lives in one process: there is no cross-process fan-out, and no keepalive comment frame is sent, so a reverse proxy that idles out a silent stream will close it and the client reconnects |
durableStreams | unsupported | The transcript store is host-neutral (@lunora/shard-engine), but the attach/produce state machine lives in @lunora/do and nothing in this host mounts it. Gate-bearing: codegen refuses an app that declares a durable stream on this target, rather than emitting one that silently behaves as an ephemeral stream |
localSql | native | better-sqlite3 (synchronous, embedded) |
commitOrderedTables | emulated | The sequence orders commits correctly, but the serialization it depends on is Lunora's per-shard write gate rather than a platform property — one process, one better-sqlite3 handle per shard key. Correct here; not something the host guarantees the way a Durable Object does |
deliveryAuthorization | unsupported | Not exercised by this host's conformance suite, and its socket registry does not reassociate a reconnecting client, so the permits a hibernated socket carries have nothing to restore into. Rate it once the suite drives an authorized RPC, a subscription and a fence install |
conditionalWrites | native | SQLite decides it on both paths: shard-local in one synchronous better-sqlite3 run, .global() in one conditional UPDATE on the host's own SQLite file (one node, so nothing to replicate) |
objectColumnPaths | native | json_extract on both paths, over better-sqlite3. It is the same SQLite statement the engine tests run on node:sqlite; it has not been run through better-sqlite3 itself in this host's suite |
queryExplain | native | EXPLAIN QUERY PLAN on better-sqlite3 for both paths. It is the same SQLite statement the engine tests run on node:sqlite; it has not been run through better-sqlite3 itself in this host's suite |
memoryTables | emulated | Same shape as Cloudflare and for a different reason: better-sqlite3 CAN open :memory:, but a shard's memory tables share the one handle its durable tables use, so they are cleared rather than never written. A host process also outlives far more than a Durable Object does, so cold starts — and therefore onShardInit — are much rarer here than in production on Cloudflare; do not use this target to judge how often a memory table is actually empty |
serverReactors | emulated | Same engine-level implementation as Cloudflare; the per-shard serialization it depends on is the host's own write gate rather than a platform guarantee |
alarmRearmBreaker | emulated | Lunora's own counter, not a platform primitive: the poll alarm's re-arms that are due sooner than the 2 s floor are counted in one row of the shard's SQL (ShardHost.sql) over a sliding window, and a re-arm past the budget is refused, leaves one recovery wake a window out, and is logged once per trip. Re-arms at or beyond the floor are checked against that row and never written to it, so a poll at 2 s or slower costs no SQL write. The arm it gates is ShardHost.alarms, so it runs wherever the shard has durable SQL and alarms |
deploymentPause | unsupported | No SchedulerDO on this host, which is where the pause flag lives and what holds scheduled jobs while paused: the admin route answers PAUSE_NOT_CONFIGURED and GET reports supported: false. The router, cron and queue checks are host-neutral runtime code and would apply unchanged given a durable home for the flag |
scheduleRateBreaker | emulated | Lunora's own counter, not a platform primitive: each ctx.scheduler target's schedules are counted per shard in one row of the shard's SQL (ShardHost.sql) over a sliding window, once per invocation, and a schedule past the budget is deferred one window instead of being refused or dropped. The schedules it defers are stored through SchedulerDO, so it runs wherever the shard has durable SQL and a scheduler |
shardAlarms | emulated | setTimeout over a durable row, dispatched to onAlarm and re-armed on construction, so an alarm survives a restart and one whose time elapsed while the process was down fires late rather than never. Delivery is at-least-once as it is on workerd: a handler that throws is re-delivered with exponential backoff (6 attempts, from 100ms) and then abandoned, and an alarm set or deleted inside a transaction is armed only if that transaction commits |
shardPlacement | unsupported | One process — every shard lives where the process does, so a location hint has nowhere to place it |
shardReadReplicas | unsupported | One process and one region: a replica here would be a second copy of a database already on the same disk |
crossShardFanout | emulated | @lunora/runtime's query coordinator over the in-process shard registry; listShardKeys is seeded from the shard files on disk, and answers every shard rather than only those holding the table (a correct superset, at the cost of visiting shards with nothing to say). That registry is the host's own, so the write-time ShardRegistryDO registration a Cloudflare shard does has nothing to report to here and does not run |
queues | emulated | createNodeQueueHost (@lunora/platform-node) — a QueueBindingLike producer per declared queue over a durable _lunora_queue_messages table, and a batched consumer feeding the same dispatchQueueBatch the Cloudflare host uses. delaySeconds (capped at 24h), all four content types, maxBatchSize/maxBatchTimeout assembly, per-message ack/retry with workerd's implicit-ack-on-return and retry-on-throw, retryDelay, maxRetries into a declared deadLetterQueue (or parked in place, never dropped), and a visibility window so a crash mid-handler redelivers. Delivery is driven by poll(); there is no timer, because this host has no dev server to own one. maxConcurrency is ignored: poll() delivers at most one batch per queue and settles it before moving on. Cloudflare's byte ceilings are enforced on send — 128 KiB per message and 256 KiB per sendBatch, measured over the encoded body — because @lunora/queue leaves both to the platform and this host is the only point where those bytes already exist. mode: "pull" queues are written but not consumed — nothing here serves the HTTP pull endpoint. message.run and ctx.run reach a Lunora function through the scheduler dispatch route, which createNodePlatform serves in-process (no HTTP listener, host-backed through the queue onBatch seam, not a provider API): the app worker's queue export takes it as queueFetchImpl (createWorker), set to platform.dispatch, and the route calls the shard through the platform's directory. The route authenticates with LUNORA_SCHEDULER_SECRET (HMAC) or LUNORA_ADMIN_TOKEN, and refuses workflow and pool targets with a 400. Gap: without queueFetchImpl the call goes to LUNORA_ORIGIN_URL, which nothing on this host answers, so the batch retries until maxRetries sends it to the deadLetterQueue or parks it |
workflows | emulated | createNodeWorkflowHost (@lunora/platform-node) binds each workflow on env under its class name — the key ctx.exports carries on Cloudflare — and compiles defineWorkflow handlers onto the @visulima/workflow engine (createRuntime): step/sleep/waitForEvent are durable + replay-safe, status maps to complete/errored/waiting/terminated, create({ id }) is honoured through a durable alias row (so ctx.spawn resolves and a retried create is one run), and runs survive a restart when backed by createNodeWorkflowStore (a SQLite WorkflowStore; the store is required, so no caller silently gets in-process-only state). step.do's per-step retries and rollbacks are emulated by the adapter, not the engine: the attempt loop runs inside the one memoized step, so a crash mid-backoff restarts that step at attempt 1 rather than resuming the countdown, and compensations are plain calls unwound in reverse declaration order, so the adapter ignores rollbackConfig's retries and a crash mid-unwind leaves it half-done (@lunora/workflow itself still reads rollbackConfig.timeout to end a rollback's decline wait). A retries.delay function is awaited in that same loop and its result replaces the backoff, as on Cloudflare. defineWorkflow's limits and defaultRetention are wrangler settings this host never reads: no per-instance step cap is enforced, and a finished run's state stays until it is deleted. delete and deleteBatch (capped at 100 ids) drop a run's stored state behind the same in-process barrier as terminate, but leave no tombstone, so a deleted run's status reads unknown. terminate is a barrier within the process: a terminated run's writes are dropped, so an activation already in flight cannot overwrite the tombstone — it is not a barrier across processes, which would need the lease rather than a set. Gaps: step.do's config.timeout is not emulated — the callback receives no AbortSignal, so a timeout here could only reject while the work it was meant to cancel kept running. @lunora/workflow still ends a ctx.runStep decline wait 2s before the step's timeout (Cloudflare's 10-minute default when unset), so here that wait charges an attempt the host would not have ended, and the next attempt resumes it; no pause/restart; subscribe rejects NOT_IMPLEMENTED, since the engine keeps no per-instance event log to replay; ctx.run has no in-process seam on this host: createNodeWorkflowHost passes no fetchImpl to createWorkflowRunContext, so it still POSTs to LUNORA_ORIGIN_URL, which nothing here answers; ctx.parallel's synchronous join cannot interleave within one trigger activation |
workflowRollback | emulated | createNodeWorkflowHost unwinds each settled step's rollback in reverse declaration order when a later step fails its last attempt. The compensations are plain calls, not durable steps — a crash during the unwind leaves it half-done — and rollbackConfig is ignored |
scheduler | emulated | SQLite job table dispatched to onDispatch and re-armed on construction, with finite retry backoff and a dead-letter queue. This host's schedule() refuses retry.forever as INVALID_INPUT before a job is persisted or armed. ctx.scheduler does not call schedule(): it posts to the SchedulerDO namespace the app's .scheduler() declaration binds, so whether a ctx.scheduler call can retry forever is decided by what backs that binding, not by this host. It is also the only host implementing runtime cron registration (SchedulerHost.cron), which Cloudflare cannot offer. An app's DECLARED crons are rated separately, under cronTriggers. This rating covers the imperative surface only: ctx.scheduler.runAfter/runAt do dispatch on this host |
relationGraph | emulated | Identical to Cloudflare: the same engine-level traversal over the same ctx.db reads, served here by better-sqlite3 through this host's per-shard handle. One process and one disk, so a deep expansion is if anything cheaper than on workerd; what it is not is a platform feature |
cronTriggers | emulated | createNodePlatform's crons option takes the generated LUNORA_CRONS map and arms each job on the scheduler host's durable cron table, keyed by job name, so two jobs on one schedule and function stay apart and a job the app stops declaring is deleted at the next start. Exactly one process should pass crons; it owns the declared set, and other processes' timers see a changed row only when they next fire. Only a process that passes crons manages that set: one that omits it (an admin script on the same file) neither fires nor deletes declared jobs, and a running server whose declared job another process removed logs that and stops firing it. A schedule with no next occurrence is refused at construction. A tick goes through the same onDispatch delivery a scheduled job does, under its own idempotency id. setTimeout over a durable row, not a platform trigger: a tick that falls while the process is down is skipped, not delivered late, and a failed tick is logged with its job, error and next run, and dropped rather than retried. Schedules are UTC, as on Cloudflare. A run that outlasts the interval skips the ticks it covers instead of overlapping itself, the outcome Cloudflare's per-job lease gives, but with no SchedulerDO the skip is not recorded: there is no run history and no deployment pause. Two processes on one database file both fire every tick. A job that targets a workflow is rated separately, under cronWorkflowTriggers |
cronWorkflowTriggers | unsupported | The scheduler host dispatches a declared cron to a function only: nothing on this host starts a workflow instance from a tick. Gate-bearing: codegen refuses a cronJobs() entry with a workflow target on this target, and createNodePlatform still refuses one at construction as a backstop. Schedule a function that calls ctx.workflows.get(name).create() instead |
authJurisdictionMove | unsupported | Not applicable rather than missing: this host has no jurisdictions. A single process cannot restrict where state lives, so the shard registry offers no jurisdiction() and a worker built for a schema that declares one fails closed at construction. There is never a pinned auth object to copy into, so the admin ops are never wired |
agents | unsupported | Nothing here mounts the generated agent classes: createNodeWorkflowHost compiles defineWorkflow handlers onto the @visulima/workflow engine, and an agent is a generated WorkflowEntrypoint resolved by its class name off ctx.exports or env, and this host binds neither. That missing mount is the whole gap: inference is not, since a model factory or AI SDK model object needs no binding and ai is emulated here through LUNORA_AI_PROXY_URL |
objectStorageBackups | emulated | The commands work unchanged, but the bucket underneath is createNodeR2Bucket — a directory on the same machine the CLI runs on, so a bucket-backed backup here is not the separate failure domain it is on Cloudflare. The scheduled half additionally needs this host's scheduler, which exists but is not a shipping target |
objectStorageCdcArchive | emulated | createNodeR2Bucket implements the startAfter seek the segment index needs, so the read-back behaves as it does on R2. Same caveat as the backups above: the bucket is a directory on the machine running the host, so archiving the changelog here moves it off SQLite but not off the disk that would take the shard with it |
objectStorage | emulated | createNodeR2Bucket (@lunora/platform-node) — an R2BucketLike over the local filesystem (fs/promises, head/list/range). One file per object with the metadata in a trailer, so the single rename that publishes the bytes publishes their checksum and content-type with them, and a get reads body and metadata through one handle rather than reopening the path. put streams into the staged file and .body streams the requested range; .arrayBuffer()/.text() still allocate the range they return. The body is single-use, as R2's is. Keys are percent-escaped per path segment (%, A-Z, :, and a trailing . or space), so A and a stay two objects on a case-insensitive volume exactly as they are on R2, and a lowercase key containing no % or : and no segment ending in . or a space still maps to a byte-identical filename. The limits R2 would apply are applied here rather than left to the deploy to discover: put verifies a declared sha256 against the bytes received and stores nothing on a mismatch, and refuses customMetadata over R2's summed 2048-byte ceiling. Because R2 has no directories, neither does this bucket's behaviour — a deleted key's empty directory is pruned, so a later object may take that prefix, and delete of a key that is only a prefix is the no-op it is on R2 rather than a raw fs error. put honors R2's onlyIf etag preconditions (etagMatches, etagDoesNotMatch, *), checked and published under a per-key lock in this process, and delete takes one key or a batch. No multipart uploads and no presigned URLs, so the binding-backed resumable upload provider (@lunora/storage/upload) finishes only files under 5 MiB here: a larger one needs a multipart upload |
keyValueStore | emulated | better-sqlite3 table behind the ShardKvStore API — not a dedicated KV product |
vectorStore | unsupported | No Vectorize-equivalent binding implemented, so codegen emits neither ctx.vectors nor the backfillVectors override; the admin op answers NOT_IMPLEMENTED, and an index's declared model is accepted but read by nothing |
ai | emulated | No Workers AI-equivalent binding implemented, so @cf/… ids, ctx.ai.run, ctx.ai.websearch and the rejectIfBusy option are unavailable. <provider>/<model> slugs route to the OpenAI-compatible proxy named by the LUNORA_AI_PROXY_URL env var (LiteLLM, OpenRouter, a self-hosted one; bearer token in LUNORA_AI_PROXY_TOKEN) over plain fetch instead of AI Gateway, and a bring-your-own AI SDK model passes straight through. ctx.ai.toMarkdown and @cf/… image ids are unavailable (no binding); ctx.ai.images.generate takes openai/<model> slugs through the proxy, or the provider's own env key without one |
aiSearch | unsupported | No AI Search-equivalent binding implemented, so codegen omits ctx.aiSearch. A REST-backed emulation (account id + API token over fetch) was considered and not built: the REST and binding APIs differ, and nobody on this target has asked for it |
browser | unsupported | No headless-browser binding implemented |
images | unsupported | No Images-equivalent binding implemented |
containers | unsupported | No container orchestration implemented, so there is nothing for ctx.containers.<name>.exec, spawn or terminal to run a command in either |
containerEgressPolicy | unsupported | No container orchestration implemented, so there is no container egress to police |
containerRuntimeScheduling | unsupported | No container orchestration implemented, so there is no image to pick at start and no filesystem to snapshot |
containerSandboxTools | unsupported | No container orchestration implemented, so there is no container filesystem to read, back up or mount a bucket into |
analytics | unsupported | No Analytics Engine-equivalent binding implemented |
analyticsSql | unsupported | No Analytics SQL-equivalent binding implemented, so codegen omits ctx.analyticsSql. Not rated emulated on the strength of createAnalyticsSqlRest: that transport queries Cloudflare's hosted analytics with an API token, so it reads data a Node host never wrote, and an app can import it directly without the ctx surface |
artifacts | unsupported | No Artifacts-equivalent binding implemented: a host would need a Git server with repo-scoped tokens, which no host contract carries |
edgeRequestMetadata | unsupported | Nothing injects per-request platform metadata here — a Node request carries only what the caller wrote. Two telemetry surfaces degrade silently as a result: trustInboundTraceContext: "mtls" can never be satisfied, so it collapses to never-trust and every inbound traceparent is dropped (the runtime warns once when that actually happens, since no codegen gate can see a createWorker option), and the OTLP resource detector finds no placement attributes, so spans ship without them |
hostTraceFusion | unsupported | No host-native trace tree to merge into, and cloudflare:workers is not importable here. Already capability-probed at runtime, so fuseCloudflareTraces is a no-op rather than a throw; onSpan remains the source of truth for the waterfall either way |
logArchive | unsupported | createNodeR2Bucket is a directory on the local filesystem with no Iceberg catalog over it and no SQL engine to query it back, so records could be written but never read. The admin route is still registered here: it answers LOG_ARCHIVE_NOT_CONFIGURED (which the studio renders as a not-configured empty state) only while the logArchive table or the R2 SQL credentials are absent. Configure both and it stops failing closed — it builds an R2 SQL client and queries Cloudflare's API over the network, which is not this host serving the archive |
pipelines | unsupported | No Pipelines-equivalent binding implemented |
pointInTimeRecovery | unsupported | better-sqlite3 keeps no change log to rewind, and createNodeShardState deliberately exposes no bookmark methods rather than a stub that would report a restore that never happened, so getPitrBookmark / pitrRestore answer PITR_UNAVAILABLE. Recover from lunora backup snapshots instead (objectStorageBackups) |
adminTokenRevocation | unsupported | Nothing on this host binds the AdminRevocationDO namespace (createWorker adminRevocations), so no named admin token can be created and any that exist are refused (ADMIN_TOKEN_NOT_CONFIGURED); the root LUNORA_ADMIN_TOKEN is the only admin credential. There is no point-in-time restore here to revive a revoked token either |
mail | unsupported | The queue tier this host lacked when the rating was written now exists (createNodeQueueHost), but nothing here composes a @lunora/mail transport or the queued-send consumer, so a send would be accepted and never delivered |
secrets | emulated | createNodeSecretBindings(names) (@lunora/platform-node) builds one binding per named secret over process.env, spread into the env the worker and shard are built over, so ctx.secrets.get(name) reads that variable when called and rejects if it is unset or empty. Only listed names are bound, as only listed secrets_store_secrets[] are on Cloudflare, and any name with the reserved LUNORA prefix is refused: the runtime reads those env vars as plain strings, which a binding spread over one would replace. Emulated, not native: environment variables are not a secrets store, so a value is plaintext to anything that can read the process environment, there is no per-secret access control or audit, and a rotated value needs a restart |
secretValues | unsupported | No store for human-supplied values. Agents are unsupported on this target (see agents), so nothing requests one, and no plaintext node store is built: a value written to local disk would be unencrypted |
services | unsupported | No sibling-Worker host: a Node process runs one app, with nothing a service binding could point at. Gate-bearing, so codegen omits ctx.services instead of emitting bindings that resolve to nothing |
topics | emulated | Each subscription is a createNodeQueueHost queue, so a publish is one durable insert per subscription into _lunora_queue_messages. A subscription handler's message.run goes through the same in-process dispatch route as the queues row, and needs the same wiring |
hyperdrive | emulated | createNodeHyperdrive (@lunora/platform-node) builds the HYPERDRIVE binding from DATABASE_URL (postgres:, postgresql:, mysql: or mariadb:, plus the libpq Unix-socket form postgres:///db?host=/socket/dir), so the app's own .hyperdrive((env) => …) wiring builds ctx.sql from it unchanged. A URL with any TLS option other than an explicit off (sslmode=prefer or require, ssl=true, sslrootcert=…) keeps it in connectionString only: Cloudflare's binding has no TLS field to mirror, so the binding's discrete host/port/user/password/database fields throw rather than let a driver built from them connect without TLS; sslmode=disable and ssl=false keep them. Emulated, not native: nothing sits between the driver and the database, so there is no edge connection pool and no query cache, and the driver's own pool settings are the only ones that apply |
httpCache | unsupported | Nothing sits in front of this host to cache its responses, and Node exposes no Web Cache API global — the runtime's REST edge cache finds no HttpCacheLike here and degrades to emitting Cache-Control alone, which browsers and any CDN in front still honour |
requestOrigin | emulated | The same runtime code reads it off request.url, but nothing here serves HTTP: the embedding server builds that Request, usually from the Host header the caller sent. Pin the host in the proxy in front, or configure a base (publicBaseUrl / STORAGE_PUBLIC_BASE_URL), which always wins over the origin. Because the caller can choose it here, never build links delivered to OTHER people from ctx.origin (password-reset or invite emails, webhooks, notifications): that is host-header poisoning. Use a configured canonical base URL for those; a signed URL returned to the same caller is fine |
identityProxy | unsupported | Nothing sits in front of this host to authenticate callers, so it never populates the execution context's access identity. @lunora/cloudflare-access still works here through its Cf-Access-Jwt-Assertion fallback, which is a plain header check and needs no host support |
workflowSchedules | unsupported | createNodeWorkflowHost only runs instances something creates: nothing reads a workflow's schedules list, so a scheduled workflow would never start. Gate-bearing: codegen refuses an app that declares one here. Start it from a mutation with ctx.workflows.get(name).create() instead, re-armed through ctx.scheduler.runAt |
Almost nothing here is rated native, and that is the matrix's own definition
doing its job rather than a hedge: native means the platform itself provides
the feature, and a bare Node process provides essentially none of them.
localSql is the exception, because SQLite genuinely is the platform primitive
there.
What it is for today
Dev and test. It exists to run the same conformance suite
(@lunora/platform/conformance, @lunora/shard-engine/conformance) against a
second host so portability is a construction check rather than a claim, and it
is a useful in-process double for exercising app code without Cloudflare
credentials. It is not wired into lunora dev, deploys only as the container
lunora deploy --target node writes (one process, which you host), and the
capabilities above (one process, no distributed placement or failover, no
Cloudflare product bindings) mean it is not a substitute for the Cloudflare
host in anything that needs them.
On-demand profiling
createNodeProfileHandler({ token }) captures a CPU or heap profile of the
running process through the built-in node:inspector Session, wrapped in
promises, with no native addon and no flag at boot. It serves the result as a
gzip pprof that go tool pprof, Pyroscope and Speedscope read. The app mounts
the handler on a bearer-guarded POST route of its own choosing, and
lunora profile --target node --url <route> calls it. A CPU capture only sees work that runs during the window. A heap capture
reports the allocations still live when it stops. Functions V8 had already
inlined before a CPU capture began can appear under their caller rather than
under their own name.
The profiler runs one capture at a time per process, and the handler refuses an
empty token when it is created. Profiling is not a ctx.* surface or binding,
so it has no entry in PlatformCapabilities.
Known divergences
node-kv-store's serializer is not Cloudflare's, and is not even a stable
wire format on its own. ShardKvStore.put's contract says a value must be
structured-clonable and hosts serialize it durably, without pinning a wire
format. Cloudflare's state.storage uses the platform's own structured-clone
implementation. This host stores values as node:v8's serialize/deserialize
output, the same structured-clone algorithm V8 uses for postMessage and
structuredClone itself, so it round-trips Date, Map, Set, RegExp, and
typed arrays, genuinely closer to Cloudflare's fidelity than JSON.stringify
would be. But node:v8's format is explicitly documented by Node as not a
stable cross-version wire format: a value written under one Node/V8 version is
not guaranteed to deserialize under another. A SQLite file carried across a
Node upgrade can fail to read back values it wrote. See
packages/platform-node/src/node-kv-store.ts and
plans/234-node-host-findings.md.
API
Every public export of src/index.ts, plus the conformance entry point.
createNodePlatform
Type: (options?: NodePlatformOptions<Queues, Workflows>) => NodePlatform<Queues, Workflows>
Composes every contract this package provides over one better-sqlite3 database
file. The queues, workflows, objectStorage and globalTables members are
undefined when the matching option (queues, workflows,
objectStorageDirectory, globalTablesPath) is omitted. Call drain() and then
close() for a graceful shutdown. After close(), scheduler.schedule() and
shard.alarms.set() throw.
NodePlatform
Type: interface
The object createNodePlatform returns. It exposes shard, kv, sockets,
scheduler, directory, dispatch, capabilities, drain, close and
[Symbol.dispose]. drain also drains the registry's shards (see
createNodeShardRegistry), plus the optional queues, workflows, objectStorage and
globalTables members described above.
NodePlatformOptions
Type: { crons?, dispatch?, globalTablesPath?, objectStorageDirectory?, onQueueBatch?, queues?, workflows? } & NodeSchedulerHostOptions & NodeShardHostOptions & NodeShardRegistryOptions
The options for createNodePlatform. The shard host reads path, shardKey and
onAlarm, the scheduler reads onDispatch, and the shard registry reads
directory, onAlarm and onFetch. queues requires onQueueBatch, which the
platform calls for each assembled batch.
Run exactly one process with crons: it owns the declared set. Processes do
not notify each other when a row changes, so a server only sees another
process's edit when its own timer next fires and re-reads the row. A job moved
to a more frequent schedule misses the ticks before then.
crons takes the generated LUNORA_CRONS map and is the app's whole declared
cron set: each job is armed on the scheduler and delivered through onDispatch
(or, with onFetch, straight to the shard), and a job an earlier run declared
that is missing from the map is deleted. Only a process that passes crons
manages that set: one that omits it, such as an admin script opening the same
file, neither fires nor deletes declared jobs. A running server whose declared
job another process removed logs a warning and stops firing it. Crons registered
through scheduler.cron() are re-armed either way. A failed tick is logged with
its job, error and next run time, and the schedule carries on.
Schedules are read as UTC, as Cloudflare's are, and a run that outlasts the
interval skips the ticks it covers instead of overlapping itself. Construction
throws for a job that targets a workflow (nothing on this host starts a workflow
instance from a tick), for two jobs with the same name, for a schedule with no
next occurrence (0 0 31 4,6,9,11 *), and for a non-empty map
when neither onFetch nor onDispatch is given.
NodePlatformDispatchOptions
Type: { adminToken?: string; schedulerSecret?: string }
The secrets the dispatch route checks. adminToken must match the
LUNORA_ADMIN_TOKEN the queue caller sends. schedulerSecret verifies a signed
scheduler body. With neither set, the route refuses every request.
createNodeDispatchRoute
Type: (options: NodeDispatchRouteOptions) => (request: Request) => Promise<Response>
Builds the in-process dispatch route. Mount the returned handler at
NODE_SCHEDULER_DISPATCH_PATH yourself. The route does not register a path.
NODE_SCHEDULER_DISPATCH_PATH
Type: "/_lunora/scheduler/dispatch"
The path @lunora/dispatch and @lunora/scheduler post to.
createNodeGlobalStore
Type: (options?: NodeGlobalStoreOptions) => NodeGlobalStore
Creates the .global() backend on its own SQLite file, using the
@lunora/sql-store core. writer(options) returns the createSqlCtxDb facade
that a shard's d1 thunk expects.
createNodeSqlExec
Type: (database: Database.Database) => SqlCtxExec
Builds the SQL executor over a better-sqlite3 connection. Its transaction
holds BEGIN IMMEDIATE open across the awaits of an async closure.
DrainOptions, DrainResult, DrainTimer, DEFAULT_DRAIN_TIMEOUT_MS
Type: interfaces and a constant
What every drain() in this package takes and returns. timeoutMs bounds the
drain (DEFAULT_DRAIN_TIMEOUT_MS, 30 s, when omitted; a value that is not a
whole number from 0 to 2147483647 ms throws a RangeError, since Node would run
a longer timer after 1 ms), and timer replaces the
clock it runs on, so a test can fire the deadline by hand. The default timer is
referenced while the drain runs: a drain waiting on a promise with no I/O behind
it (a stalled shard waitUntil) keeps the process alive until the deadline
fires, instead of letting it exit silently. NodePlatform.drain() runs its host
and registry drains under that one deadline, repeating until both are idle at the
same instant, since host work can start shard work after the registry drained.
Scheduler deliveries count as busy work too: a scheduled job or cron tick
running through onDispatch (yours or the built-in one) is waited for until the
scheduler has recorded its outcome, and named if the deadline passes first. A DrainResult
reports timedOut, the pending work still running when the deadline passed,
and the work that failed while the drain waited (an alarm retry that could not
be written), one readable label each. Each failure is also logged with its cause
when it happens, and drains wait with settled semantics, so one failure never
stops them waiting for the rest.
createNodeHttpServer
Type: (options: NodeHttpServerOptions) => Promise<NodeHttpServer>
Serves an app worker's fetch over node:http and resolves once the server is
listening. fetch is required. host defaults to the loopback interface. A
handler that throws is answered with 500 and logged with its error, its method
and its path (never the query string, which can carry a token). drain() stops
the listener, then waits until every response that was in progress when it
began is written or its client is gone; a request still arriving on an open
connection is answered with Connection: close and not waited for. Event
streams and WebSockets are not waited for, and close() ends them. It is
bounded by a deadline (see DrainOptions, checked before anything is stopped, so an invalid one leaves the server serving) and resolves with what was still
unfinished, which it also logs. A graceful shutdown refuses new requests in its
fetch, awaits drain(), then close().
createNodeHyperdrive
Type: (url?: string) => NodeHyperdriveBinding
Builds the HYPERDRIVE binding from a postgres://, postgresql://,
mysql:// or mariadb:// URL, process.env.DATABASE_URL unless given. A
Postgres URL may name a Unix socket the libpq way, postgres:///db?host=/var/run/postgresql,
and the socket directory becomes host. Without a port in the authority, a
Postgres ?port= (1 to 65535) sets port; the authority's port wins when both are set. A URL with any TLS option other than an
explicit off (sslmode=prefer or require, ssl=true, sslrootcert=…) keeps it
only in connectionString; the binding's discrete fields throw instead of letting
a driver built from them connect without TLS, so build the driver from
connectionString. sslmode=disable and ssl=false keep the discrete fields. Put it on the env
under the binding name the app reads, and the app's .hyperdrive((env) => …)
wiring builds ctx.sql from it unchanged. There is no pool or query cache in
front of the database: the driver connects to it directly.
createNodeProfileHandler
Type: ({ token }: NodeProfileHandlerOptions) => NodeProfileHandler
Builds a fetch-style handler that captures a CPU or heap profile of the running
process. It accepts POST requests with Authorization: Bearer <token>. The
token option is required and non-empty, and creating the handler throws when it
is empty.
NodeProfileHandlerOptions
Type: { token: string }
The bearer token the profile handler checks, compared as SHA-256 digests.
createNodeQueueHost
Type: <Queues>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>
Creates the queue host over the _lunora_queue_messages table, with one producer
binding per declared queue. Delivery runs on poll(), because the host owns no
timer.
createNodeR2Bucket
Type: (options: NodeR2BucketOptions) => R2BucketLike
Creates a bucket over a local directory, with one file per object. Use it with
createStorage({ bucket, bucketName }).
createNodeSchedulerHost
Type: (database: Database.Database, options?: NodeSchedulerHostOptions) => NodeSchedulerHost
Creates a scheduler whose jobs persist in a SQLite table and re-arm on
construction. onDispatch receives due jobs. Its schedule() refuses
retry.forever. Besides the SchedulerHost it returns declareCrons(crons),
which replaces the declared cron set (keyed by job name) and leaves crons
registered through scheduler.cron() alone.
createNodeSecretBindings
Type: (names: ReadonlyArray<string>, source?: Record<string, string | undefined>) => Record<string, NodeSecretBinding>
Builds the ctx.secrets bindings from environment variables (process.env
unless source is given): one binding per name, to spread into the env the
worker and shard are built over. ctx.secrets.get(name) reads the variable when
called and rejects if it is unset or empty. Only the listed names are bound, so
the plain strings the env already carries (LUNORA_ADMIN_TOKEN and the like)
stay strings. A LUNORA_* name throws: the runtime reads those env vars as plain
strings across many modules, so the whole prefix is reserved.
createNodeShardHost
Type: (options?: NodeShardHostOptions) => { database, dispose, drain, host }
Creates the single-writer shard host over a better-sqlite3 database. path is
the database file. dispose() clears the pending alarm timer and closes the
database together.
createNodeShardKvStore
Type: (database: Database.Database) => ShardKvStore
Builds the key-value store over a better-sqlite3 table in the shard's database.
Values use node:v8 serialization, so see Known divergences.
createNodeShardNamespace
Type: (directory: DirectShardDirectory) => ShardNamespaceLike
Presents a shard registry as the namespace a worker is built over
(createWorker({ shardDO })). Both idForName and idFromName return the key
itself.
createNodeShardRegistry
Type: (options?: NodeShardRegistryOptions) => NodeShardRegistry
Builds the in-process shard registry. directory names the folder that holds one
SQLite file per shard. Omit it for in-memory shards, which do not survive a
restart. onAlarm and onFetch are the registry's delivery hooks. drain()
waits until every shard is idle: no onFetch or onAlarm call in flight (cron
and scheduled-job deliveries included), no waitUntil work pending and no socket
close handler running. Each pass re-reads every live shard, so work handed to a
shard after its own drain finished, or a shard opened while draining, is seen;
Alarm deliveries count until their retry, if any, is written, so a shutdown
cannot lose a failed alarm. A retry waiting for another task's transaction to end
always settles: it is written once the transaction ends, superseded by a later
set or delete, or, if the shard closes first, given up and logged. A retry
write that fails (contention from another process) is tried again with backoff
before the alarm is given up and logged. idle() answers the same question synchronously.
It returns only when a full pass finds nothing running, or when its deadline
passes, logging one line per shard with how many requests, alarms and
waitUntil tasks it still had (never the request or its payload). Await it before close(), which does not wait. close({ force: true }), for
after a drain has finished or reached its deadline, disposes a shard whose socket
close handler is still running instead of waiting for it, and logs it. A shard
that fails to close does not stop the others: every one is tried, each failure is
logged, and close() then throws one AggregateError naming them.
NodePlatform.close() runs all of its teardowns the same way.
rearmPersistedAlarms() (on the registry and on NodePlatform) opens every
stored shard that has a persisted alarm, so a restarted process fires it without
waiting for a request to that shard; call it once before taking traffic. Shards
without an alarm stay closed. idle() reports synchronously whether anything a
drain would wait for is running, and drainTogether(parts, options) drains
several registries or platforms under one deadline until all are idle in the same
pass, since work on one can start work on another after it drained.
createNodeShardState
Type: (shard: NodeShard) => NodeShardState
Builds the DurableObjectState-shaped object for a shard. It omits the native
point-in-time-recovery methods, so getPitrBookmark and pitrRestore answer
PITR_UNAVAILABLE.
bindShardSockets
Type: (shard: ShardSocketHooks, inbound: Pick<NodeShard["inbound"], "onClose" | "onMessage">) => void
Delivers a shard's inbound socket events. Call it once for each shard instance,
at the point where you build the shard. Cloudflare calls webSocketMessage and
webSocketClose for you, but Node does not.
createNodeSocketHost
Type: (database: Database.Database) => NodeSocketHost
Builds the socket registry. Attachments and tags persist to database. The
returned socket member implements SocketHost.
createNodeWorkflowHost
Type: <Workflows>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>
Compiles each declared workflow onto the @visulima/workflow engine. It requires
a store from createNodeWorkflowStore, so runs survive a restart.
createNodeWorkflowStore
Type: (database: Database.Database) => WorkflowStore
Builds the durable workflow store over a better-sqlite3 connection. Pass the
result to createNodeWorkflowHost({ store }).
createNodeConformanceHost
Type: () => ConformanceHost
Imported from @lunora/platform-node/conformance. Builds a fresh host over an
in-memory better-sqlite3 database for one run of the @lunora/platform
conformance suite.
NodeShardRegistryOptions
Type: { directory?: string; onAlarm?: (shard: NodeShard) => Promise<void> | void; onFetch?: (request: Request, shard: NodeShard) => Promise<Response> | Response }
Options for createNodeShardRegistry. Omit directory for in-memory shards.