@lunora/platform-node 1.0.0-alpha.23 → 1.0.0-alpha.231

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 (43) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +8 -1
  3. package/dist/conformance/index.mjs +1 -1
  4. package/dist/index.d.mts +1005 -151
  5. package/dist/index.d.ts +1005 -151
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs +1 -0
  8. package/dist/packem_shared/NODE_SCHEDULER_DISPATCH_PATH-CgTHf6UW.mjs +1 -0
  9. package/dist/packem_shared/bindShardSockets-DjLmRlIA.mjs +1 -0
  10. package/dist/packem_shared/checkNodeAppHost-CzH-jdhY.mjs +1 -0
  11. package/dist/packem_shared/createNodeDurableObjectFactory-DhewI6JL.mjs +1 -0
  12. package/dist/packem_shared/createNodeGlobalStore-CD4DiqeS.mjs +1 -0
  13. package/dist/packem_shared/createNodeHttpServer-CKwkBmRI.mjs +4 -0
  14. package/dist/packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs +1 -0
  15. package/dist/packem_shared/createNodeMailHost-AOATqXEM.mjs +8 -0
  16. package/dist/packem_shared/createNodePlatform-4XLWgRgP.mjs +1 -0
  17. package/dist/packem_shared/createNodeProfileHandler-MX5xKPg0.mjs +1 -0
  18. package/dist/packem_shared/createNodeQueueHost--kuV6C8-.mjs +17 -0
  19. package/dist/packem_shared/createNodeR2Bucket-D_jsnenX.mjs +1 -0
  20. package/dist/packem_shared/createNodeSchedulerHost-B5KeCI9c.mjs +15 -0
  21. package/dist/packem_shared/createNodeSecretBindings-C7wh0fOm.mjs +1 -0
  22. package/dist/packem_shared/createNodeShardHost-PBzbPuHa.mjs +1 -0
  23. package/dist/packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs +1 -0
  24. package/dist/packem_shared/createNodeShardNamespace-BgQjDv7V.mjs +1 -0
  25. package/dist/packem_shared/createNodeShardRegistry-Dt2izX_5.mjs +1 -0
  26. package/dist/packem_shared/createNodeSocketHost-BJf5HOHr.mjs +2 -0
  27. package/dist/packem_shared/createNodeWorkflowHost-B76TKiw_.mjs +1 -0
  28. package/dist/packem_shared/hmac-url-Bogwm7I6.mjs +1 -0
  29. package/dist/packem_shared/node-dispatch-route-DjQWVUkP.mjs +2 -0
  30. package/dist/packem_shared/node-socket-pair-BsiTm62u.mjs +1 -0
  31. package/dist/packem_shared/prepared-statement-3XBQZXtC.mjs +1 -0
  32. package/package.json +18 -10
  33. package/dist/packem_shared/createNodeGlobalStore-Cwi33XOk.mjs +0 -1
  34. package/dist/packem_shared/createNodePlatform-1fAQ_biu.mjs +0 -1
  35. package/dist/packem_shared/createNodeQueueHost--mBLGSxF.mjs +0 -17
  36. package/dist/packem_shared/createNodeR2Bucket-CmHYlIni.mjs +0 -1
  37. package/dist/packem_shared/createNodeSchedulerHost-vZgv1CEo.mjs +0 -15
  38. package/dist/packem_shared/createNodeShardHost-C0j8nvSU.mjs +0 -1
  39. package/dist/packem_shared/createNodeShardKvStore-DVi1OsvH.mjs +0 -1
  40. package/dist/packem_shared/createNodeShardRegistry-DKdc0pV8.mjs +0 -1
  41. package/dist/packem_shared/createNodeShardState-CpUzvWwd.mjs +0 -1
  42. package/dist/packem_shared/createNodeSocketHost-DK3X5PlQ.mjs +0 -2
  43. package/dist/packem_shared/createNodeWorkflowHost-CTVBYiuj.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,9 +1,99 @@
1
+ import { QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, ShardKvListOptions, ShardKvStore, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, R2BucketLike } from '@lunora/platform';
1
2
  import { SchemaLike } from '@lunora/shard-engine';
2
3
  import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
3
4
  import Database from 'better-sqlite3';
4
- import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike, SocketHandle } from '@lunora/platform';
5
+ import { Mailer, QueueLike, MailEnv, MailTransport } from '@lunora/mail';
5
6
  import { WorkflowBindingLike } from '@lunora/workflow';
6
7
  import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
8
+ import { ShardNamespaceLike } from '@lunora/runtime';
9
+ /**
10
+ * The deadline every `drain()` in this package runs under. A shutdown that waits for work without a bound is held open by the
11
+ * one request or background task that never settles, until the supervisor's kill skips the database close the drain exists to
12
+ * reach. Each drain returns what was still pending when its deadline passed, so the caller can log it and close anyway.
13
+ */
14
+ /**
15
+ * Arms `onExpire` to run after `ms` and returns a function that disarms it. Injectable so a test drives the deadline by hand
16
+ * rather than waiting for a clock.
17
+ */
18
+ type DrainTimer = (ms: number, onExpire: () => void) => () => void;
19
+ /** Options every `drain()` accepts. */
20
+ interface DrainOptions {
21
+ /** Stop waiting after this many milliseconds. Defaults to {@link DEFAULT_DRAIN_TIMEOUT_MS}. */
22
+ timeoutMs?: number;
23
+ /** The clock the deadline runs on. Defaults to `setTimeout`, which keeps the process alive until the drain settles or expires. */
24
+ timer?: DrainTimer;
25
+ }
26
+ /** How a `drain()` ended. */
27
+ interface DrainResult {
28
+ /**
29
+ * Work that failed while the drain waited for it (an alarm retry that could not be written), one readable entry each. Each
30
+ * was also logged with its cause when it happened. A failure never stops the drain waiting for the rest.
31
+ */
32
+ failed: string[];
33
+ /** What was still running when the deadline passed, one human-readable entry each. Empty when the drain completed. */
34
+ pending: string[];
35
+ /** `true` when the deadline passed before the work settled. */
36
+ timedOut: boolean;
37
+ }
38
+ /** Long enough for an ordinary request or background write to finish; short enough that a stuck one cannot stall a shutdown. */
39
+ declare const DEFAULT_DRAIN_TIMEOUT_MS = 3e4;
40
+ /** Something that drains and can say, synchronously, whether it is idle: a registry, a platform. */
41
+ interface Drainable {
42
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
43
+ idle: () => boolean;
44
+ /** What is running right now, re-read when the deadline passes: a part that drained early can have gained work since. */
45
+ pending: () => string[];
46
+ }
47
+ /**
48
+ * Drain several parts under one deadline until a pass that began with every part idle also ends with every part idle. Work
49
+ * on one part can start work on another after that one finished draining (a request handed between registries), and a
50
+ * failure can be recorded after a part's own drain returned; the pass that begins idle collects it, and is held to the same
51
+ * deadline as any other.
52
+ */
53
+ declare const drainTogether: (parts: ReadonlyArray<Drainable>, options?: DrainOptions) => Promise<DrainResult>;
54
+ /** One function call the route has authenticated and parsed. */
55
+ interface NodeDispatchInvocation {
56
+ args: Record<string, unknown>;
57
+ functionPath: string;
58
+ /**
59
+ * The shard's idempotency key, derived from the function path, the scheduling user's
60
+ * `dedupScope` and the scheduler's per-record `dedupKey` (else the record or delivery id). A
61
+ * scheduler id is free again once its job settles, so the bare id would answer a reused id's
62
+ * new job from the previous job's dedup row; and every dispatch shares the shard's `"system:"`
63
+ * namespace, so the bare key would let another user or function answer this one.
64
+ */
65
+ id: string | undefined;
66
+ /** Identity the trusted caller forwarded, if any. */
67
+ identity: {
68
+ identity?: string;
69
+ userId?: string;
70
+ } | undefined;
71
+ /** The job's due time in epoch-ms, when the sender stamped one. */
72
+ scheduledFor?: number;
73
+ shardKey: string;
74
+ traceparent: string | undefined;
75
+ }
76
+ interface NodeDispatchRouteOptions {
77
+ /** `LUNORA_ADMIN_TOKEN`. Used as the bearer when no HMAC signature is presented. */
78
+ adminToken?: string;
79
+ /** The shard a body without `shardKey` is sent to. */
80
+ defaultShardKey: string;
81
+ /** Runs the call in-process and returns the shard's response, unchanged. */
82
+ invoke: (call: NodeDispatchInvocation) => Promise<Response>;
83
+ /** Epoch-ms clock for the signature window. Defaults to `Date.now`; tests inject one. */
84
+ now?: () => number;
85
+ /** `LUNORA_SCHEDULER_SECRET`. When set, a signed request is verified against it. */
86
+ schedulerSecret?: string;
87
+ }
88
+ /**
89
+ * Build the dispatch route. The returned function answers any request it is
90
+ * handed; mounting it at {@link NODE_SCHEDULER_DISPATCH_PATH} is the caller's job.
91
+ * With neither secret configured every request is refused, so an unconfigured
92
+ * route fails closed.
93
+ */
94
+ declare const createNodeDispatchRoute: (options: NodeDispatchRouteOptions) => ((request: Request) => Promise<Response>);
95
+ /** The path `@lunora/dispatch` and `@lunora/scheduler` POST to. */
96
+ declare const NODE_SCHEDULER_DISPATCH_PATH: "/_lunora/scheduler/dispatch";
7
97
  /**
8
98
  * The Node store options — the shared store options minus the two this binding
9
99
  * owns. `dialect` is fixed (SQLite) and `exec` is the store's own connection;
@@ -14,13 +104,21 @@ type NodeGlobalContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect" | "exec"
14
104
  /**
15
105
  * Wrap a `better-sqlite3` connection as the async exec the store core consumes.
16
106
  *
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.
107
+ * `batch` runs the statements in order inside one `better-sqlite3`
108
+ * transaction, which is synchronous, so nothing else runs between them. There is
109
+ * no round trip to save; atomicity is the point. The store core's FTS5 search
110
+ * companion writes each document as an ordered list of statements, and without
111
+ * this two async writers interleaved at every `await` between them: one could
112
+ * move a document's mapping while the other's entry was mid-write, leaving an
113
+ * entry no later write or purge could reach. The `sqlite` dialect's contract
114
+ * requires an ordered, atomic `batch` for exactly that reason.
115
+ *
116
+ * `transaction` holds `BEGIN IMMEDIATE` … `COMMIT` open across the awaits of
117
+ * an async `work`, which `better-sqlite3`'s own synchronous `transaction()`
118
+ * cannot. The connection is shared, so while one is open every other statement
119
+ * waits for it to settle: run in between, another writer's statement would land
120
+ * inside it and be rolled back with it. The wait and the statement (or the
121
+ * `BEGIN`) run with no `await` between them, so nothing slips in after the check.
24
122
  */
25
123
  declare const createNodeSqlExec: (database: Database.Database) => SqlCtxExec;
26
124
  /** Options for {@link createNodeGlobalStore}. */
@@ -63,8 +161,79 @@ interface NodeGlobalStore {
63
161
  * which is the whole point of the dialect seam.
64
162
  */
65
163
  declare const createNodeGlobalStore: (options?: NodeGlobalStoreOptions) => NodeGlobalStore;
66
- /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
67
- declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
164
+ /** Options for {@link createNodeMailHost}. */
165
+ interface NodeMailHostOptions {
166
+ /**
167
+ * Where `MAIL_FROM`, `RESEND_API_KEY` and the capture switches
168
+ * (`LUNORA_MAIL_CAPTURE`, `WORKER_ENV`, …) are read, once, at construction.
169
+ * `process.env` unless given.
170
+ */
171
+ env?: MailEnv;
172
+ /** The host clock, shared with the queue host so a retry delay and `poll(now)` agree. Defaults to `Date.now`. */
173
+ now?: () => number;
174
+ /**
175
+ * Deliver through this, an SMTP client, another provider or a test double.
176
+ * It wins over `RESEND_API_KEY`, which is only read without it. Ignored while
177
+ * the env selects capture, as `createMailerFromEnv` ignores a transport then.
178
+ */
179
+ transport?: MailTransport;
180
+ }
181
+ /** Queued mail delivery for one Node process. */
182
+ /**
183
+ * Why a send sits in `deadLetters`: its retries ran out (`retries_exhausted`); its idempotency key
184
+ * belongs to other content (`idempotency_key_conflict`); an earlier delivery may have been sent
185
+ * and the provider no longer drops a repeat (`outcome_unknown`), so the provider's logs decide;
186
+ * or that may be so and the record of it has expired (`evidence_expired`). `unknown` is a row
187
+ * parked with no reason recorded (by a build before reasons, or a process that stopped first),
188
+ * which may be any of these, so treat it as `outcome_unknown` until the provider's logs say.
189
+ */
190
+ type MailParkReason = "evidence_expired" | "idempotency_key_conflict" | "outcome_unknown" | "retries_exhausted" | "unknown";
191
+ interface NodeMailHost {
192
+ /** Sends that failed past the queue's retries, parked by the queue host rather than dropped. */
193
+ deadLetters: {
194
+ /** Each parked send, with why it was parked, so an operator can decide whether to requeue it. */
195
+ list: () => {
196
+ attempts: number;
197
+ body: unknown;
198
+ id: string;
199
+ reason: MailParkReason;
200
+ }[];
201
+ /**
202
+ * Return a parked send to the queue for one more delivery. Its attempt
203
+ * count is kept, so a send an earlier attempt may have delivered is
204
+ * refused once the provider no longer dedupes it. `false` when no mail
205
+ * send with that id is parked. Throws for one queued 15 or more days ago,
206
+ * whose attempt record in the sent ledger has expired.
207
+ */
208
+ requeue: (id: string) => boolean;
209
+ };
210
+ /** Wait for every `poll()` in flight. `createNodePlatform`'s `drain()` calls it before the database can close. */
211
+ drain: () => Promise<void>;
212
+ /** Whether no `poll()` is in flight: what `createNodePlatform`'s `drain()` checks to end its passes. */
213
+ idle: () => boolean;
214
+ /** `queue()` enqueues onto {@link NodeMailHost.queue}; `send()` delivers now through the same transport. */
215
+ mailer: Mailer;
216
+ /** Deliver the queued sends that are due, and return how many batches went out. Nothing here runs on a timer. */
217
+ poll: (now?: number) => Promise<number>;
218
+ /**
219
+ * The producer: pass it as `createMailerFromEnv(env, { queue })` in your own
220
+ * module. A queued body needs an `idempotencyKey`, which `mailer.queue()` mints.
221
+ */
222
+ queue: QueueLike;
223
+ }
224
+ /**
225
+ * Create queued mail delivery over `database`: a durable `lunora-mail` queue, a
226
+ * mailer whose `queue()` writes to it, and `poll()` to drain it through the given
227
+ * `transport` or, without one, Resend (`RESEND_API_KEY`). In a dev environment
228
+ * the mailer captures instead, exactly as `createMailerFromEnv` decides on
229
+ * Cloudflare. Throws when `MAIL_FROM` is unset or nothing can deliver.
230
+ *
231
+ * Give it a connection nothing else opens a transaction on, ideally a file of
232
+ * its own, as `createNodePlatform({ mail: { path } })` does: on a shard host's
233
+ * connection, a poll during `shard.transaction()` writes inside it, and that
234
+ * transaction's rollback would undo the acks and sent records and resend.
235
+ */
236
+ declare const createNodeMailHost: (database: Database.Database, options?: NodeMailHostOptions) => NodeMailHost;
68
237
  /** Options for {@link createNodeQueueHost}. */
69
238
  interface NodeQueueHostOptions<Queues extends Record<string, {
70
239
  isLunoraQueue: true;
@@ -118,15 +287,17 @@ interface NodeQueueHost<Queues extends Record<string, {
118
287
  body: unknown;
119
288
  id: string;
120
289
  }[];
121
- /** Return a parked message to its queue with `attempts` reset. `false` when no such message is parked. */
290
+ /** Return a parked message to its queue with `attempts` reset. `false` when no message of a queue this host declared is parked under that id. */
122
291
  requeue: (id: string) => boolean;
123
292
  };
124
293
  /** The caller's `env` plus one `QUEUE_<EXPORT>` binding per queue. */
125
294
  readonly env: Record<string, unknown>;
126
295
  /**
127
- * Deliver every batch currently due, one per queue per call, and return how
128
- * many batches were delivered. Drives the consumer — nothing here runs on a
129
- * timer, because this host has no dev server to own one yet.
296
+ * Deliver the batches currently due, queue by queue, and return how many
297
+ * batches were delivered. Each queue gets at least one batch, then further
298
+ * ones while the poll is inside its time budget. Drives the consumer —
299
+ * nothing here runs on a timer, because this host has no dev server to own
300
+ * one yet.
130
301
  */
131
302
  poll: (now?: number) => Promise<number>;
132
303
  }
@@ -137,6 +308,14 @@ interface NodeQueueHost<Queues extends Record<string, {
137
308
  declare const createNodeQueueHost: <Queues extends Record<string, {
138
309
  isLunoraQueue: true;
139
310
  }>>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>;
311
+ /** One declared cron job, as {@link NodeSchedulerHost.declareCrons} takes it. */
312
+ interface NodeDeclaredCron {
313
+ args: Record<string, unknown>;
314
+ expression: string;
315
+ functionPath: string;
316
+ /** The job's `cronJobs()` name, unique across the app. Keys its row. */
317
+ name: string;
318
+ }
140
319
  /** Options for {@link createNodeSchedulerHost}. */
141
320
  interface NodeSchedulerHostOptions {
142
321
  /**
@@ -146,17 +325,22 @@ interface NodeSchedulerHostOptions {
146
325
  * A handler that **throws** marks the delivery failed, which is what drives
147
326
  * the retry/dead-letter machinery: the job's `attempts` increments and it is
148
327
  * either re-armed with backoff or parked. A handler that resolves marks the
149
- * job delivered and removes it.
328
+ * job `succeeded`.
150
329
  *
151
330
  * Omitting it makes every delivery trivially succeed, which means a caller
152
331
  * who forgets to pass one gets a scheduler that quietly drops work — the
153
332
  * precise failure plan 267 caught. Supply one in anything real; the
154
333
  * conformance host supplies one purely so the TCK can tell a delivery apart
155
334
  * from an expired timer.
335
+ *
336
+ * `job.scheduledFor` is the due time (a cron tick's planned fire time).
337
+ * Forwarding it as the dispatch body's `scheduledFor` is what lets the shard
338
+ * record the `scheduler.lag_ms` metric, as the Worker dispatch path does.
156
339
  */
157
340
  onDispatch?: (functionPath: string, args: Record<string, unknown>, job: {
158
341
  attempts: number;
159
342
  id: string;
343
+ scheduledFor: number;
160
344
  }) => Promise<void> | void;
161
345
  }
162
346
  /**
@@ -164,6 +348,14 @@ interface NodeSchedulerHostOptions {
164
348
  * TCK's dead-letter legs need.
165
349
  */
166
350
  interface NodeSchedulerHost {
351
+ /**
352
+ * Make `crons` the app's declared cron set: upsert each one, arm it, and
353
+ * delete and disarm any declared row not in the list (a job the app removed
354
+ * or renamed). Every expression is parsed before anything is written, so an
355
+ * invalid one throws and leaves the previous set in place. Throws after
356
+ * `dispose()`.
357
+ */
358
+ declareCrons: (crons: ReadonlyArray<NodeDeclaredCron>) => void;
167
359
  /**
168
360
  * Clear every armed `setTimeout` (one-shot jobs and cron ticks alike) and
169
361
  * put the host into a terminal, closed state: afterwards `schedule()` and
@@ -177,6 +369,14 @@ interface NodeSchedulerHost {
177
369
  * left uncleared.
178
370
  */
179
371
  dispose: () => void;
372
+ /**
373
+ * Deliveries running now, one-shot jobs and cron ticks alike, each from its timer firing until the scheduler has
374
+ * recorded the outcome, labelled by job. A drain waits for these before the database the scheduler writes to is closed.
375
+ */
376
+ pendingDispatches: () => {
377
+ labels: string[];
378
+ waits: Promise<unknown>[];
379
+ };
180
380
  scheduler: SchedulerHost;
181
381
  /**
182
382
  * Drive a pending job straight to its dead-letter state without waiting out
@@ -185,6 +385,12 @@ interface NodeSchedulerHost {
185
385
  * while how many failures it takes to get there is host policy.
186
386
  */
187
387
  simulateDeadLetter: (id: string) => Promise<boolean>;
388
+ /**
389
+ * Stop firing: clear every armed timer and arm none from then on, while rows are still written and kept. A shutdown calls
390
+ * it before draining, so no job or cron tick starts after the drain checked for running work; each then re-arms from its
391
+ * row after a restart. A delivery already running finishes. One-way; `dispose()` still ends the host.
392
+ */
393
+ suspend: () => void;
188
394
  }
189
395
  /** Build a durable, SQLite-backed scheduler over `database`. */
190
396
  declare const createNodeSchedulerHost: (database: Database.Database, options?: NodeSchedulerHostOptions) => NodeSchedulerHost;
@@ -197,9 +403,12 @@ interface NodeShardHostOptions {
197
403
  * `_lunora_alarm` when the host is constructed over an existing database,
198
404
  * including an alarm whose time elapsed while nothing was running.
199
405
  *
200
- * A handler that throws is isolated to its own delivery; it never reaches
406
+ * A handler that throws is isolated to its own delivery — it never reaches
201
407
  * the caller that set the alarm, because by then that call has long
202
- * returned.
408
+ * returned — and the wakeup is then re-delivered with backoff up to
409
+ * {@link ALARM_RETRY_LIMIT} times, the way workerd retries a throwing
410
+ * `alarm()`. Delivery is at-least-once, so the handler must tolerate
411
+ * running twice for one scheduled timestamp.
203
412
  */
204
413
  onAlarm?: () => Promise<void> | void;
205
414
  /**
@@ -218,25 +427,59 @@ interface NodeShardHostOptions {
218
427
  /**
219
428
  * Build a `ShardHost` over a real `better-sqlite3` database.
220
429
  *
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.
227
- *
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.
430
+ * `runSerialized` and `transaction` share **one** boundary lock, because they
431
+ * write **one** `better-sqlite3` connection. `transaction` issues raw
432
+ * `BEGIN`/`COMMIT`/`ROLLBACK` — legal here (unlike inside a Cloudflare Durable
433
+ * Object, where the runtime forbids it and callers must use
434
+ * `storage.transaction`) because better-sqlite3 is a plain embedded database
435
+ * with no platform-level transaction primitive layered over it.
436
+ *
437
+ * ## Why one lane and not two
438
+ *
439
+ * This host shipped with two private tail chains, one per entry point, so each
440
+ * serialized against itself and neither against the other. `runSerialized`
441
+ * issues no `BEGIN` of its own, so one of its closures overlapping a bare
442
+ * `transaction()` wrote straight into that transaction's span. `assertOwnTurn`
443
+ * below catches the write — it is the only reason this host never silently lost
444
+ * one the way an unguarded connection would — but catching it is not the same
445
+ * as preventing it, and the refusal lands in the wrong place:
446
+ *
447
+ * 1. A `runSerialized` closure writes a row. Nothing is open, so it commits.
448
+ * 2. It awaits (a scheduler hop, an `onShardInit` read, any real I/O).
449
+ * 3. A bare `transaction()` runs `BEGIN` while it is parked. `transaction` is
450
+ * a public contract surface, and `./node-shard-state` re-exports it as the
451
+ * `storage.transaction` member `ShardDO` documents as "the platform
452
+ * primitive", so a subclass reaches one without going through the engine.
453
+ * 4. The closure resumes and its next write is refused with
454
+ * `SHARD_UNAVAILABLE`, so `runSerialized` **rejects** — with step 1 already
455
+ * durable.
456
+ *
457
+ * The boundary the contract promises is atomic-or-nothing to its caller tore in
458
+ * half: a rejection the caller will retry, on top of a write the retry now
459
+ * re-applies. That is `runSerialized`'s "no two closures interleave" guarantee
460
+ * broken by a `transaction` it was never serialized against.
461
+ *
462
+ * ## Why the lock is re-entrant, and why `AsyncLocalStorage` is what makes it so
463
+ *
464
+ * The engine composes the two, and stacks them: `ShardRunner.runInTransaction`
465
+ * is `runSerialized(() => transaction(work))` (`@lunora/shard-engine`), and
466
+ * `ShardDO.fetch` widens a mutation dispatch carrying `x-lunora-mutation-id`
467
+ * into a *further* `runSerialized` span around it (`@lunora/do`). Under two
468
+ * plain FIFO chains that outer span is already fatal on this host — the inner
469
+ * `runSerialized` waits on a `tail` that only settles when the outer closure it
470
+ * is running inside resolves, and because nothing ever resets that `tail`, the
471
+ * shard's write lane is wedged for the life of the process rather than for the
472
+ * life of the request.
473
+ *
474
+ * So the lock is skipped for a boundary opened from inside a boundary, and
475
+ * `AsyncLocalStorage` is the only thing that can tell that case from the one
476
+ * that must queue: its store follows a single call's own await chain without
477
+ * leaking into a sibling chain. A held boolean cannot — it reads `true` for an
478
+ * unrelated *second top-level* `transaction()` too, which would then nest a raw
479
+ * `BEGIN` on a connection already inside one. This is the same distinction
480
+ * workerd's `blockConcurrencyWhile` draws natively with "does not queue events
481
+ * initiated as part of the callback itself", which is what
482
+ * `@lunora/platform-cloudflare` leans on for the identical composition.
240
483
  *
241
484
  * The returned `dispose()` is this host's lifecycle owner: it clears the
242
485
  * pending alarm `setTimeout` (so it can never fire against a connection this
@@ -246,16 +489,119 @@ interface NodeShardHostOptions {
246
489
  * rather than closing `database` directly, so the alarm timer and the
247
490
  * connection are always retired together.
248
491
  */
249
- declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
492
+ /** What {@link createNodeShardHost} returns. */
493
+ interface NodeShardHostParts {
494
+ /** Settles once every alarm delivery running now (its handler and any retry write) has; `undefined` when none is. */
495
+ alarmsSettled: () => Promise<unknown> | undefined;
250
496
  database: Database.Database;
251
497
  dispose: () => void;
252
498
  drain: () => Promise<void>;
253
499
  host: ShardHost;
254
- };
500
+ pendingAlarms: () => number;
501
+ pendingBackground: () => number;
502
+ /** Stop arming and claiming alarms, leaving the durable row for a restart. One-way: a closing registry calls it. */
503
+ suspendAlarms: () => void;
504
+ /** The failures recorded since the last call, which a drain reports in its result; each is also logged when it happens. */
505
+ takeFailures: () => string[];
506
+ }
507
+ declare const createNodeShardHost: (options?: NodeShardHostOptions) => NodeShardHostParts;
508
+ /**
509
+ * `ShardKvListOptions` plus the paging options `DurableObjectStorage.list` has. The contract leaves
510
+ * them out on purpose (Cloudflare's `ShardKvStore` would spend a `limit` on hidden secret records);
511
+ * the Node storage bridge emulates `state.storage`, whose callers pass them, so this store serves them
512
+ * with Cloudflare's meanings. A key it does not know throws rather than being ignored.
513
+ */
514
+ interface NodeShardKvListOptions extends ShardKvListOptions {
515
+ /** Only keys below this one. Exclusive, in either direction. */
516
+ end?: string;
517
+ /** At most this many keys, counted from the end the listing starts at. A positive integer. */
518
+ limit?: number;
519
+ /** List in descending key order. `start`, `startAfter` and `end` keep their meaning. */
520
+ reverse?: boolean;
521
+ /** Only keys at or above this one. Not together with `startAfter`. */
522
+ start?: string;
523
+ /** Only keys above this one. Not together with `start`. */
524
+ startAfter?: string;
525
+ }
526
+ /** A `ShardKvStore` whose `list` also takes the paging options. Keys always come back in key order. */
527
+ interface NodeShardKvStore extends ShardKvStore {
528
+ list: <T = unknown>(options?: NodeShardKvListOptions) => Promise<Map<string, T>>;
529
+ }
530
+ /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
531
+ declare const createNodeShardKvStore: (database: Database.Database) => NodeShardKvStore;
532
+ /** Every frame type a `SocketHandle` may be handed. `ws` sends each of them, a Blob by its `size`. */
533
+ type OutboundFrame = Parameters<SocketHandle["send"]>[0];
534
+ /** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
535
+ interface NodeServerEnd {
536
+ /**
537
+ * Outbound bytes not yet on the wire: the attached transport's own buffer, or before the handshake
538
+ * the frames still queued. A getter, so the socket host's adopted handle (this very object) stays
539
+ * live; the engine's drain wait reads it before each frame it streams.
540
+ */
541
+ readonly bufferedAmount: number;
542
+ close: (code?: number, reason?: string) => void;
543
+ send: (data: OutboundFrame) => void;
544
+ }
545
+ /**
546
+ * The socket-host half of a Node platform instance, plus the test-only hooks
547
+ * `@lunora/platform/conformance`'s `ConformanceHost` needs to drive a recycle
548
+ * from inside a test.
549
+ */
550
+ interface NodeSocketHost {
551
+ /**
552
+ * Wait for every close handler still running, including ones they start. `undefined` when none are,
553
+ * so a caller can dispose synchronously.
554
+ */
555
+ drain: () => Promise<void> | undefined;
556
+ /** Deliver a connection's close to `handler`, which calls `webSocketClose`. One handler per host. */
557
+ onClose: (handler: (socket: NodeServerEnd, code: number, reason: string, wasClean: boolean) => void | Promise<void>) => void;
558
+ /**
559
+ * Deliver a connection's inbound frames to `handler`. The handler is the
560
+ * shard that accepted the connection, so it calls `webSocketMessage`. One
561
+ * handler per host: a later call replaces the earlier one.
562
+ */
563
+ onMessage: (handler: (socket: NodeServerEnd, data: string | ArrayBuffer) => void) => void;
564
+ /** Read back the frames sent to a socket, oldest first, text frames only. */
565
+ readFrames: (handle: SocketHandle) => string[];
566
+ /**
567
+ * Re-create a runtime socket from durable state.
568
+ *
569
+ * `attachment` is a fallback only: this host restores what it persisted,
570
+ * because that is what a real wake looks like. The argument covers an id
571
+ * this host never durably tracked (a synthetic id a test constructs).
572
+ */
573
+ restoreSocket: (id: string, attachment: unknown) => SocketHandle;
574
+ /** Drop the runtime socket map while keeping durable attachments/tags. */
575
+ simulateRecycle: () => void;
576
+ /** The `SocketHost` contract implementation. */
577
+ socket: SocketHost;
578
+ }
579
+ /** Build the socket registry, persisting attachments and tags to `database`. */
580
+ declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
255
581
  /** The contracts scoped to one shard key. */
256
582
  interface NodeShard {
583
+ /**
584
+ * Register a synchronous callback run immediately before this shard's database is closed, on every close path, forced
585
+ * or not: the place for a Durable Object instance to write what it buffers in memory. A callback that throws is logged
586
+ * and the shard is still closed. If the close itself fails and the shard stays live, the callbacks run again on the retry.
587
+ */
588
+ beforeClose: (flush: () => void) => void;
589
+ /**
590
+ * Inbound socket events for this shard's registry. Bind the shard that owns
591
+ * the sockets here, so a frame or close reaches its `webSocketMessage` and
592
+ * `webSocketClose`. See `bindShardSockets`.
593
+ */
594
+ inbound: Pick<NodeSocketHost, "onClose" | "onMessage">;
595
+ /**
596
+ * Register a synchronous check asked before the registry closes this shard for being idle: answering `true` keeps it
597
+ * open. The place for a Durable Object instance holding state in memory between requests (an open response stream) to say
598
+ * so. A check that throws counts as `true` and is logged once for the shard. The Durable Object factory registers one that
599
+ * keeps the shard open unless the instance implements `hasUnfinishedWork` and it answers false, so a class must implement it
600
+ * to take part in idle closing.
601
+ */
602
+ keepOpen: (check: () => boolean) => void;
257
603
  /** Durable key-value storage on this shard's database. */
258
- kv: ShardKvStore;
604
+ kv: NodeShardKvStore;
259
605
  /** Single-writer execution, local SQL, transactions, durable alarms. */
260
606
  shard: ShardHost;
261
607
  /** The key this shard serves. */
@@ -272,6 +618,13 @@ interface NodeShardRegistryOptions {
272
618
  * from, so its fan-out set is empty until each shard is touched again.
273
619
  */
274
620
  directory?: string;
621
+ /**
622
+ * How many file-backed shards may stay open before idle ones are closed, least recently used first (default 256). A target,
623
+ * not a hard limit: busy shards keep the registry above it, and later passes close them once idle. Applies per registry,
624
+ * so per Durable Object binding. An in-memory registry ignores it: closing one of its shards would destroy its
625
+ * data. A positive safe integer; anything else throws at construction.
626
+ */
627
+ maxOpenShards?: number;
275
628
  /** Called when a shard's durable alarm comes due. */
276
629
  onAlarm?: (shard: NodeShard) => Promise<void> | void;
277
630
  /**
@@ -289,10 +642,32 @@ interface NodeShardRegistryOptions {
289
642
  }
290
643
  /** An in-process shard registry: placement, hosting, and the fan-out key set. */
291
644
  interface NodeShardRegistry {
292
- /** Dispose every live shard. Safe to call more than once. */
293
- close: () => void;
645
+ /**
646
+ * Dispose every live shard, and refuse new work from then on: `shardFor`, a stub's `fetch` and `rearmPersistedAlarms`
647
+ * throw once this is called, so nothing reopens a shard. Safe to call more than once. A shard that a request or a socket
648
+ * close handler is still using is disposed once that work settles, unless `force` is set: then it is disposed now and
649
+ * named in a log line. A shard whose dispose fails stays live; a failure after close() returned is logged and reported by
650
+ * the next `drain()`, and the next `close()` retries it. A shutdown passes `force` after its drain has finished or
651
+ * reached its deadline, so work that never settles cannot keep a database open at exit.
652
+ */
653
+ close: (options?: {
654
+ force?: boolean;
655
+ }) => void;
294
656
  /** The `ShardDirectory` to hand the runtime. */
295
657
  directory: DirectShardDirectory;
658
+ /**
659
+ * Wait until every shard is idle: no `onFetch` or `onAlarm` call in flight (a cron or scheduled job's delivery is one), no
660
+ * promise handed to a shard's `waitUntil` pending, and no socket close handler still running, across every live shard,
661
+ * including one opened while draining. Work that starts more work is waited for too. Bounded by `timeoutMs` (30 s by
662
+ * default); resolves with what was still running when it passed, which it also logs. A graceful shutdown awaits this, then
663
+ * calls {@link NodeShardRegistry.close}; `close()` alone does not wait for any of it.
664
+ */
665
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
666
+ /**
667
+ * Whether every shard is idle right now (nothing a {@link NodeShardRegistry.drain} would wait for). Synchronous, so a caller
668
+ * that drained several things can confirm all of them are still idle at one instant before it closes anything.
669
+ */
670
+ idle: () => boolean;
296
671
  /**
297
672
  * Every shard key this registry knows about — the set `@lunora/runtime`'s
298
673
  * query coordinator fans out over.
@@ -305,27 +680,91 @@ interface NodeShardRegistry {
305
680
  * cost of visiting shards that had nothing to say.
306
681
  */
307
682
  listShardKeys: (table?: string) => ReadonlyArray<string>;
683
+ /** What is running right now, one label per shard with its counts, as a drain that timed out would report it. */
684
+ pending: () => string[];
685
+ /**
686
+ * Open every stored shard that has a persisted alarm, so the alarm is re-armed now rather than when something next sends
687
+ * that shard a request: after a restart an alarm would otherwise never fire on a shard nobody calls. Shards without one stay
688
+ * closed. Returns the keys it opened. A process serving the registry calls this once, before it takes traffic.
689
+ */
690
+ rearmPersistedAlarms: () => string[];
308
691
  /** Materialize (or reuse) the shard serving `key`. */
309
692
  shardFor: (key: string) => NodeShard;
693
+ /**
694
+ * Stop arming and claiming alarms on every shard, including one opened afterwards, leaving each durable row to re-arm after
695
+ * a restart. A shutdown calls it before draining, so no alarm starts after the drain checked for running work. One-way;
696
+ * `close()` does it too.
697
+ */
698
+ suspendAlarms: () => void;
310
699
  }
311
700
  /** Build the in-process shard registry. */
312
701
  declare const createNodeShardRegistry: (options?: NodeShardRegistryOptions) => NodeShardRegistry;
702
+ /** Options for {@link createNodeWorkflowHost}. */
703
+ interface NodeWorkflowHostOptions<Workflows extends Record<string, {
704
+ isLunoraWorkflow: true;
705
+ }>> {
706
+ /** Base env merged under the derived workflow bindings — surfaced to workflow bodies as `ctx.env` and used to resolve spawned children. */
707
+ env?: Record<string, unknown>;
708
+ /** How long (ms) the engine holds a cross-process lease while an activation runs, for stores that implement `acquire`. Defaults to 30000. */
709
+ leaseTtlMs?: number;
710
+ /** Where runs are persisted. Required — see the header for why there is no default. `createNodeWorkflowStore(database)` is the durable one. */
711
+ store: WorkflowStore;
712
+ /** The declared workflows keyed by their `lunora/workflows.ts` export name (e.g. `{ orderPipeline: orderPipeline }`). Values must be `defineWorkflow` results. */
713
+ workflows: Workflows;
714
+ }
715
+ /** A fully-wired Node workflow host. */
716
+ interface NodeWorkflowHost<Workflows extends Record<string, {
717
+ isLunoraWorkflow: true;
718
+ }>> {
719
+ /** Per-export-name `WorkflowBindingLike` — the map `ctx.workflows` consumes. */
720
+ readonly bindings: { [K in keyof Workflows]: WorkflowBindingLike; };
721
+ /**
722
+ * The caller's `env` plus one binding per workflow under its class name
723
+ * (`OrderPipelineWorkflow`), the key `ctx.exports` would carry on Cloudflare —
724
+ * merge this into a worker env so `ctx.spawn`/`ctx.parallel` resolve
725
+ * children through the same runtime.
726
+ */
727
+ readonly env: Record<string, unknown>;
728
+ /** The underlying visulima runtime — `sweep`/`signal` for a dev loop or tests. */
729
+ readonly runtime: WorkflowRuntime;
730
+ }
731
+ /**
732
+ * Create a Node workflow host: compile every declared Lunora workflow onto the
733
+ * visulima engine, derive the workflow env, and expose the per-workflow
734
+ * `WorkflowBindingLike` handles.
735
+ */
736
+ declare const createNodeWorkflowHost: <Workflows extends Record<string, {
737
+ isLunoraWorkflow: true;
738
+ }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
739
+ /** One entry of the generated `LUNORA_CRONS` map (`_generated/crons.ts`). */
740
+ interface NodeCronJob {
741
+ args?: Record<string, unknown>;
742
+ functionPath?: string;
743
+ name: string;
744
+ workflow?: string;
745
+ }
313
746
  /** Every contract this package provides, composed for one Node process. */
314
747
  interface NodePlatform<Queues extends Record<string, {
315
748
  isLunoraQueue: true;
749
+ }> = Record<string, never>, Workflows extends Record<string, {
750
+ isLunoraWorkflow: true;
316
751
  }> = Record<string, never>> {
317
752
  /** `using platform = createNodePlatform(...)` support — delegates to `close()`. */
318
753
  [Symbol.dispose]: () => void;
319
754
  /** What this target supports — see `NODE_CAPABILITIES` in `@lunora/platform`. */
320
755
  capabilities: PlatformCapabilities;
321
756
  /**
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.
757
+ * Tear this platform instance down: every resource this root built, in
758
+ * reverse construction order — the global store's own connection, every
759
+ * armed scheduler job timer, the registry's live shards, and last the shard
760
+ * host's pending alarm timer and its `better-sqlite3` database (and, with
761
+ * it, `kv`'s table — both live on the same connection). Nothing in this
762
+ * package closes these resources on its own — a `NodePlatform` a caller
763
+ * stops using without calling `close()` leaks the open file handles (plus
764
+ * their WAL/SHM sidecar files) and keeps the process alive on outstanding
765
+ * timers. Safe to call more than once. A `createNodePlatform` that throws
766
+ * unwinds the same list itself, so a failed construction leaks nothing and
767
+ * leaves nothing to call this on.
329
768
  *
330
769
  * **`close()` is a terminal state, not merely a cleanup step.** After it
331
770
  * runs: `scheduler.schedule()` throws instead of arming a fresh timer
@@ -340,21 +779,83 @@ interface NodePlatform<Queues extends Record<string, {
340
779
  * any runtime socket map or durable row. A no-op instead of a throw would
341
780
  * be indistinguishable from a working call — exactly the silent-vanishing
342
781
  * this lifecycle exists to end.
782
+ *
783
+ * `force` is for a shutdown whose drain has finished or reached its deadline:
784
+ * a shard whose socket close handler is still running is disposed now (and
785
+ * logged) instead of once the handler settles. See `NodeShardRegistry.close`.
343
786
  */
344
- close: () => void;
787
+ close: (options?: {
788
+ force?: boolean;
789
+ }) => void;
345
790
  /** In-process shard directory (see `createNodeShardRegistry` for what it can and cannot do). */
346
- directory: ShardDirectory;
791
+ directory: DirectShardDirectory;
792
+ /**
793
+ * The scheduler dispatch route, served in-process: `Request` in, shard
794
+ * response out, no listener. It answers the path `@lunora/dispatch` and
795
+ * `@lunora/scheduler` POST to. Pass it to `dispatchQueueBatch` as
796
+ * `queueFetchImpl` on `createWorker` so a queue handler's `message.run` /
797
+ * `ctx.run` reaches the shard; the env you pass there must carry `LUNORA_ORIGIN_URL` and the same
798
+ * `LUNORA_ADMIN_TOKEN` as `dispatch.adminToken`. Every request is refused
799
+ * unless `dispatch` supplies a secret.
800
+ */
801
+ dispatch: (request: Request) => Promise<Response>;
347
802
  /**
348
- * Wait for every promise handed to `shard.waitUntil` to settle.
803
+ * Wait for every promise handed to `shard.waitUntil` to settle, for every
804
+ * `mail.poll()` in flight, and for the registry's shards to go idle
805
+ * (`NodeShardRegistry.drain`): in-flight `onFetch` and `onAlarm` calls,
806
+ * including cron and scheduled-job deliveries, and each shard's own
807
+ * `waitUntil` work.
349
808
  *
350
809
  * Separate from `close()` because the two answer different questions:
351
810
  * `close()` releases handles and stays synchronous (it backs
352
811
  * `Symbol.dispose`), while draining is inherently awaitable. A graceful
353
- * shutdown is `await platform.drain()` then `platform.close()`.
812
+ * shutdown is `await platform.drain()` then `platform.close()`. Bounded by
813
+ * `timeoutMs` (30 s by default); resolves with what was still running when
814
+ * it passed.
815
+ *
816
+ * Draining is the start of shutdown: it first stops the scheduler's job and
817
+ * cron timers and every alarm timer, so nothing new starts once the drain
818
+ * has found the platform idle. Their rows are kept and re-armed after a
819
+ * restart.
354
820
  */
355
- drain: () => Promise<void>;
821
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
822
+ /**
823
+ * The `.global()` backend, or `undefined` when the caller named no database
824
+ * file for it. There is no default path, because a global store silently
825
+ * rooted at `:memory:` loses every row when the process exits.
826
+ *
827
+ * **A building block, not a wiring.** Unlike its three siblings, nothing
828
+ * downstream of this composition root reads it: a `.global()` read or write
829
+ * reaches its backend through exactly one seam, `createShardCtxDb({ globalDb
830
+ * })`, and the only thing that passes `globalDb` is the generated `shard.ts`,
831
+ * from its `d1` / `hyperdriveGlobal` config thunks. `createNodePlatform`
832
+ * constructs no shard DO, so it cannot make that hop itself. A caller that
833
+ * wants `.global()` on this host makes it: after `migrate(schema)` has
834
+ * provisioned the tables, give the generated `createShardDO` a `d1` thunk
835
+ * returning `platform.globalTables.writer({ schema, … })` — `writer` builds
836
+ * the `createSqlCtxDb` facade that seam expects, and `node-platform.test.ts`
837
+ * round-trips a row through exactly that object.
838
+ */
839
+ globalTables?: NodeGlobalStore;
840
+ /**
841
+ * Whether nothing a {@link NodePlatform.drain} would wait for is running right now. Synchronous, so a caller draining
842
+ * several platforms or registries together can confirm they are all idle at one instant.
843
+ */
844
+ idle: () => boolean;
356
845
  /** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
357
846
  kv: ShardKvStore;
847
+ /**
848
+ * Queued mail delivery, or `undefined` when the caller passed no `mail`.
849
+ * Its queue, sent ledger and key records live in `mail.path`, a database file
850
+ * of its own on its own connection, never the shard's: construction refuses a
851
+ * path that is the shard's file, the `globalTablesPath` file, or a `.sqlite3`
852
+ * file in the shard registry's `directory`.
853
+ */
854
+ mail?: NodeMailHost;
855
+ /** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
856
+ objectStorage?: R2BucketLike;
857
+ /** What is running right now (host work, scheduler deliveries, each shard's work), as a timed-out drain would report it. */
858
+ pending: () => string[];
358
859
  /**
359
860
  * The declared queues, or `undefined` when the caller declared none.
360
861
  *
@@ -363,12 +864,48 @@ interface NodePlatform<Queues extends Record<string, {
363
864
  * works when no queue exists to send to.
364
865
  */
365
866
  queues?: NodeQueueHost<Queues>;
867
+ /** Open every stored shard with a persisted alarm, so it is re-armed before traffic arrives. See `NodeShardRegistry.rearmPersistedAlarms`. */
868
+ rearmPersistedAlarms: () => string[];
366
869
  /** Delayed jobs and crons, persisted to the same database and re-armed on construction. */
367
870
  scheduler: SchedulerHost;
368
871
  /** Single-writer execution, local SQL, transactions, durable alarms. */
369
872
  shard: ShardHost;
370
873
  /** Socket registry with mutable tags and SQLite-persisted attachments. */
371
874
  sockets: SocketHost;
875
+ /**
876
+ * The declared workflows, or `undefined` when the caller declared none.
877
+ * Runs are persisted to the same `better-sqlite3` database as the shard, so
878
+ * they survive a restart without a second store to configure.
879
+ */
880
+ workflows?: NodeWorkflowHost<Workflows>;
881
+ }
882
+ /**
883
+ * `createNodePlatform`'s `mail` option: the {@link NodeMailHostOptions} plus the
884
+ * database file the mail host keeps its queue, sent ledger and key records in.
885
+ *
886
+ * Its own file, never the shard's, and there is no default: a shard transaction
887
+ * holds the shard file across awaits, and mail written inside it would be rolled
888
+ * back with it (see `composeMail`). The same reason `globalTablesPath` has none.
889
+ */
890
+ type NodePlatformMailOptions = NodeMailHostOptions & {
891
+ /** The mail database file, for example `./.lunora/mail.sqlite3`. */
892
+ path: string;
893
+ };
894
+ /**
895
+ * The secrets the dispatch route authenticates with. With neither, the route
896
+ * refuses everything.
897
+ *
898
+ * Queue and topic delivery authenticates with `adminToken` alone:
899
+ * `@lunora/dispatch` always sends `Bearer <LUNORA_ADMIN_TOKEN>` and never signs,
900
+ * so the value here must match the token the caller puts on the env it passes
901
+ * `dispatchQueueBatch`. `schedulerSecret` only verifies a signed body, which the
902
+ * scheduler's own delivery sends; queue delivery never does.
903
+ */
904
+ interface NodePlatformDispatchOptions {
905
+ /** `LUNORA_ADMIN_TOKEN`. The bearer queue and topic delivery sends, so it must match the caller's env. */
906
+ adminToken?: string;
907
+ /** `LUNORA_SCHEDULER_SECRET`. When set, a signed body is verified against it. Queue delivery does not sign. */
908
+ schedulerSecret?: string;
372
909
  }
373
910
  /**
374
911
  * Options for {@link createNodePlatform} — the shard host's (`path`,
@@ -378,23 +915,224 @@ interface NodePlatform<Queues extends Record<string, {
378
915
  * or job with nowhere to land is bookkeeping. `directory` makes the shards the
379
916
  * directory resolves for fan-out file-backed too, and `onAlarm` gives their
380
917
  * durable alarms somewhere to land.
918
+ *
919
+ * `queues`, `workflows`, `objectStorageDirectory` and `globalTablesPath` are the
920
+ * four declarations — each is absent from the returned platform when omitted.
381
921
  */
382
922
  type NodePlatformOptions<Queues extends Record<string, {
383
923
  isLunoraQueue: true;
924
+ }> = Record<string, never>, Workflows extends Record<string, {
925
+ isLunoraWorkflow: true;
384
926
  }> = Record<string, never>> = {
385
927
  /**
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.
928
+ * The app's declared crons — pass the generated `LUNORA_CRONS` map
929
+ * (`_generated/crons.ts`). Each job is armed on the scheduler and delivered
930
+ * through the same `onDispatch` a scheduled job uses, so it needs `onFetch`
931
+ * (or your own `onDispatch`) to reach a shard; a non-empty map with neither
932
+ * throws. Job names must be unique, every schedule must have a next
933
+ * occurrence, and schedules are read as UTC. The map is the whole declared
934
+ * set: a job declared by an earlier run and absent here is deleted. Omit
935
+ * the option and this process neither fires nor deletes declared jobs, so
936
+ * a script opening the same file leaves a running server's crons alone.
937
+ * Crons registered through `scheduler.cron()` are re-armed either way.
938
+ */
939
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
940
+ /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
941
+ dispatch?: NodePlatformDispatchOptions;
942
+ /**
943
+ * Database file the `.global()` tables live in — its own file, never a
944
+ * shard's, because a table every shard reads must not be inside any one of
945
+ * them. Omit when the app declares no `.global()` table; there is no
946
+ * default, for the same reason the bucket has none.
947
+ */
948
+ globalTablesPath?: string;
949
+ /**
950
+ * Deliver `@lunora/mail` sends: a durable `lunora-mail` queue drained
951
+ * through the given `transport` or, without one, Resend (`RESEND_API_KEY`), exposed as
952
+ * `platform.mail`. Its queue, sent ledger and key records live in `path`, a
953
+ * database file of their own (see {@link NodePlatformMailOptions}). Omit when
954
+ * the app sends no mail. Throws here, not on the first send, when `MAIL_FROM`
955
+ * is unset or nothing can deliver.
956
+ */
957
+ mail?: NodePlatformMailOptions;
958
+ /**
959
+ * Directory the object-storage bucket keeps its objects in, one file per
960
+ * key. Omit when the app declares no buckets — there is no default,
961
+ * because a bucket silently rooted at the process's working directory is
962
+ * worse than an absent one.
963
+ */
964
+ objectStorageDirectory?: string;
965
+ /**
966
+ * Deliver one assembled queue batch — wire this to the app worker's `queue`
967
+ * export from `createWorker`, not to bare `dispatchQueueBatch`. That export
968
+ * is the only path that hands the consumer `ctx.live`, and it takes
969
+ * `queueFetchImpl` (this platform's `dispatch`, wrapped as a `fetch`) so
970
+ * `ctx.run` reaches the shard here rather than `LUNORA_ORIGIN_URL`. Required
971
+ * alongside `queues`; without it the messages would be stored and never consumed.
389
972
  */
390
973
  onQueueBatch?: NodeQueueHostOptions<Queues>["onBatch"];
391
974
  /** The app's `defineQueue` results, keyed by export name. Omit when the app declares no queues. */
392
975
  queues?: Queues;
976
+ /** The app's `defineWorkflow` results, keyed by export name. Omit when the app declares no workflows. */
977
+ workflows?: Workflows;
393
978
  } & NodeSchedulerHostOptions & NodeShardHostOptions & NodeShardRegistryOptions;
394
979
  /** Compose every contract this package provides over one `better-sqlite3` database. */
395
980
  declare const createNodePlatform: <Queues extends Record<string, {
396
981
  isLunoraQueue: true;
397
- }> = Record<string, never>>(options?: NodePlatformOptions<Queues>) => NodePlatform<Queues>;
982
+ }> = Record<string, never>, Workflows extends Record<string, {
983
+ isLunoraWorkflow: true;
984
+ }> = Record<string, never>>(options?: NodePlatformOptions<Queues, Workflows>) => NodePlatform<Queues, Workflows>;
985
+ /** One `durable_objects.bindings[]` entry: the `env` key and the exported class behind it. */
986
+ interface NodeAppDurableObjectBinding {
987
+ className: string;
988
+ name: string;
989
+ }
990
+ /** Options for {@link createNodeAppHost}. */
991
+ interface NodeAppHostOptions {
992
+ /**
993
+ * The app's declared crons — the generated `LUNORA_CRONS` map. Armed on the {@link NodeAppHostOptions.shardBinding} platform and
994
+ * delivered to its default shard, as `createNodePlatform`'s `crons` are. The map is the whole declared set, so a host built
995
+ * without a job an earlier one declared deletes it.
996
+ */
997
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
998
+ /**
999
+ * Directory the shard databases live in, one subdirectory per binding. Omit for in-memory shards, which lose every row when the
1000
+ * host closes.
1001
+ */
1002
+ dataDirectory?: string;
1003
+ /** The wrangler config's `durable_objects.bindings`. Each `className` must be a named export of `worker`. */
1004
+ durableObjects: ReadonlyArray<NodeAppDurableObjectBinding>;
1005
+ /** Plain values for `env`: vars, dev vars, and any binding the caller composes itself. A Durable Object binding of the same name wins. */
1006
+ env?: Record<string, unknown>;
1007
+ /** How many shards each binding may keep open before idle ones are closed (default 256), as the registry's `maxOpenShards`. */
1008
+ maxOpenShards?: number;
1009
+ /** The Durable Object binding whose shards run functions, which is where crons fire. Defaults to `SHARD`. */
1010
+ shardBinding?: string;
1011
+ /** The imported worker module. */
1012
+ worker: Record<string, unknown>;
1013
+ }
1014
+ /** A worker module composed over this host. */
1015
+ interface NodeAppHost {
1016
+ /**
1017
+ * Drain, then close: wait under one deadline (`timeoutMs`, 30 s by default) for the requests `fetch` is still answering, the
1018
+ * worker's `waitUntil` work, and every
1019
+ * platform to go idle (in-flight shard requests, alarms, cron deliveries and each shard's own `waitUntil` work), then close
1020
+ * every platform, cron timers included. The close runs whether or not the drain finished in time, so a reload never opens the
1021
+ * databases while this host still holds them. Resolves with what the drain cut off or saw fail. Safe to call more than once.
1022
+ */
1023
+ close: (options?: DrainOptions) => Promise<DrainResult>;
1024
+ /** The worker's `fetch`, bound to the composed `env`. Hand it to `createNodeHttpServer`. */
1025
+ fetch: (request: Request) => Promise<Response>;
1026
+ /**
1027
+ * Open every stored shard with a persisted alarm, so its alarm fires without waiting for a request to reach it. Call once
1028
+ * the host serves; a shard opens its database here, so a caller replacing an older host calls it after closing that one.
1029
+ */
1030
+ rearmPersistedAlarms: () => string[];
1031
+ }
1032
+ /**
1033
+ * Throw what `createNodeAppHost` would refuse for `options`, without opening a database or arming a timer: the default export,
1034
+ * every binding's name and class, and the declared crons. `createNodeAppHost` runs it before building anything, so a refused composition
1035
+ * changes no stored state (cron rows included); a caller replacing a running host runs it first, so a refused candidate leaves
1036
+ * that host serving.
1037
+ */
1038
+ declare const checkNodeAppHost: (options: NodeAppHostOptions) => void;
1039
+ /** Compose `worker` over one in-process platform per Durable Object binding. */
1040
+ declare const createNodeAppHost: (options: NodeAppHostOptions) => NodeAppHost;
1041
+ /** What a Durable Object instance must answer on this host. The socket and alarm hooks are optional, as on Cloudflare. */
1042
+ interface NodeDurableObjectInstance {
1043
+ alarm?: () => Promise<void> | void;
1044
+ fetch: (request: Request) => Promise<Response> | Response;
1045
+ /** Write what the instance buffers in memory; the host calls it right before closing the shard's database. */
1046
+ flushBeforeClose?: () => void;
1047
+ /**
1048
+ * Whether the instance holds work in memory a close would lose (a response body still streaming, a side effect still
1049
+ * running); while it does, the host does not close the shard as idle. A class without it never has its shard closed as
1050
+ * idle: the host cannot tell whether a body it returned is still read.
1051
+ */
1052
+ hasUnfinishedWork?: () => boolean;
1053
+ webSocketClose?: (socket: unknown, code: number, reason: string, wasClean: boolean) => Promise<void> | void;
1054
+ webSocketMessage?: (socket: unknown, data: ArrayBuffer | string) => Promise<void> | void;
1055
+ }
1056
+ type NodeDurableObjectClass = new (state: never, env: Record<string, unknown>) => NodeDurableObjectInstance;
1057
+ /** The instance of `DurableObject` for a shard, constructed on first use and once it is ready. */
1058
+ declare const createNodeDurableObjectFactory: (DurableObject: NodeDurableObjectClass, env: Record<string, unknown>) => ((shard: NodeShard) => Promise<NodeDurableObjectInstance>);
1059
+ /** Serve `options.fetch` over `node:http`. Resolves once the server is listening. */
1060
+ declare const createNodeHttpServer: (options: NodeHttpServerOptions) => Promise<NodeHttpServer>;
1061
+ /** Options for {@link createNodeHttpServer}. */
1062
+ interface NodeHttpServerOptions {
1063
+ /** The app worker's `fetch`, already bound to its env and context. */
1064
+ fetch: (request: Request) => Promise<Response> | Response;
1065
+ /** Host to bind. Defaults to the loopback interface. */
1066
+ host?: string;
1067
+ /**
1068
+ * The public base URL the app is served at, e.g. `https://app.example`. Every request URL uses its origin, so origin-sensitive
1069
+ * behaviour (CSRF, WebSocket origin checks, cookie rules) sees the public scheme behind a TLS proxy. The client's `Host` header is
1070
+ * never used. Defaults to the bound `http://host:port`, which is only allowed for a loopback `host`: binding a non-loopback address
1071
+ * (e.g. `0.0.0.0` or a LAN IP) without `origin` makes {@link createNodeHttpServer} reject, because browsers would send that address
1072
+ * as `Origin` and fail the CSRF check. Set `origin` to the URL users open.
1073
+ */
1074
+ origin?: string;
1075
+ /** Port to bind. `0` (the default) picks a free ephemeral port. */
1076
+ port?: number;
1077
+ }
1078
+ /** A listening server. */
1079
+ interface NodeHttpServer {
1080
+ /** Stop accepting connections and end every open one, streams included. */
1081
+ close: () => Promise<void>;
1082
+ /**
1083
+ * Stop accepting connections, then wait until every HTTP response that was in progress when the drain began has been written
1084
+ * to the end or its client has gone, or until the deadline passes (`timeoutMs`, 30 s by default). A request that still
1085
+ * arrives on an open connection is answered with keep-alive off and is not waited for. Event streams (`text/event-stream`)
1086
+ * and WebSockets are endless by design and are not waited for; {@link NodeHttpServer.close} ends them. Resolves with what was
1087
+ * still unfinished when the deadline passed, which it also logs.
1088
+ */
1089
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
1090
+ /** The `http://host:port` origin the server answers on. */
1091
+ origin: string;
1092
+ }
1093
+ /**
1094
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
1095
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
1096
+ * Declared here structurally so this package does not depend on
1097
+ * `@lunora/hyperdrive` for a type.
1098
+ */
1099
+ interface NodeHyperdriveBinding {
1100
+ connectionString: string;
1101
+ database: string;
1102
+ host: string;
1103
+ password: string;
1104
+ port: number;
1105
+ user: string;
1106
+ }
1107
+ /**
1108
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
1109
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
1110
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
1111
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
1112
+ * unchanged.
1113
+ *
1114
+ * There is no pool or query cache in front of the database here: the driver
1115
+ * the app constructs from `connectionString` connects to it directly, so its own
1116
+ * pool settings are the only ones that apply.
1117
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
1118
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
1119
+ * which becomes the binding's `host`.
1120
+ *
1121
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
1122
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
1123
+ * throw: they cannot carry it, so a pool built from them would silently connect
1124
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
1125
+ * from `connectionString`, which keeps every query option.
1126
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
1127
+ */
1128
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
1129
+ interface NodeProfileHandlerOptions {
1130
+ /** The bearer a caller must present. Required and non-empty: an empty token would make the endpoint open to anyone. */
1131
+ token: string;
1132
+ }
1133
+ type NodeProfileHandler = (request: Request) => Promise<Response>;
1134
+ /** The public handler: the real profiler, guarded by `token`. */
1135
+ declare const createNodeProfileHandler: ({ token }: NodeProfileHandlerOptions) => NodeProfileHandler;
398
1136
  /** Options for {@link createNodeR2Bucket}. */
399
1137
  interface NodeR2BucketOptions {
400
1138
  /** The bucket directory — created on first write. Objects live here, one file per key. */
@@ -402,10 +1140,41 @@ interface NodeR2BucketOptions {
402
1140
  }
403
1141
  /**
404
1142
  * Create an `R2BucketLike` over the local filesystem. Any object shape
405
- * `createStorage({ bucket })` accepts — `put`/`get`/`head`/`delete`/`list` —
1143
+ * `createStorage({ bucket, bucketName })` accepts — `put`/`get`/`head`/`delete`/`list` —
406
1144
  * maps directly onto a file operation.
407
1145
  */
408
1146
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
1147
+ /** The shape `ctx.secrets` reads off `env[name]`: a Cloudflare Secrets Store secret binding. */
1148
+ interface NodeSecretBinding {
1149
+ get: () => Promise<string>;
1150
+ }
1151
+ /**
1152
+ * Build the `ctx.secrets` bindings for a Node host from environment variables:
1153
+ * one binding per name, spread into the `env` the worker and shard are built
1154
+ * over. `ctx.secrets.get(name)` then reads `source[name]`.
1155
+ *
1156
+ * Names are listed rather than every variable in `source` being bound, for the
1157
+ * same reason a wrangler config lists `secrets_store_secrets[]`: `ctx.secrets`
1158
+ * reaches only what was granted to it. It also keeps the bindings off names the
1159
+ * env already carries as plain strings (`LUNORA_ADMIN_TOKEN` and the like),
1160
+ * which the runtime reads as strings and a binding object would break; a
1161
+ * `LUNORA_*` name is refused for that reason.
1162
+ *
1163
+ * The value is read when `get()` is called, so an unused secret never has to be
1164
+ * set. An unset or empty variable rejects the call.
1165
+ * @param names The secret names the app reads through `ctx.secrets`.
1166
+ * @param source Where values come from; `process.env` unless given.
1167
+ */
1168
+ declare const createNodeSecretBindings: (names: ReadonlyArray<string>, source?: Readonly<Record<string, string | undefined>>) => Record<string, NodeSecretBinding>;
1169
+ /**
1170
+ * Present the node shard registry as the `ShardNamespaceLike` a worker is built
1171
+ * over (`createWorker({ shardDO })`).
1172
+ *
1173
+ * The registry names its id derivation `idForName`, which is the
1174
+ * `ShardDirectory` spelling; the worker reads Cloudflare's `idFromName`. Both
1175
+ * return the key itself here, so a stub from either route reaches the same shard.
1176
+ */
1177
+ declare const createNodeShardNamespace: (directory: DirectShardDirectory) => ShardNamespaceLike;
409
1178
  /**
410
1179
  * The `DurableObjectState` subset `ShardDO` consumes.
411
1180
  *
@@ -422,14 +1191,17 @@ interface NodeShardState {
422
1191
  id: {
423
1192
  name?: string;
424
1193
  };
1194
+ /** Open a connection pair. Read by `@lunora/platform-cloudflare`'s socket host, which has no `WebSocketPair` here. */
1195
+ openSocketPair: () => {
1196
+ client: unknown;
1197
+ server: unknown;
1198
+ };
425
1199
  storage: {
426
1200
  delete: (key: string) => Promise<boolean>;
427
1201
  deleteAlarm: () => Promise<void>;
428
1202
  get: <T = unknown>(key: string) => Promise<T | undefined>;
429
1203
  getAlarm: () => Promise<number | null>;
430
- list: <T = unknown>(options?: {
431
- prefix?: string;
432
- }) => Promise<Map<string, T>>;
1204
+ list: <T = unknown>(options?: NodeShardKvListOptions) => Promise<Map<string, T>>;
433
1205
  put: (key: string, value: unknown) => Promise<void>;
434
1206
  setAlarm: (scheduledTime: Date | number) => Promise<void>;
435
1207
  sql: {
@@ -438,6 +1210,8 @@ interface NodeShardState {
438
1210
  };
439
1211
  transaction: <T>(closure: () => Promise<T>) => Promise<T>;
440
1212
  };
1213
+ /** Build the upgrade response for a pair's client end. A Node `Response` cannot carry status 101, so this is a marker. */
1214
+ upgradeResponse: (client: unknown) => Response;
441
1215
  waitUntil: (promise: Promise<unknown>) => void;
442
1216
  }
443
1217
  /**
@@ -451,72 +1225,83 @@ interface NodeShardState {
451
1225
  * one local `wrangler dev` takes — whereas supplying a stub that resolves would
452
1226
  * report a point-in-time restore that never happened.
453
1227
  */
454
- declare const createNodeShardState: (shard: NodeShard) => NodeShardState;
455
1228
  /**
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.
1229
+ * `onBlockConcurrency` sees each `blockConcurrencyWhile` promise as it starts, so a caller can tell when the work an object's
1230
+ * constructor gated behind it has finished (see `createNodeDurableObjectFactory`).
459
1231
  */
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;
1232
+ declare const createNodeShardState: (shard: NodeShard, onBlockConcurrency?: (work: Promise<unknown>) => void) => NodeShardState;
1233
+ /** The two socket hooks a `ShardDO` runs on the Cloudflare runtime's behalf. */
1234
+ interface ShardSocketHooks {
1235
+ webSocketClose(ws: unknown, code: number, reason: string, wasClean: boolean): unknown;
1236
+ webSocketMessage(ws: unknown, message: string | ArrayBuffer): unknown;
505
1237
  }
506
1238
  /**
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.
1239
+ * Deliver a shard's inbound socket events. The Cloudflare runtime calls
1240
+ * `webSocketMessage` and `webSocketClose` on the Durable Object for a hibernated
1241
+ * socket. On Node nothing does, so the embedder calls this once per shard
1242
+ * instance, at the same point it builds the shard.
510
1243
  */
511
- declare const createNodeWorkflowHost: <Workflows extends Record<string, {
512
- isLunoraWorkflow: true;
513
- }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
1244
+ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShard["inbound"], "onClose" | "onMessage">) => void;
514
1245
  /**
515
1246
  * Build a durable {@link WorkflowStore} over a `better-sqlite3` connection.
516
1247
  * Pass the result as `createNodeWorkflowHost({ store })`.
517
1248
  */
518
1249
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
519
- export {
1250
+ export { DEFAULT_DRAIN_TIMEOUT_MS,
1251
+ /**
1252
+ * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
1253
+ * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
1254
+ * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
1255
+ * scheduler registry.
1256
+ *
1257
+ * Promoted from `@lunora/platform`'s `node:sqlite` reference host
1258
+ * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
1259
+ * durability half of each contract actually holds: alarms and scheduler jobs
1260
+ * are persisted **and re-armed on construction**, socket attachments and tags
1261
+ * live in SQLite rather than a `Map`, and `.global()` tables run the real
1262
+ * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
1263
+ * a restart test — a second host over the same database file — not only by the
1264
+ * TCK's simulated recycle.
1265
+ *
1266
+ * Three suites run against this package: `@lunora/platform/conformance`'s host
1267
+ * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
1268
+ * lifecycle/global-store tests.
1269
+ *
1270
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1271
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1272
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1273
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1274
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1275
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1276
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1277
+ * is the one combination that fails at runtime with no diagnostic before it.
1278
+ *
1279
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1280
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1281
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1282
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1283
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1284
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1285
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1286
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1287
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1288
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1289
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1290
+ * transport, for a process that composes it and polls it, as the server
1291
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1292
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1293
+ * a queued send is not delivered.
1294
+ *
1295
+ * `lunora deploy --target node` bundles an app into a container build context
1296
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1297
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1298
+ *
1299
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1300
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1301
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1302
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
1303
+ */
1304
+ type DrainOptions,
520
1305
  /**
521
1306
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
522
1307
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -536,18 +1321,41 @@ export {
536
1321
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
537
1322
  * lifecycle/global-store tests.
538
1323
  *
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`.
1324
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1325
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1326
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1327
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1328
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1329
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1330
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1331
+ * is the one combination that fails at runtime with no diagnostic before it.
1332
+ *
1333
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1334
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1335
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1336
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1337
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1338
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1339
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1340
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1341
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1342
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1343
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1344
+ * transport, for a process that composes it and polls it, as the server
1345
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1346
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1347
+ * a queued send is not delivered.
1348
+ *
1349
+ * `lunora deploy --target node` bundles an app into a container build context
1350
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1351
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1352
+ *
1353
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1354
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1355
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1356
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
549
1357
  */
550
- type NodeGlobalContextDatabaseOptions,
1358
+ type DrainResult,
551
1359
  /**
552
1360
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
553
1361
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -567,18 +1375,41 @@ type NodeGlobalContextDatabaseOptions,
567
1375
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
568
1376
  * lifecycle/global-store tests.
569
1377
  *
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
579
- * `plans/234-node-host-findings.md`.
1378
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1379
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1380
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1381
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1382
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1383
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1384
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1385
+ * is the one combination that fails at runtime with no diagnostic before it.
1386
+ *
1387
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1388
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1389
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1390
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1391
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1392
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1393
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1394
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1395
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1396
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1397
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1398
+ * transport, for a process that composes it and polls it, as the server
1399
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1400
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1401
+ * a queued send is not delivered.
1402
+ *
1403
+ * `lunora deploy --target node` bundles an app into a container build context
1404
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1405
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1406
+ *
1407
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1408
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1409
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1410
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
580
1411
  */
581
- type NodeGlobalStore,
1412
+ type DrainTimer,
582
1413
  /**
583
1414
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
584
1415
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -598,15 +1429,38 @@ type NodeGlobalStore,
598
1429
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
599
1430
  * lifecycle/global-store tests.
600
1431
  *
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
610
- * `plans/234-node-host-findings.md`.
611
- */
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 };
1432
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1433
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1434
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1435
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1436
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1437
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1438
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1439
+ * is the one combination that fails at runtime with no diagnostic before it.
1440
+ *
1441
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1442
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1443
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1444
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1445
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1446
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1447
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1448
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1449
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1450
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1451
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1452
+ * transport, for a process that composes it and polls it, as the server
1453
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1454
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1455
+ * a queued send is not delivered.
1456
+ *
1457
+ * `lunora deploy --target node` bundles an app into a container build context
1458
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1459
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1460
+ *
1461
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1462
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1463
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1464
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
1465
+ */
1466
+ type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeAppDurableObjectBinding, type NodeAppHost, type NodeAppHostOptions, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeDurableObjectClass, type NodeDurableObjectInstance, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodeMailHost, type NodeMailHostOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformMailOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardKvListOptions, type NodeShardKvStore, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, checkNodeAppHost, createNodeAppHost, createNodeDispatchRoute, createNodeDurableObjectFactory, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };