@lunora/platform-node 1.0.0-alpha.21 → 1.0.0-alpha.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +7 -0
  2. package/dist/conformance/index.mjs +1 -1
  3. package/dist/index.d.mts +397 -147
  4. package/dist/index.d.ts +397 -147
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/NODE_SCHEDULER_DISPATCH_PATH-C3-wCHPp.mjs +1 -0
  7. package/dist/packem_shared/bindShardSockets-9GvSocBW.mjs +1 -0
  8. package/dist/packem_shared/createNodeGlobalStore-CD4DiqeS.mjs +1 -0
  9. package/dist/packem_shared/createNodeHttpServer-D4YVdhJn.mjs +4 -0
  10. package/dist/packem_shared/createNodePlatform-CuZZbfWJ.mjs +1 -0
  11. package/dist/packem_shared/createNodeProfileHandler-MX5xKPg0.mjs +1 -0
  12. package/dist/packem_shared/createNodeQueueHost-CttDb5sY.mjs +17 -0
  13. package/dist/packem_shared/createNodeR2Bucket-D_jsnenX.mjs +1 -0
  14. package/dist/packem_shared/createNodeSchedulerHost-CiSdzxod.mjs +15 -0
  15. package/dist/packem_shared/createNodeShardHost-Bhbm4txQ.mjs +1 -0
  16. package/dist/packem_shared/createNodeShardNamespace-BgQjDv7V.mjs +1 -0
  17. package/dist/packem_shared/createNodeShardRegistry-BKl1QXiv.mjs +1 -0
  18. package/dist/packem_shared/createNodeSocketHost-ByOmEGFe.mjs +2 -0
  19. package/dist/packem_shared/createNodeWorkflowHost-B76TKiw_.mjs +1 -0
  20. package/dist/packem_shared/hmac-url-Bogwm7I6.mjs +1 -0
  21. package/dist/packem_shared/node-socket-pair-0baNnoFw.mjs +1 -0
  22. package/dist/packem_shared/prepared-statement-3XBQZXtC.mjs +1 -0
  23. package/package.json +15 -9
  24. package/dist/packem_shared/createNodeGlobalStore-Cwi33XOk.mjs +0 -1
  25. package/dist/packem_shared/createNodePlatform-1fAQ_biu.mjs +0 -1
  26. package/dist/packem_shared/createNodeQueueHost--mBLGSxF.mjs +0 -17
  27. package/dist/packem_shared/createNodeR2Bucket-CmHYlIni.mjs +0 -1
  28. package/dist/packem_shared/createNodeSchedulerHost-vZgv1CEo.mjs +0 -15
  29. package/dist/packem_shared/createNodeShardHost-C0j8nvSU.mjs +0 -1
  30. package/dist/packem_shared/createNodeShardRegistry-DKdc0pV8.mjs +0 -1
  31. package/dist/packem_shared/createNodeShardState-CpUzvWwd.mjs +0 -1
  32. package/dist/packem_shared/createNodeSocketHost-DK3X5PlQ.mjs +0 -2
  33. package/dist/packem_shared/createNodeWorkflowHost-CTVBYiuj.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -1,9 +1,43 @@
1
1
  import { SchemaLike } from '@lunora/shard-engine';
2
2
  import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
3
3
  import Database from 'better-sqlite3';
4
- import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike, SocketHandle } from '@lunora/platform';
4
+ import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike } from '@lunora/platform';
5
5
  import { WorkflowBindingLike } from '@lunora/workflow';
6
6
  import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
7
+ import { ShardNamespaceLike } from '@lunora/runtime';
8
+ /** One function call the route has authenticated and parsed. */
9
+ interface NodeDispatchInvocation {
10
+ args: Record<string, unknown>;
11
+ functionPath: string;
12
+ /** The scheduler record or delivery id, used as the shard's idempotency key. */
13
+ id: string | undefined;
14
+ /** Identity the trusted caller forwarded, if any. */
15
+ identity: {
16
+ identity?: string;
17
+ userId?: string;
18
+ } | undefined;
19
+ shardKey: string;
20
+ traceparent: string | undefined;
21
+ }
22
+ interface NodeDispatchRouteOptions {
23
+ /** `LUNORA_ADMIN_TOKEN`. Used as the bearer when no HMAC signature is presented. */
24
+ adminToken?: string;
25
+ /** The shard a body without `shardKey` is sent to. */
26
+ defaultShardKey: string;
27
+ /** Runs the call in-process and returns the shard's response, unchanged. */
28
+ invoke: (call: NodeDispatchInvocation) => Promise<Response>;
29
+ /** `LUNORA_SCHEDULER_SECRET`. When set, a signed request is verified against it. */
30
+ schedulerSecret?: string;
31
+ }
32
+ /**
33
+ * Build the dispatch route. The returned function answers any request it is
34
+ * handed; mounting it at {@link NODE_SCHEDULER_DISPATCH_PATH} is the caller's job.
35
+ * With neither secret configured every request is refused, so an unconfigured
36
+ * route fails closed.
37
+ */
38
+ declare const createNodeDispatchRoute: (options: NodeDispatchRouteOptions) => ((request: Request) => Promise<Response>);
39
+ /** The path `@lunora/dispatch` and `@lunora/scheduler` POST to. */
40
+ declare const NODE_SCHEDULER_DISPATCH_PATH: "/_lunora/scheduler/dispatch";
7
41
  /**
8
42
  * The Node store options — the shared store options minus the two this binding
9
43
  * owns. `dialect` is fixed (SQLite) and `exec` is the store's own connection;
@@ -14,13 +48,21 @@ type NodeGlobalContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect" | "exec"
14
48
  /**
15
49
  * Wrap a `better-sqlite3` connection as the async exec the store core consumes.
16
50
  *
17
- * `batch` is deliberately **not** implemented. The contract lets an exec that
18
- * omits it fall back to a sequential `run()` loop, and that fallback is already
19
- * optimal here: `batch` exists to collapse network round trips (D1 does it
20
- * atomically in one request; the Hyperdrive adapters dispatch concurrently over
21
- * a pool), and an embedded database has no round trip to collapse. Declaring it
22
- * would buy nothing and would opt this exec into the "MAY reorder or
23
- * parallelize" licence for no reason.
51
+ * `batch` runs the statements in order inside one `better-sqlite3`
52
+ * transaction, which is synchronous, so nothing else runs between them. There is
53
+ * no round trip to save; atomicity is the point. The store core's FTS5 search
54
+ * companion writes each document as an ordered list of statements, and without
55
+ * this two async writers interleaved at every `await` between them: one could
56
+ * move a document's mapping while the other's entry was mid-write, leaving an
57
+ * entry no later write or purge could reach. The `sqlite` dialect's contract
58
+ * requires an ordered, atomic `batch` for exactly that reason.
59
+ *
60
+ * `transaction` holds `BEGIN IMMEDIATE` … `COMMIT` open across the awaits of
61
+ * an async `work`, which `better-sqlite3`'s own synchronous `transaction()`
62
+ * cannot. The connection is shared, so while one is open every other statement
63
+ * waits for it to settle: run in between, another writer's statement would land
64
+ * inside it and be rolled back with it. The wait and the statement (or the
65
+ * `BEGIN`) run with no `await` between them, so nothing slips in after the check.
24
66
  */
25
67
  declare const createNodeSqlExec: (database: Database.Database) => SqlCtxExec;
26
68
  /** Options for {@link createNodeGlobalStore}. */
@@ -63,6 +105,32 @@ interface NodeGlobalStore {
63
105
  * which is the whole point of the dialect seam.
64
106
  */
65
107
  declare const createNodeGlobalStore: (options?: NodeGlobalStoreOptions) => NodeGlobalStore;
108
+ /** Serve `options.fetch` over `node:http`. Resolves once the server is listening. */
109
+ declare const createNodeHttpServer: (options: NodeHttpServerOptions) => Promise<NodeHttpServer>;
110
+ /** Options for {@link createNodeHttpServer}. */
111
+ interface NodeHttpServerOptions {
112
+ /** The app worker's `fetch`, already bound to its env and context. */
113
+ fetch: (request: Request) => Promise<Response> | Response;
114
+ /** Host to bind. Defaults to the loopback interface. */
115
+ host?: string;
116
+ /**
117
+ * The public base URL the app is served at, e.g. `https://app.example`. Every request URL uses its origin, so origin-sensitive
118
+ * behaviour (CSRF, WebSocket origin checks, cookie rules) sees the public scheme behind a TLS proxy. The client's `Host` header is
119
+ * never used. Defaults to the bound `http://host:port`, which is only allowed for a loopback `host`: binding a non-loopback address
120
+ * (e.g. `0.0.0.0` or a LAN IP) without `origin` makes {@link createNodeHttpServer} reject, because browsers would send that address
121
+ * as `Origin` and fail the CSRF check. Set `origin` to the URL users open.
122
+ */
123
+ origin?: string;
124
+ /** Port to bind. `0` (the default) picks a free ephemeral port. */
125
+ port?: number;
126
+ }
127
+ /** A listening server. */
128
+ interface NodeHttpServer {
129
+ /** Stop accepting connections and end every open one, streams included. */
130
+ close: () => Promise<void>;
131
+ /** The `http://host:port` origin the server answers on. */
132
+ origin: string;
133
+ }
66
134
  /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
67
135
  declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
68
136
  /** Options for {@link createNodeQueueHost}. */
@@ -146,7 +214,7 @@ interface NodeSchedulerHostOptions {
146
214
  * A handler that **throws** marks the delivery failed, which is what drives
147
215
  * the retry/dead-letter machinery: the job's `attempts` increments and it is
148
216
  * either re-armed with backoff or parked. A handler that resolves marks the
149
- * job delivered and removes it.
217
+ * job `succeeded`.
150
218
  *
151
219
  * Omitting it makes every delivery trivially succeed, which means a caller
152
220
  * who forgets to pass one gets a scheduler that quietly drops work — the
@@ -197,9 +265,12 @@ interface NodeShardHostOptions {
197
265
  * `_lunora_alarm` when the host is constructed over an existing database,
198
266
  * including an alarm whose time elapsed while nothing was running.
199
267
  *
200
- * A handler that throws is isolated to its own delivery; it never reaches
268
+ * A handler that throws is isolated to its own delivery — it never reaches
201
269
  * the caller that set the alarm, because by then that call has long
202
- * returned.
270
+ * returned — and the wakeup is then re-delivered with backoff up to
271
+ * {@link ALARM_RETRY_LIMIT} times, the way workerd retries a throwing
272
+ * `alarm()`. Delivery is at-least-once, so the handler must tolerate
273
+ * running twice for one scheduled timestamp.
203
274
  */
204
275
  onAlarm?: () => Promise<void> | void;
205
276
  /**
@@ -218,25 +289,59 @@ interface NodeShardHostOptions {
218
289
  /**
219
290
  * Build a `ShardHost` over a real `better-sqlite3` database.
220
291
  *
221
- * `runSerialized` chains onto a single `tail` promise rather than the
222
- * reference host's explicit job-array-plus-drain-loop: every queued closure
223
- * runs once `tail` settles, and `tail` is reset to a version that always
224
- * resolves (never rejects) so one job's failure cannot wedge the queue for
225
- * every job after it — the same "no two closures interleave" guarantee,
226
- * fewer moving parts to get wrong.
292
+ * `runSerialized` and `transaction` share **one** boundary lock, because they
293
+ * write **one** `better-sqlite3` connection. `transaction` issues raw
294
+ * `BEGIN`/`COMMIT`/`ROLLBACK` — legal here (unlike inside a Cloudflare Durable
295
+ * Object, where the runtime forbids it and callers must use
296
+ * `storage.transaction`) because better-sqlite3 is a plain embedded database
297
+ * with no platform-level transaction primitive layered over it.
298
+ *
299
+ * ## Why one lane and not two
300
+ *
301
+ * This host shipped with two private tail chains, one per entry point, so each
302
+ * serialized against itself and neither against the other. `runSerialized`
303
+ * issues no `BEGIN` of its own, so one of its closures overlapping a bare
304
+ * `transaction()` wrote straight into that transaction's span. `assertOwnTurn`
305
+ * below catches the write — it is the only reason this host never silently lost
306
+ * one the way an unguarded connection would — but catching it is not the same
307
+ * as preventing it, and the refusal lands in the wrong place:
227
308
  *
228
- * `transaction` issues raw `BEGIN`/`COMMIT`/`ROLLBACK` — legal here (unlike
229
- * inside a Cloudflare Durable Object, where the runtime forbids it and
230
- * callers must use `storage.transaction`) because better-sqlite3 is a plain
231
- * embedded database with no platform-level transaction primitive layered over
232
- * it. It runs on its own private `transactionTail` chain, the same shape as
233
- * `runSerialized`'s but never shared with it: two bare, overlapping
234
- * `transaction()` calls on this host serialize against each other rather than
235
- * corrupting each other's commits (raw `BEGIN` on a connection already inside
236
- * a transaction throws, or worse, interleaves). Routing `transaction` through
237
- * `runSerialized` itself would deadlock, since the engine already composes
238
- * `runSerialized(() => transaction(work))` — the inner enqueue would then wait
239
- * on the outer closure awaiting it.
309
+ * 1. A `runSerialized` closure writes a row. Nothing is open, so it commits.
310
+ * 2. It awaits (a scheduler hop, an `onShardInit` read, any real I/O).
311
+ * 3. A bare `transaction()` runs `BEGIN` while it is parked. `transaction` is
312
+ * a public contract surface, and `./node-shard-state` re-exports it as the
313
+ * `storage.transaction` member `ShardDO` documents as "the platform
314
+ * primitive", so a subclass reaches one without going through the engine.
315
+ * 4. The closure resumes and its next write is refused with
316
+ * `SHARD_UNAVAILABLE`, so `runSerialized` **rejects** — with step 1 already
317
+ * durable.
318
+ *
319
+ * The boundary the contract promises is atomic-or-nothing to its caller tore in
320
+ * half: a rejection the caller will retry, on top of a write the retry now
321
+ * re-applies. That is `runSerialized`'s "no two closures interleave" guarantee
322
+ * broken by a `transaction` it was never serialized against.
323
+ *
324
+ * ## Why the lock is re-entrant, and why `AsyncLocalStorage` is what makes it so
325
+ *
326
+ * The engine composes the two, and stacks them: `ShardRunner.runInTransaction`
327
+ * is `runSerialized(() => transaction(work))` (`@lunora/shard-engine`), and
328
+ * `ShardDO.fetch` widens a mutation dispatch carrying `x-lunora-mutation-id`
329
+ * into a *further* `runSerialized` span around it (`@lunora/do`). Under two
330
+ * plain FIFO chains that outer span is already fatal on this host — the inner
331
+ * `runSerialized` waits on a `tail` that only settles when the outer closure it
332
+ * is running inside resolves, and because nothing ever resets that `tail`, the
333
+ * shard's write lane is wedged for the life of the process rather than for the
334
+ * life of the request.
335
+ *
336
+ * So the lock is skipped for a boundary opened from inside a boundary, and
337
+ * `AsyncLocalStorage` is the only thing that can tell that case from the one
338
+ * that must queue: its store follows a single call's own await chain without
339
+ * leaking into a sibling chain. A held boolean cannot — it reads `true` for an
340
+ * unrelated *second top-level* `transaction()` too, which would then nest a raw
341
+ * `BEGIN` on a connection already inside one. This is the same distinction
342
+ * workerd's `blockConcurrencyWhile` draws natively with "does not queue events
343
+ * initiated as part of the callback itself", which is what
344
+ * `@lunora/platform-cloudflare` leans on for the identical composition.
240
345
  *
241
346
  * The returned `dispose()` is this host's lifecycle owner: it clears the
242
347
  * pending alarm `setTimeout` (so it can never fire against a connection this
@@ -252,8 +357,55 @@ declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
252
357
  drain: () => Promise<void>;
253
358
  host: ShardHost;
254
359
  };
360
+ /** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
361
+ interface NodeServerEnd {
362
+ close: (code?: number, reason?: string) => void;
363
+ send: (data: string | ArrayBuffer) => void;
364
+ }
365
+ /**
366
+ * The socket-host half of a Node platform instance, plus the test-only hooks
367
+ * `@lunora/platform/conformance`'s `ConformanceHost` needs to drive a recycle
368
+ * from inside a test.
369
+ */
370
+ interface NodeSocketHost {
371
+ /**
372
+ * Wait for every close handler still running, including ones they start. `undefined` when none are,
373
+ * so a caller can dispose synchronously.
374
+ */
375
+ drain: () => Promise<void> | undefined;
376
+ /** Deliver a connection's close to `handler`, which calls `webSocketClose`. One handler per host. */
377
+ onClose: (handler: (socket: NodeServerEnd, code: number, reason: string, wasClean: boolean) => void | Promise<void>) => void;
378
+ /**
379
+ * Deliver a connection's inbound frames to `handler`. The handler is the
380
+ * shard that accepted the connection, so it calls `webSocketMessage`. One
381
+ * handler per host: a later call replaces the earlier one.
382
+ */
383
+ onMessage: (handler: (socket: NodeServerEnd, data: string | ArrayBuffer) => void) => void;
384
+ /** Read back the frames sent to a socket, oldest first, text frames only. */
385
+ readFrames: (handle: SocketHandle) => string[];
386
+ /**
387
+ * Re-create a runtime socket from durable state.
388
+ *
389
+ * `attachment` is a fallback only: this host restores what it persisted,
390
+ * because that is what a real wake looks like. The argument covers an id
391
+ * this host never durably tracked (a synthetic id a test constructs).
392
+ */
393
+ restoreSocket: (id: string, attachment: unknown) => SocketHandle;
394
+ /** Drop the runtime socket map while keeping durable attachments/tags. */
395
+ simulateRecycle: () => void;
396
+ /** The `SocketHost` contract implementation. */
397
+ socket: SocketHost;
398
+ }
399
+ /** Build the socket registry, persisting attachments and tags to `database`. */
400
+ declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
255
401
  /** The contracts scoped to one shard key. */
256
402
  interface NodeShard {
403
+ /**
404
+ * Inbound socket events for this shard's registry. Bind the shard that owns
405
+ * the sockets here, so a frame or close reaches its `webSocketMessage` and
406
+ * `webSocketClose`. See `bindShardSockets`.
407
+ */
408
+ inbound: Pick<NodeSocketHost, "onClose" | "onMessage">;
257
409
  /** Durable key-value storage on this shard's database. */
258
410
  kv: ShardKvStore;
259
411
  /** Single-writer execution, local SQL, transactions, durable alarms. */
@@ -310,22 +462,65 @@ interface NodeShardRegistry {
310
462
  }
311
463
  /** Build the in-process shard registry. */
312
464
  declare const createNodeShardRegistry: (options?: NodeShardRegistryOptions) => NodeShardRegistry;
465
+ /** Options for {@link createNodeWorkflowHost}. */
466
+ interface NodeWorkflowHostOptions<Workflows extends Record<string, {
467
+ isLunoraWorkflow: true;
468
+ }>> {
469
+ /** Base env merged under the derived workflow bindings — surfaced to workflow bodies as `ctx.env` and used to resolve spawned children. */
470
+ env?: Record<string, unknown>;
471
+ /** How long (ms) the engine holds a cross-process lease while an activation runs, for stores that implement `acquire`. Defaults to 30000. */
472
+ leaseTtlMs?: number;
473
+ /** Where runs are persisted. Required — see the header for why there is no default. `createNodeWorkflowStore(database)` is the durable one. */
474
+ store: WorkflowStore;
475
+ /** The declared workflows keyed by their `lunora/workflows.ts` export name (e.g. `{ orderPipeline: orderPipeline }`). Values must be `defineWorkflow` results. */
476
+ workflows: Workflows;
477
+ }
478
+ /** A fully-wired Node workflow host. */
479
+ interface NodeWorkflowHost<Workflows extends Record<string, {
480
+ isLunoraWorkflow: true;
481
+ }>> {
482
+ /** Per-export-name `WorkflowBindingLike` — the map `ctx.workflows` consumes. */
483
+ readonly bindings: { [K in keyof Workflows]: WorkflowBindingLike; };
484
+ /**
485
+ * The caller's `env` plus one binding per workflow under its class name
486
+ * (`OrderPipelineWorkflow`), the key `ctx.exports` would carry on Cloudflare —
487
+ * merge this into a worker env so `ctx.spawn`/`ctx.parallel` resolve
488
+ * children through the same runtime.
489
+ */
490
+ readonly env: Record<string, unknown>;
491
+ /** The underlying visulima runtime — `sweep`/`signal` for a dev loop or tests. */
492
+ readonly runtime: WorkflowRuntime;
493
+ }
494
+ /**
495
+ * Create a Node workflow host: compile every declared Lunora workflow onto the
496
+ * visulima engine, derive the workflow env, and expose the per-workflow
497
+ * `WorkflowBindingLike` handles.
498
+ */
499
+ declare const createNodeWorkflowHost: <Workflows extends Record<string, {
500
+ isLunoraWorkflow: true;
501
+ }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
313
502
  /** Every contract this package provides, composed for one Node process. */
314
503
  interface NodePlatform<Queues extends Record<string, {
315
504
  isLunoraQueue: true;
505
+ }> = Record<string, never>, Workflows extends Record<string, {
506
+ isLunoraWorkflow: true;
316
507
  }> = Record<string, never>> {
317
508
  /** `using platform = createNodePlatform(...)` support — delegates to `close()`. */
318
509
  [Symbol.dispose]: () => void;
319
510
  /** What this target supports — see `NODE_CAPABILITIES` in `@lunora/platform`. */
320
511
  capabilities: PlatformCapabilities;
321
512
  /**
322
- * Tear this platform instance down: clears the shard host's pending alarm
323
- * timer and closes its `better-sqlite3` database (and, with it, `kv`'s
324
- * table — both live on the same connection), then clears every armed
325
- * scheduler job timer. Nothing in this package closes these resources on
326
- * its own — a `NodePlatform` a caller stops using without calling `close()`
327
- * leaks the open file handle (plus its WAL/SHM sidecar files) and keeps
328
- * the process alive on outstanding timers. Safe to call more than once.
513
+ * Tear this platform instance down: every resource this root built, in
514
+ * reverse construction order — the global store's own connection, every
515
+ * armed scheduler job timer, the registry's live shards, and last the shard
516
+ * host's pending alarm timer and its `better-sqlite3` database (and, with
517
+ * it, `kv`'s table — both live on the same connection). Nothing in this
518
+ * package closes these resources on its own — a `NodePlatform` a caller
519
+ * stops using without calling `close()` leaks the open file handles (plus
520
+ * their WAL/SHM sidecar files) and keeps the process alive on outstanding
521
+ * timers. Safe to call more than once. A `createNodePlatform` that throws
522
+ * unwinds the same list itself, so a failed construction leaks nothing and
523
+ * leaves nothing to call this on.
329
524
  *
330
525
  * **`close()` is a terminal state, not merely a cleanup step.** After it
331
526
  * runs: `scheduler.schedule()` throws instead of arming a fresh timer
@@ -344,6 +539,16 @@ interface NodePlatform<Queues extends Record<string, {
344
539
  close: () => void;
345
540
  /** In-process shard directory (see `createNodeShardRegistry` for what it can and cannot do). */
346
541
  directory: ShardDirectory;
542
+ /**
543
+ * The scheduler dispatch route, served in-process: `Request` in, shard
544
+ * response out, no listener. It answers the path `@lunora/dispatch` and
545
+ * `@lunora/scheduler` POST to. Pass it to `dispatchQueueBatch` as
546
+ * `queueFetchImpl` on `createWorker` so a queue handler's `message.run` /
547
+ * `ctx.run` reaches the shard; the env you pass there must carry `LUNORA_ORIGIN_URL` and the same
548
+ * `LUNORA_ADMIN_TOKEN` as `dispatch.adminToken`. Every request is refused
549
+ * unless `dispatch` supplies a secret.
550
+ */
551
+ dispatch: (request: Request) => Promise<Response>;
347
552
  /**
348
553
  * Wait for every promise handed to `shard.waitUntil` to settle.
349
554
  *
@@ -353,8 +558,28 @@ interface NodePlatform<Queues extends Record<string, {
353
558
  * shutdown is `await platform.drain()` then `platform.close()`.
354
559
  */
355
560
  drain: () => Promise<void>;
561
+ /**
562
+ * The `.global()` backend, or `undefined` when the caller named no database
563
+ * file for it. There is no default path, because a global store silently
564
+ * rooted at `:memory:` loses every row when the process exits.
565
+ *
566
+ * **A building block, not a wiring.** Unlike its three siblings, nothing
567
+ * downstream of this composition root reads it: a `.global()` read or write
568
+ * reaches its backend through exactly one seam, `createShardCtxDb({ globalDb
569
+ * })`, and the only thing that passes `globalDb` is the generated `shard.ts`,
570
+ * from its `d1` / `hyperdriveGlobal` config thunks. `createNodePlatform`
571
+ * constructs no shard DO, so it cannot make that hop itself. A caller that
572
+ * wants `.global()` on this host makes it: after `migrate(schema)` has
573
+ * provisioned the tables, give the generated `createShardDO` a `d1` thunk
574
+ * returning `platform.globalTables.writer({ schema, … })` — `writer` builds
575
+ * the `createSqlCtxDb` facade that seam expects, and `node-platform.test.ts`
576
+ * round-trips a row through exactly that object.
577
+ */
578
+ globalTables?: NodeGlobalStore;
356
579
  /** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
357
580
  kv: ShardKvStore;
581
+ /** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
582
+ objectStorage?: R2BucketLike;
358
583
  /**
359
584
  * The declared queues, or `undefined` when the caller declared none.
360
585
  *
@@ -369,6 +594,28 @@ interface NodePlatform<Queues extends Record<string, {
369
594
  shard: ShardHost;
370
595
  /** Socket registry with mutable tags and SQLite-persisted attachments. */
371
596
  sockets: SocketHost;
597
+ /**
598
+ * The declared workflows, or `undefined` when the caller declared none.
599
+ * Runs are persisted to the same `better-sqlite3` database as the shard, so
600
+ * they survive a restart without a second store to configure.
601
+ */
602
+ workflows?: NodeWorkflowHost<Workflows>;
603
+ }
604
+ /**
605
+ * The secrets the dispatch route authenticates with. With neither, the route
606
+ * refuses everything.
607
+ *
608
+ * Queue and topic delivery authenticates with `adminToken` alone:
609
+ * `@lunora/dispatch` always sends `Bearer <LUNORA_ADMIN_TOKEN>` and never signs,
610
+ * so the value here must match the token the caller puts on the env it passes
611
+ * `dispatchQueueBatch`. `schedulerSecret` only verifies a signed body, which the
612
+ * scheduler's own delivery sends; queue delivery never does.
613
+ */
614
+ interface NodePlatformDispatchOptions {
615
+ /** `LUNORA_ADMIN_TOKEN`. The bearer queue and topic delivery sends, so it must match the caller's env. */
616
+ adminToken?: string;
617
+ /** `LUNORA_SCHEDULER_SECRET`. When set, a signed body is verified against it. Queue delivery does not sign. */
618
+ schedulerSecret?: string;
372
619
  }
373
620
  /**
374
621
  * Options for {@link createNodePlatform} — the shard host's (`path`,
@@ -378,23 +625,58 @@ interface NodePlatform<Queues extends Record<string, {
378
625
  * or job with nowhere to land is bookkeeping. `directory` makes the shards the
379
626
  * directory resolves for fan-out file-backed too, and `onAlarm` gives their
380
627
  * durable alarms somewhere to land.
628
+ *
629
+ * `queues`, `workflows`, `objectStorageDirectory` and `globalTablesPath` are the
630
+ * four declarations — each is absent from the returned platform when omitted.
381
631
  */
382
632
  type NodePlatformOptions<Queues extends Record<string, {
383
633
  isLunoraQueue: true;
634
+ }> = Record<string, never>, Workflows extends Record<string, {
635
+ isLunoraWorkflow: true;
384
636
  }> = Record<string, never>> = {
637
+ /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
638
+ dispatch?: NodePlatformDispatchOptions;
639
+ /**
640
+ * Database file the `.global()` tables live in — its own file, never a
641
+ * shard's, because a table every shard reads must not be inside any one of
642
+ * them. Omit when the app declares no `.global()` table; there is no
643
+ * default, for the same reason the bucket has none.
644
+ */
645
+ globalTablesPath?: string;
385
646
  /**
386
- * Deliver one assembled queue batch — wire this to `dispatchQueueBatch`.
387
- * Required alongside `queues`; without it the messages would be stored
388
- * and never consumed.
647
+ * Directory the object-storage bucket keeps its objects in, one file per
648
+ * key. Omit when the app declares no buckets — there is no default,
649
+ * because a bucket silently rooted at the process's working directory is
650
+ * worse than an absent one.
651
+ */
652
+ objectStorageDirectory?: string;
653
+ /**
654
+ * Deliver one assembled queue batch — wire this to the app worker's `queue`
655
+ * export from `createWorker`, not to bare `dispatchQueueBatch`. That export
656
+ * is the only path that hands the consumer `ctx.live`, and it takes
657
+ * `queueFetchImpl` (this platform's `dispatch`, wrapped as a `fetch`) so
658
+ * `ctx.run` reaches the shard here rather than `LUNORA_ORIGIN_URL`. Required
659
+ * alongside `queues`; without it the messages would be stored and never consumed.
389
660
  */
390
661
  onQueueBatch?: NodeQueueHostOptions<Queues>["onBatch"];
391
662
  /** The app's `defineQueue` results, keyed by export name. Omit when the app declares no queues. */
392
663
  queues?: Queues;
664
+ /** The app's `defineWorkflow` results, keyed by export name. Omit when the app declares no workflows. */
665
+ workflows?: Workflows;
393
666
  } & NodeSchedulerHostOptions & NodeShardHostOptions & NodeShardRegistryOptions;
394
667
  /** Compose every contract this package provides over one `better-sqlite3` database. */
395
668
  declare const createNodePlatform: <Queues extends Record<string, {
396
669
  isLunoraQueue: true;
397
- }> = Record<string, never>>(options?: NodePlatformOptions<Queues>) => NodePlatform<Queues>;
670
+ }> = Record<string, never>, Workflows extends Record<string, {
671
+ isLunoraWorkflow: true;
672
+ }> = Record<string, never>>(options?: NodePlatformOptions<Queues, Workflows>) => NodePlatform<Queues, Workflows>;
673
+ interface NodeProfileHandlerOptions {
674
+ /** The bearer a caller must present. Required and non-empty: an empty token would make the endpoint open to anyone. */
675
+ token: string;
676
+ }
677
+ type NodeProfileHandler = (request: Request) => Promise<Response>;
678
+ /** The public handler: the real profiler, guarded by `token`. */
679
+ declare const createNodeProfileHandler: ({ token }: NodeProfileHandlerOptions) => NodeProfileHandler;
398
680
  /** Options for {@link createNodeR2Bucket}. */
399
681
  interface NodeR2BucketOptions {
400
682
  /** The bucket directory — created on first write. Objects live here, one file per key. */
@@ -402,10 +684,19 @@ interface NodeR2BucketOptions {
402
684
  }
403
685
  /**
404
686
  * Create an `R2BucketLike` over the local filesystem. Any object shape
405
- * `createStorage({ bucket })` accepts — `put`/`get`/`head`/`delete`/`list` —
687
+ * `createStorage({ bucket, bucketName })` accepts — `put`/`get`/`head`/`delete`/`list` —
406
688
  * maps directly onto a file operation.
407
689
  */
408
690
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
691
+ /**
692
+ * Present the node shard registry as the `ShardNamespaceLike` a worker is built
693
+ * over (`createWorker({ shardDO })`).
694
+ *
695
+ * The registry names its id derivation `idForName`, which is the
696
+ * `ShardDirectory` spelling; the worker reads Cloudflare's `idFromName`. Both
697
+ * return the key itself here, so a stub from either route reaches the same shard.
698
+ */
699
+ declare const createNodeShardNamespace: (directory: DirectShardDirectory) => ShardNamespaceLike;
409
700
  /**
410
701
  * The `DurableObjectState` subset `ShardDO` consumes.
411
702
  *
@@ -422,6 +713,11 @@ interface NodeShardState {
422
713
  id: {
423
714
  name?: string;
424
715
  };
716
+ /** Open a connection pair. Read by `@lunora/platform-cloudflare`'s socket host, which has no `WebSocketPair` here. */
717
+ openSocketPair: () => {
718
+ client: unknown;
719
+ server: unknown;
720
+ };
425
721
  storage: {
426
722
  delete: (key: string) => Promise<boolean>;
427
723
  deleteAlarm: () => Promise<void>;
@@ -438,6 +734,8 @@ interface NodeShardState {
438
734
  };
439
735
  transaction: <T>(closure: () => Promise<T>) => Promise<T>;
440
736
  };
737
+ /** Build the upgrade response for a pair's client end. A Node `Response` cannot carry status 101, so this is a marker. */
738
+ upgradeResponse: (client: unknown) => Response;
441
739
  waitUntil: (promise: Promise<unknown>) => void;
442
740
  }
443
741
  /**
@@ -452,71 +750,24 @@ interface NodeShardState {
452
750
  * report a point-in-time restore that never happened.
453
751
  */
454
752
  declare const createNodeShardState: (shard: NodeShard) => NodeShardState;
455
- /**
456
- * The socket-host half of a Node platform instance, plus the test-only hooks
457
- * `@lunora/platform/conformance`'s `ConformanceHost` needs to drive a recycle
458
- * from inside a test.
459
- */
460
- interface NodeSocketHost {
461
- /** Read back the frames sent to a socket, oldest first, text frames only. */
462
- readFrames: (handle: SocketHandle) => string[];
463
- /**
464
- * Re-create a runtime socket from durable state.
465
- *
466
- * `attachment` is a fallback only: this host restores what it persisted,
467
- * because that is what a real wake looks like. The argument covers an id
468
- * this host never durably tracked (a synthetic id a test constructs).
469
- */
470
- restoreSocket: (id: string, attachment: unknown) => SocketHandle;
471
- /** Drop the runtime socket map while keeping durable attachments/tags. */
472
- simulateRecycle: () => void;
473
- /** The `SocketHost` contract implementation. */
474
- socket: SocketHost;
475
- }
476
- /** Build the socket registry, persisting attachments and tags to `database`. */
477
- declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
478
- /** Options for {@link createNodeWorkflowHost}. */
479
- interface NodeWorkflowHostOptions<Workflows extends Record<string, {
480
- isLunoraWorkflow: true;
481
- }>> {
482
- /** Base env merged under the derived `WORKFLOW_*` bindings — surfaced to workflow bodies as `ctx.env` and used to resolve spawned children. */
483
- env?: Record<string, unknown>;
484
- /** How long (ms) the engine holds a cross-process lease while an activation runs, for stores that implement `acquire`. Defaults to 30000. */
485
- leaseTtlMs?: number;
486
- /** Where runs are persisted. Required — see the header for why there is no default. `createNodeWorkflowStore(database)` is the durable one. */
487
- store: WorkflowStore;
488
- /** The declared workflows keyed by their `lunora/workflows.ts` export name (e.g. `{ orderPipeline: orderPipeline }`). Values must be `defineWorkflow` results. */
489
- workflows: Workflows;
490
- }
491
- /** A fully-wired Node workflow host. */
492
- interface NodeWorkflowHost<Workflows extends Record<string, {
493
- isLunoraWorkflow: true;
494
- }>> {
495
- /** Per-export-name `WorkflowBindingLike` — the map `ctx.workflows` consumes. */
496
- readonly bindings: { [K in keyof Workflows]: WorkflowBindingLike; };
497
- /**
498
- * The caller's `env` plus one `WORKFLOW_&lt;EXPORT>` binding per workflow —
499
- * merge this into a worker env so `ctx.spawn`/`ctx.parallel` resolve
500
- * children through the same runtime.
501
- */
502
- readonly env: Record<string, unknown>;
503
- /** The underlying visulima runtime — `sweep`/`signal` for a dev loop or tests. */
504
- readonly runtime: WorkflowRuntime;
753
+ /** The two socket hooks a `ShardDO` runs on the Cloudflare runtime's behalf. */
754
+ interface ShardSocketHooks {
755
+ webSocketClose(ws: unknown, code: number, reason: string, wasClean: boolean): unknown;
756
+ webSocketMessage(ws: unknown, message: string | ArrayBuffer): unknown;
505
757
  }
506
758
  /**
507
- * Create a Node workflow host: compile every declared Lunora workflow onto the
508
- * visulima engine, derive the `WORKFLOW_*` env, and expose the per-workflow
509
- * `WorkflowBindingLike` handles.
759
+ * Deliver a shard's inbound socket events. The Cloudflare runtime calls
760
+ * `webSocketMessage` and `webSocketClose` on the Durable Object for a hibernated
761
+ * socket. On Node nothing does, so the embedder calls this once per shard
762
+ * instance, at the same point it builds the shard.
510
763
  */
511
- declare const createNodeWorkflowHost: <Workflows extends Record<string, {
512
- isLunoraWorkflow: true;
513
- }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
764
+ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShard["inbound"], "onClose" | "onMessage">) => void;
514
765
  /**
515
766
  * Build a durable {@link WorkflowStore} over a `better-sqlite3` connection.
516
767
  * Pass the result as `createNodeWorkflowHost({ store })`.
517
768
  */
518
769
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
519
- export {
770
+ export { NODE_SCHEDULER_DISPATCH_PATH,
520
771
  /**
521
772
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
522
773
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -536,49 +787,33 @@ export {
536
787
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
537
788
  * lifecycle/global-store tests.
538
789
  *
539
- * **Still missing**, and rated accordingly in `NODE_CAPABILITIES`
540
- * (`@lunora/platform`): a dev server — so `lunora dev --target node` does not
541
- * exist yet — plus most Cloudflare product bindings (Queues, Vectorize, Workers
542
- * AI, Browser Rendering, Containers, Analytics Engine, Pipelines, Secrets Store,
543
- * Hyperdrive). R2 buckets are emulated over the local filesystem
544
- * (`./node-r2-bucket`) and Workflows over the `@visulima/workflow` engine
545
- * (`./node-workflow-host`). Cross-shard fan-out is emulated via
546
- * `@lunora/runtime`'s query coordinator over the in-process shard registry, and
547
- * a `@lunora/config` deploy driver makes `--target node` resolve. See
548
- * `plans/234-node-host-findings.md`.
549
- */
550
- type NodeGlobalContextDatabaseOptions,
551
- /**
552
- * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
553
- * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
554
- * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
555
- * scheduler registry.
556
- *
557
- * Promoted from `@lunora/platform`'s `node:sqlite` reference host
558
- * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
559
- * durability half of each contract actually holds: alarms and scheduler jobs
560
- * are persisted **and re-armed on construction**, socket attachments and tags
561
- * live in SQLite rather than a `Map`, and `.global()` tables run the real
562
- * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
563
- * a restart test — a second host over the same database file — not only by the
564
- * TCK's simulated recycle.
790
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
791
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
792
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
793
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
794
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
795
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
796
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
797
+ * is the one combination that fails at runtime with no diagnostic before it.
565
798
  *
566
- * Three suites run against this package: `@lunora/platform/conformance`'s host
567
- * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
568
- * lifecycle/global-store tests.
799
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
800
+ * nothing here owns a timer, so queue delivery is driven by an explicit
801
+ * `poll()`. What exists is the listener a dev server would sit on:
802
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
803
+ * streaming the response body, and `createNodeShardNamespace` presents the
804
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
805
+ * the Cloudflare product bindings with no local
806
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
807
+ * Engine, Pipelines, Secrets Store, Hyperdrive.
569
808
  *
570
- * **Still missing**, and rated accordingly in `NODE_CAPABILITIES`
571
- * (`@lunora/platform`): a dev server — so `lunora dev --target node` does not
572
- * exist yet — plus most Cloudflare product bindings (Queues, Vectorize, Workers
573
- * AI, Browser Rendering, Containers, Analytics Engine, Pipelines, Secrets Store,
574
- * Hyperdrive). R2 buckets are emulated over the local filesystem
575
- * (`./node-r2-bucket`) and Workflows over the `@visulima/workflow` engine
576
- * (`./node-workflow-host`). Cross-shard fan-out is emulated via
577
- * `@lunora/runtime`'s query coordinator over the in-process shard registry, and
578
- * a `@lunora/config` deploy driver makes `--target node` resolve. See
809
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
810
+ * for `provision` — which reports, once, which declared features this target
811
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
812
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
813
+ * server, which is why both statements above hold at once. See
579
814
  * `plans/234-node-host-findings.md`.
580
815
  */
581
- type NodeGlobalStore,
816
+ type NodeDispatchInvocation,
582
817
  /**
583
818
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
584
819
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -598,15 +833,30 @@ type NodeGlobalStore,
598
833
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
599
834
  * lifecycle/global-store tests.
600
835
  *
601
- * **Still missing**, and rated accordingly in `NODE_CAPABILITIES`
602
- * (`@lunora/platform`): a dev server — so `lunora dev --target node` does not
603
- * exist yet — plus most Cloudflare product bindings (Queues, Vectorize, Workers
604
- * AI, Browser Rendering, Containers, Analytics Engine, Pipelines, Secrets Store,
605
- * Hyperdrive). R2 buckets are emulated over the local filesystem
606
- * (`./node-r2-bucket`) and Workflows over the `@visulima/workflow` engine
607
- * (`./node-workflow-host`). Cross-shard fan-out is emulated via
608
- * `@lunora/runtime`'s query coordinator over the in-process shard registry, and
609
- * a `@lunora/config` deploy driver makes `--target node` resolve. See
836
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
837
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
838
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
839
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
840
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
841
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
842
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
843
+ * is the one combination that fails at runtime with no diagnostic before it.
844
+ *
845
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
846
+ * nothing here owns a timer, so queue delivery is driven by an explicit
847
+ * `poll()`. What exists is the listener a dev server would sit on:
848
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
849
+ * streaming the response body, and `createNodeShardNamespace` presents the
850
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
851
+ * the Cloudflare product bindings with no local
852
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
853
+ * Engine, Pipelines, Secrets Store, Hyperdrive.
854
+ *
855
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
856
+ * for `provision` — which reports, once, which declared features this target
857
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
858
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
859
+ * server, which is why both statements above hold at once. See
610
860
  * `plans/234-node-host-findings.md`.
611
861
  */
612
- type NodeGlobalStoreOptions, type NodePlatform, type NodePlatformOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, createNodeGlobalStore, createNodePlatform, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
862
+ type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };