@lunora/platform-node 1.0.0-alpha.221 → 1.0.0-alpha.222

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
+ import { QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost, ShardKvStore, 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, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike } from '@lunora/platform';
5
5
  import { Mailer, QueueLike, MailEnv, MailTransport } from '@lunora/mail';
6
6
  import { WorkflowBindingLike } from '@lunora/workflow';
7
7
  import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
@@ -155,78 +155,6 @@ interface NodeGlobalStore {
155
155
  * which is the whole point of the dialect seam.
156
156
  */
157
157
  declare const createNodeGlobalStore: (options?: NodeGlobalStoreOptions) => NodeGlobalStore;
158
- /** Serve `options.fetch` over `node:http`. Resolves once the server is listening. */
159
- declare const createNodeHttpServer: (options: NodeHttpServerOptions) => Promise<NodeHttpServer>;
160
- /** Options for {@link createNodeHttpServer}. */
161
- interface NodeHttpServerOptions {
162
- /** The app worker's `fetch`, already bound to its env and context. */
163
- fetch: (request: Request) => Promise<Response> | Response;
164
- /** Host to bind. Defaults to the loopback interface. */
165
- host?: string;
166
- /**
167
- * The public base URL the app is served at, e.g. `https://app.example`. Every request URL uses its origin, so origin-sensitive
168
- * behaviour (CSRF, WebSocket origin checks, cookie rules) sees the public scheme behind a TLS proxy. The client's `Host` header is
169
- * never used. Defaults to the bound `http://host:port`, which is only allowed for a loopback `host`: binding a non-loopback address
170
- * (e.g. `0.0.0.0` or a LAN IP) without `origin` makes {@link createNodeHttpServer} reject, because browsers would send that address
171
- * as `Origin` and fail the CSRF check. Set `origin` to the URL users open.
172
- */
173
- origin?: string;
174
- /** Port to bind. `0` (the default) picks a free ephemeral port. */
175
- port?: number;
176
- }
177
- /** A listening server. */
178
- interface NodeHttpServer {
179
- /** Stop accepting connections and end every open one, streams included. */
180
- close: () => Promise<void>;
181
- /**
182
- * Stop accepting connections, then wait until every HTTP response that was in progress when the drain began has been written
183
- * to the end or its client has gone, or until the deadline passes (`timeoutMs`, 30 s by default). A request that still
184
- * arrives on an open connection is answered with keep-alive off and is not waited for. Event streams (`text/event-stream`)
185
- * and WebSockets are endless by design and are not waited for; {@link NodeHttpServer.close} ends them. Resolves with what was
186
- * still unfinished when the deadline passed, which it also logs.
187
- */
188
- drain: (options?: DrainOptions) => Promise<DrainResult>;
189
- /** The `http://host:port` origin the server answers on. */
190
- origin: string;
191
- }
192
- /**
193
- * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
194
- * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
195
- * Declared here structurally so this package does not depend on
196
- * `@lunora/hyperdrive` for a type.
197
- */
198
- interface NodeHyperdriveBinding {
199
- connectionString: string;
200
- database: string;
201
- host: string;
202
- password: string;
203
- port: number;
204
- user: string;
205
- }
206
- /**
207
- * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
208
- * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
209
- * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
210
- * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
211
- * unchanged.
212
- *
213
- * There is no pool or query cache in front of the database here: the driver
214
- * the app constructs from `connectionString` connects to it directly, so its own
215
- * pool settings are the only ones that apply.
216
- * A Postgres URL may name a Unix socket the libpq way: an empty host with the
217
- * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
218
- * which becomes the binding's `host`.
219
- *
220
- * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
221
- * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
222
- * throw: they cannot carry it, so a pool built from them would silently connect
223
- * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
224
- * from `connectionString`, which keeps every query option.
225
- * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
226
- */
227
- declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
228
- /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
229
- declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
230
158
  /** Options for {@link createNodeMailHost}. */
231
159
  interface NodeMailHostOptions {
232
160
  /**
@@ -553,7 +481,8 @@ interface NodeShardHostOptions {
553
481
  * rather than closing `database` directly, so the alarm timer and the
554
482
  * connection are always retired together.
555
483
  */
556
- declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
484
+ /** What {@link createNodeShardHost} returns. */
485
+ interface NodeShardHostParts {
557
486
  /** Settles once every alarm delivery running now (its handler and any retry write) has; `undefined` when none is. */
558
487
  alarmsSettled: () => Promise<unknown> | undefined;
559
488
  database: Database.Database;
@@ -566,7 +495,8 @@ declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
566
495
  suspendAlarms: () => void;
567
496
  /** The failures recorded since the last call, which a drain reports in its result; each is also logged when it happens. */
568
497
  takeFailures: () => string[];
569
- };
498
+ }
499
+ declare const createNodeShardHost: (options?: NodeShardHostOptions) => NodeShardHostParts;
570
500
  /** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
571
501
  interface NodeServerEnd {
572
502
  close: (code?: number, reason?: string) => void;
@@ -797,7 +727,7 @@ interface NodePlatform<Queues extends Record<string, {
797
727
  force?: boolean;
798
728
  }) => void;
799
729
  /** In-process shard directory (see `createNodeShardRegistry` for what it can and cannot do). */
800
- directory: ShardDirectory;
730
+ directory: DirectShardDirectory;
801
731
  /**
802
732
  * The scheduler dispatch route, served in-process: `Request` in, shard
803
733
  * response out, no listener. It answers the path `@lunora/dispatch` and
@@ -991,6 +921,142 @@ declare const createNodePlatform: <Queues extends Record<string, {
991
921
  }> = Record<string, never>, Workflows extends Record<string, {
992
922
  isLunoraWorkflow: true;
993
923
  }> = Record<string, never>>(options?: NodePlatformOptions<Queues, Workflows>) => NodePlatform<Queues, Workflows>;
924
+ /** One `durable_objects.bindings[]` entry: the `env` key and the exported class behind it. */
925
+ interface NodeAppDurableObjectBinding {
926
+ className: string;
927
+ name: string;
928
+ }
929
+ /** Options for {@link createNodeAppHost}. */
930
+ interface NodeAppHostOptions {
931
+ /**
932
+ * The app's declared crons — the generated `LUNORA_CRONS` map. Armed on the {@link NodeAppHostOptions.shardBinding} platform and
933
+ * delivered to its default shard, as `createNodePlatform`'s `crons` are. The map is the whole declared set, so a host built
934
+ * without a job an earlier one declared deletes it.
935
+ */
936
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
937
+ /**
938
+ * Directory the shard databases live in, one subdirectory per binding. Omit for in-memory shards, which lose every row when the
939
+ * host closes.
940
+ */
941
+ dataDirectory?: string;
942
+ /** The wrangler config's `durable_objects.bindings`. Each `className` must be a named export of `worker`. */
943
+ durableObjects: ReadonlyArray<NodeAppDurableObjectBinding>;
944
+ /** Plain values for `env`: vars, dev vars, and any binding the caller composes itself. A Durable Object binding of the same name wins. */
945
+ env?: Record<string, unknown>;
946
+ /** The Durable Object binding whose shards run functions, which is where crons fire. Defaults to `SHARD`. */
947
+ shardBinding?: string;
948
+ /** The imported worker module. */
949
+ worker: Record<string, unknown>;
950
+ }
951
+ /** A worker module composed over this host. */
952
+ interface NodeAppHost {
953
+ /**
954
+ * Drain, then close: wait under one deadline (`timeoutMs`, 30 s by default) for the requests `fetch` is still answering, the
955
+ * worker's `waitUntil` work, and every
956
+ * platform to go idle (in-flight shard requests, alarms, cron deliveries and each shard's own `waitUntil` work), then close
957
+ * every platform, cron timers included. The close runs whether or not the drain finished in time, so a reload never opens the
958
+ * databases while this host still holds them. Resolves with what the drain cut off or saw fail. Safe to call more than once.
959
+ */
960
+ close: (options?: DrainOptions) => Promise<DrainResult>;
961
+ /** The worker's `fetch`, bound to the composed `env`. Hand it to `createNodeHttpServer`. */
962
+ fetch: (request: Request) => Promise<Response>;
963
+ /**
964
+ * Open every stored shard with a persisted alarm, so its alarm fires without waiting for a request to reach it. Call once
965
+ * the host serves; a shard opens its database here, so a caller replacing an older host calls it after closing that one.
966
+ */
967
+ rearmPersistedAlarms: () => string[];
968
+ }
969
+ /**
970
+ * Throw what `createNodeAppHost` would refuse for `options`, without opening a database or arming a timer: the default export,
971
+ * every binding's name and class, and the declared crons. `createNodeAppHost` runs it before building anything, so a refused composition
972
+ * changes no stored state (cron rows included); a caller replacing a running host runs it first, so a refused candidate leaves
973
+ * that host serving.
974
+ */
975
+ declare const checkNodeAppHost: (options: NodeAppHostOptions) => void;
976
+ /** Compose `worker` over one in-process platform per Durable Object binding. */
977
+ declare const createNodeAppHost: (options: NodeAppHostOptions) => NodeAppHost;
978
+ /** What a Durable Object instance must answer on this host. The socket and alarm hooks are optional, as on Cloudflare. */
979
+ interface NodeDurableObjectInstance {
980
+ alarm?: () => Promise<void> | void;
981
+ fetch: (request: Request) => Promise<Response> | Response;
982
+ webSocketClose?: (socket: unknown, code: number, reason: string, wasClean: boolean) => Promise<void> | void;
983
+ webSocketMessage?: (socket: unknown, data: ArrayBuffer | string) => Promise<void> | void;
984
+ }
985
+ type NodeDurableObjectClass = new (state: never, env: Record<string, unknown>) => NodeDurableObjectInstance;
986
+ /** The instance of `DurableObject` for a shard, constructed on first use and once it is ready. */
987
+ declare const createNodeDurableObjectFactory: (DurableObject: NodeDurableObjectClass, env: Record<string, unknown>) => ((shard: NodeShard) => Promise<NodeDurableObjectInstance>);
988
+ /** Serve `options.fetch` over `node:http`. Resolves once the server is listening. */
989
+ declare const createNodeHttpServer: (options: NodeHttpServerOptions) => Promise<NodeHttpServer>;
990
+ /** Options for {@link createNodeHttpServer}. */
991
+ interface NodeHttpServerOptions {
992
+ /** The app worker's `fetch`, already bound to its env and context. */
993
+ fetch: (request: Request) => Promise<Response> | Response;
994
+ /** Host to bind. Defaults to the loopback interface. */
995
+ host?: string;
996
+ /**
997
+ * The public base URL the app is served at, e.g. `https://app.example`. Every request URL uses its origin, so origin-sensitive
998
+ * behaviour (CSRF, WebSocket origin checks, cookie rules) sees the public scheme behind a TLS proxy. The client's `Host` header is
999
+ * never used. Defaults to the bound `http://host:port`, which is only allowed for a loopback `host`: binding a non-loopback address
1000
+ * (e.g. `0.0.0.0` or a LAN IP) without `origin` makes {@link createNodeHttpServer} reject, because browsers would send that address
1001
+ * as `Origin` and fail the CSRF check. Set `origin` to the URL users open.
1002
+ */
1003
+ origin?: string;
1004
+ /** Port to bind. `0` (the default) picks a free ephemeral port. */
1005
+ port?: number;
1006
+ }
1007
+ /** A listening server. */
1008
+ interface NodeHttpServer {
1009
+ /** Stop accepting connections and end every open one, streams included. */
1010
+ close: () => Promise<void>;
1011
+ /**
1012
+ * Stop accepting connections, then wait until every HTTP response that was in progress when the drain began has been written
1013
+ * to the end or its client has gone, or until the deadline passes (`timeoutMs`, 30 s by default). A request that still
1014
+ * arrives on an open connection is answered with keep-alive off and is not waited for. Event streams (`text/event-stream`)
1015
+ * and WebSockets are endless by design and are not waited for; {@link NodeHttpServer.close} ends them. Resolves with what was
1016
+ * still unfinished when the deadline passed, which it also logs.
1017
+ */
1018
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
1019
+ /** The `http://host:port` origin the server answers on. */
1020
+ origin: string;
1021
+ }
1022
+ /**
1023
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
1024
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
1025
+ * Declared here structurally so this package does not depend on
1026
+ * `@lunora/hyperdrive` for a type.
1027
+ */
1028
+ interface NodeHyperdriveBinding {
1029
+ connectionString: string;
1030
+ database: string;
1031
+ host: string;
1032
+ password: string;
1033
+ port: number;
1034
+ user: string;
1035
+ }
1036
+ /**
1037
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
1038
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
1039
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
1040
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
1041
+ * unchanged.
1042
+ *
1043
+ * There is no pool or query cache in front of the database here: the driver
1044
+ * the app constructs from `connectionString` connects to it directly, so its own
1045
+ * pool settings are the only ones that apply.
1046
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
1047
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
1048
+ * which becomes the binding's `host`.
1049
+ *
1050
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
1051
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
1052
+ * throw: they cannot carry it, so a pool built from them would silently connect
1053
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
1054
+ * from `connectionString`, which keeps every query option.
1055
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
1056
+ */
1057
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
1058
+ /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
1059
+ declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
994
1060
  interface NodeProfileHandlerOptions {
995
1061
  /** The bearer a caller must present. Required and non-empty: an empty token would make the endpoint open to anyone. */
996
1062
  token: string;
@@ -1092,7 +1158,11 @@ interface NodeShardState {
1092
1158
  * one local `wrangler dev` takes — whereas supplying a stub that resolves would
1093
1159
  * report a point-in-time restore that never happened.
1094
1160
  */
1095
- declare const createNodeShardState: (shard: NodeShard) => NodeShardState;
1161
+ /**
1162
+ * `onBlockConcurrency` sees each `blockConcurrencyWhile` promise as it starts, so a caller can tell when the work an object's
1163
+ * constructor gated behind it has finished (see `createNodeDurableObjectFactory`).
1164
+ */
1165
+ declare const createNodeShardState: (shard: NodeShard, onBlockConcurrency?: (work: Promise<unknown>) => void) => NodeShardState;
1096
1166
  /** The two socket hooks a `ShardDO` runs on the Cloudflare runtime's behalf. */
1097
1167
  interface ShardSocketHooks {
1098
1168
  webSocketClose(ws: unknown, code: number, reason: string, wasClean: boolean): unknown;
@@ -1139,30 +1209,30 @@ export { DEFAULT_DRAIN_TIMEOUT_MS,
1139
1209
  * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1140
1210
  * is the one combination that fails at runtime with no diagnostic before it.
1141
1211
  *
1142
- * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1143
- * nothing here owns a timer, so queue delivery is driven by an explicit
1144
- * `poll()`. What exists is the listener a dev server would sit on:
1145
- * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1146
- * streaming the response body, and `createNodeShardNamespace` presents the
1147
- * registry as the `shardDO` namespace that worker routes to. Also absent are
1148
- * the Cloudflare product bindings with no local
1149
- * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1150
- * Engine, Pipelines. `ctx.secrets` reads environment variables through
1151
- * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1152
- * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1153
- * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1154
- * (`./node-mail-host`) through Resend or a caller-supplied transport.
1212
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1213
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1214
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1215
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1216
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1217
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1218
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1219
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1220
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1221
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1222
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1223
+ * transport, for a process that composes it and polls it, as the server
1224
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1225
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1226
+ * a queued send is not delivered.
1155
1227
  *
1156
1228
  * `lunora deploy --target node` bundles an app into a container build context
1157
1229
  * whose generated entry composes this package (crons, `ctx.secrets`,
1158
1230
  * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1159
1231
  *
1160
1232
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1161
- * for `provision` — which reports, once, which declared features this target
1162
- * cannot serve, and writes nothing: there is no hosted control plane to deploy
1163
- * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1164
- * server, which is why both statements above hold at once. See
1165
- * `plans/234-node-host-findings.md`.
1233
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1234
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1235
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
1166
1236
  */
1167
1237
  type DrainOptions,
1168
1238
  /**
@@ -1193,30 +1263,30 @@ type DrainOptions,
1193
1263
  * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1194
1264
  * is the one combination that fails at runtime with no diagnostic before it.
1195
1265
  *
1196
- * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1197
- * nothing here owns a timer, so queue delivery is driven by an explicit
1198
- * `poll()`. What exists is the listener a dev server would sit on:
1199
- * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1200
- * streaming the response body, and `createNodeShardNamespace` presents the
1201
- * registry as the `shardDO` namespace that worker routes to. Also absent are
1202
- * the Cloudflare product bindings with no local
1203
- * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1204
- * Engine, Pipelines. `ctx.secrets` reads environment variables through
1205
- * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1206
- * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1207
- * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1208
- * (`./node-mail-host`) through Resend or a caller-supplied transport.
1266
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1267
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1268
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1269
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1270
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1271
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1272
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1273
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1274
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1275
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1276
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1277
+ * transport, for a process that composes it and polls it, as the server
1278
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1279
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1280
+ * a queued send is not delivered.
1209
1281
  *
1210
1282
  * `lunora deploy --target node` bundles an app into a container build context
1211
1283
  * whose generated entry composes this package (crons, `ctx.secrets`,
1212
1284
  * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1213
1285
  *
1214
1286
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1215
- * for `provision` — which reports, once, which declared features this target
1216
- * cannot serve, and writes nothing: there is no hosted control plane to deploy
1217
- * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1218
- * server, which is why both statements above hold at once. See
1219
- * `plans/234-node-host-findings.md`.
1287
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1288
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1289
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
1220
1290
  */
1221
1291
  type DrainResult,
1222
1292
  /**
@@ -1247,30 +1317,30 @@ type DrainResult,
1247
1317
  * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1248
1318
  * is the one combination that fails at runtime with no diagnostic before it.
1249
1319
  *
1250
- * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1251
- * nothing here owns a timer, so queue delivery is driven by an explicit
1252
- * `poll()`. What exists is the listener a dev server would sit on:
1253
- * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1254
- * streaming the response body, and `createNodeShardNamespace` presents the
1255
- * registry as the `shardDO` namespace that worker routes to. Also absent are
1256
- * the Cloudflare product bindings with no local
1257
- * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1258
- * Engine, Pipelines. `ctx.secrets` reads environment variables through
1259
- * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1260
- * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1261
- * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1262
- * (`./node-mail-host`) through Resend or a caller-supplied transport.
1320
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1321
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1322
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1323
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1324
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1325
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1326
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1327
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1328
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1329
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1330
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1331
+ * transport, for a process that composes it and polls it, as the server
1332
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1333
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1334
+ * a queued send is not delivered.
1263
1335
  *
1264
1336
  * `lunora deploy --target node` bundles an app into a container build context
1265
1337
  * whose generated entry composes this package (crons, `ctx.secrets`,
1266
1338
  * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1267
1339
  *
1268
1340
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1269
- * for `provision` — which reports, once, which declared features this target
1270
- * cannot serve, and writes nothing: there is no hosted control plane to deploy
1271
- * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1272
- * server, which is why both statements above hold at once. See
1273
- * `plans/234-node-host-findings.md`.
1341
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1342
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1343
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
1274
1344
  */
1275
1345
  type DrainTimer,
1276
1346
  /**
@@ -1301,29 +1371,29 @@ type DrainTimer,
1301
1371
  * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1302
1372
  * is the one combination that fails at runtime with no diagnostic before it.
1303
1373
  *
1304
- * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1305
- * nothing here owns a timer, so queue delivery is driven by an explicit
1306
- * `poll()`. What exists is the listener a dev server would sit on:
1307
- * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1308
- * streaming the response body, and `createNodeShardNamespace` presents the
1309
- * registry as the `shardDO` namespace that worker routes to. Also absent are
1310
- * the Cloudflare product bindings with no local
1311
- * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1312
- * Engine, Pipelines. `ctx.secrets` reads environment variables through
1313
- * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1314
- * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1315
- * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1316
- * (`./node-mail-host`) through Resend or a caller-supplied transport.
1374
+ * **Serving an app.** `createNodeAppHost` composes a worker entry module over
1375
+ * one shard registry per Durable Object binding, and `createNodeHttpServer`
1376
+ * serves its `fetch` over `node:http`, streaming the response body. `lunora dev
1377
+ * --target node` runs exactly that pair. Nothing here owns a timer, so queue
1378
+ * delivery is driven by an explicit `poll()`. Absent are the Cloudflare product
1379
+ * bindings with no local equivalent — Vectorize, Workers AI, Browser Rendering,
1380
+ * Containers, Analytics Engine, Pipelines. `ctx.secrets` reads environment
1381
+ * variables through `createNodeSecretBindings` (`./node-secrets`), and the
1382
+ * Hyperdrive binding is built from `DATABASE_URL` by `createNodeHyperdrive`
1383
+ * (`./node-hyperdrive`). Queued `@lunora/mail` sends are delivered by
1384
+ * `createNodeMailHost` (`./node-mail-host`) through Resend or a caller-supplied
1385
+ * transport, for a process that composes it and polls it, as the server
1386
+ * `lunora deploy --target node` writes does. `lunora dev --target node` composes
1387
+ * none: there mail is captured to the Studio inbox, and with capture turned off
1388
+ * a queued send is not delivered.
1317
1389
  *
1318
1390
  * `lunora deploy --target node` bundles an app into a container build context
1319
1391
  * whose generated entry composes this package (crons, `ctx.secrets`,
1320
1392
  * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1321
1393
  *
1322
1394
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1323
- * for `provision` — which reports, once, which declared features this target
1324
- * cannot serve, and writes nothing: there is no hosted control plane to deploy
1325
- * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1326
- * server, which is why both statements above hold at once. See
1327
- * `plans/234-node-host-findings.md`.
1395
+ * and codegen gates against `NODE_CAPABILITIES`. There is no hosted control
1396
+ * plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
1397
+ * the deploy stops at a build context. See `plans/234-node-host-findings.md`.
1328
1398
  */
1329
- type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, 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 NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
1399
+ 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 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 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{N as d,c}from"./packem_shared/node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as p,createNodeSqlExec as N}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as x}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as s}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as l}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as i}from"./packem_shared/createNodeMailHost-DrUo8de-.mjs";import{createNodePlatform as E}from"./packem_shared/createNodePlatform-BqtVmQqS.mjs";import{createNodeProfileHandler as _}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as n}from"./packem_shared/createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as R}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as P}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as v}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as M}from"./packem_shared/createNodeShardHost-VU8MPeba.mjs";import{createNodeShardNamespace as b}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as y}from"./packem_shared/createNodeShardRegistry-C1SRJQhd.mjs";import{bindShardSockets as C,createNodeShardState as L}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as W}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as F}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as K}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,d as NODE_SCHEDULER_DISPATCH_PATH,C as bindShardSockets,c as createNodeDispatchRoute,p as createNodeGlobalStore,x as createNodeHttpServer,s as createNodeHyperdrive,i as createNodeMailHost,E as createNodePlatform,_ as createNodeProfileHandler,n as createNodeQueueHost,R as createNodeR2Bucket,P as createNodeSchedulerHost,v as createNodeSecretBindings,M as createNodeShardHost,l as createNodeShardKvStore,b as createNodeShardNamespace,y as createNodeShardRegistry,L as createNodeShardState,W as createNodeSocketHost,N as createNodeSqlExec,F as createNodeWorkflowHost,K as createNodeWorkflowStore,t as drainTogether};
1
+ import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-Cv5p7igg.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-B3GAZkHT.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs";import{createNodeGlobalStore as s,createNodeSqlExec as H}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as h}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-DrUo8de-.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-De8dIBya.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as v}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as O}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as w}from"./packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardNamespace as C}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as L}from"./packem_shared/createNodeShardRegistry-D1r6M8Rg.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as z}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as V}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,N as NODE_SCHEDULER_DISPATCH_PATH,j as bindShardSockets,c as checkNodeAppHost,d as createNodeAppHost,f as createNodeDispatchRoute,x as createNodeDurableObjectFactory,s as createNodeGlobalStore,h as createNodeHttpServer,D as createNodeHyperdrive,E as createNodeMailHost,_ as createNodePlatform,R as createNodeProfileHandler,P as createNodeQueueHost,v as createNodeR2Bucket,I as createNodeSchedulerHost,O as createNodeSecretBindings,w as createNodeShardHost,u as createNodeShardKvStore,C as createNodeShardNamespace,L as createNodeShardRegistry,q as createNodeShardState,K as createNodeSocketHost,H as createNodeSqlExec,z as createNodeWorkflowHost,V as createNodeWorkflowStore,t as drainTogether};
@@ -1 +1 @@
1
- import{N as o,c as r,a as t}from"./node-dispatch-route-ByuCR26s.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,r as createNodeDispatchRoute,t as createShardInvoke};
1
+ import{N as o,c as r,a as t}from"./node-dispatch-route-B3GAZkHT.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,r as createNodeDispatchRoute,t as createShardInvoke};
@@ -0,0 +1 @@
1
+ const l=(t,o)=>({acceptWebSocket:(e,a)=>{t.sockets.accept(e,void 0,a)},blockConcurrencyWhile:e=>{const a=t.shard.runSerialized(e);return o?.(a),a},getWebSockets:e=>t.sockets.getSockets(e),id:{name:t.shardKey},storage:{delete:e=>t.kv.delete(e),deleteAlarm:async()=>{await t.shard.alarms.delete()},get:e=>t.kv.get(e),getAlarm:async()=>t.shard.alarms.get(),list:e=>t.kv.list(e),put:(e,a)=>t.kv.put(e,a),setAlarm:async e=>{await t.shard.alarms.set(e)},sql:{get databaseSize(){return t.shard.sql.databaseSize},exec:(e,...a)=>t.shard.sql.exec(e,...a)},transaction:e=>t.shard.transaction(e)},waitUntil:e=>{t.shard.waitUntil?.(e)},openSocketPair:()=>t.sockets.newPair(),upgradeResponse:e=>t.sockets.upgradeResponse(e)}),i=(t,o)=>{const e=async(a,s)=>{await t.webSocketMessage(a,s)};o.onMessage((a,s)=>{e(a,s).catch(c=>{console.error("[lunora] webSocketMessage threw:",c)})}),o.onClose(async(a,s,c,r)=>{try{await t.webSocketClose(a,s,c,r)}catch(n){console.error("[lunora] webSocketClose threw:",n)}})};export{i as bindShardSockets,l as createNodeShardState};
@@ -0,0 +1 @@
1
+ import{mkdirSync as p,existsSync as m,realpathSync as h,lstatSync as g}from"node:fs";import{join as f,relative as y,isAbsolute as O}from"node:path";import{LunoraError as i}from"@lunora/errors";import{drainTimeoutMs as k,drainTogether as A,startDrainDeadline as R,settlesBefore as D}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeDurableObjectFactory as $}from"./createNodeDurableObjectFactory-hAwJt_pN.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-De8dIBya.mjs";import{createNodeShardNamespace as I}from"./createNodeShardNamespace-BgQjDv7V.mjs";const w=e=>{const r=new Set;let a=0;const t=()=>{const n=a===0?[]:[`${String(a)} ${e.label} failed`];return a=0,n},o=()=>r.size===0?[]:[`${String(r.size)} ${e.label}`];return{drain:async n=>{const c=R(n);try{for(;r.size>0;)if(!await D(Promise.all(r),c))return{failed:t(),pending:o(),timedOut:!0};return{failed:t(),pending:[],timedOut:!1}}finally{c.cancel()}},idle:()=>r.size===0,pending:o,track:n=>{const c=Promise.resolve(n).then(()=>{},d=>{e.reportFailures&&(a+=1,console.error("[@lunora/platform-node] work handed to waitUntil failed:",d))}).finally(()=>r.delete(c));r.add(c)}}},b=e=>{const r=[];for(const a of e)try{a.close({force:!0})}catch(t){r.push(t)}if(r.length>0)throw new AggregateError(r,`@lunora/platform-node: ${String(r.length)} platform(s) failed to close`)},S=e=>typeof e=="object"&&e!==null&&typeof e.fetch=="function",j=(e,r,a,t)=>{const o=$(r.worker[e.className],a);return v({crons:e.name===t?r.crons??{}:void 0,directory:r.dataDirectory===void 0?void 0:f(r.dataDirectory,e.name),onAlarm:async n=>{n!==void 0&&await(await o(n)).alarm?.()},onFetch:async(n,c)=>(await o(c)).fetch(n),path:r.dataDirectory===void 0?void 0:f(r.dataDirectory,`${e.name}.platform.sqlite3`)})},E=/^[A-Za-z_$][\w$]*$/u,L=(e,r)=>{const a=y(e,r);return a!==""&&!a.startsWith("..")&&!O(a)},T=(e,r)=>{if(!E.test(e))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${JSON.stringify(e)} is not a valid binding name (a JavaScript identifier such as SHARD), and its name becomes a directory under the data directory`);if(r===void 0||!m(r))return;const a=h(r);for(const t of[f(r,e),f(r,`${e}.platform.sqlite3`)]){let o;try{o=g(t)}catch{continue}if(o.isSymbolicLink()&&!m(t))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} is a link to nothing, which SQLite would follow`);if(!L(a,h(t)))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} links out of it`)}},_=e=>{const r=new Map;for(const{name:a}of e){const t=r.get(a.toLowerCase());if(t!==void 0)throw new i("VALIDATION_ERROR",t===a?`@lunora/platform-node: Durable Object binding ${a} is declared twice, and both would share one shard directory and platform database`:`@lunora/platform-node: Durable Object bindings ${t} and ${a} differ only in case, so on a case-insensitive volume they would share one shard directory and platform database — rename one`);r.set(a.toLowerCase(),a)}},P=e=>{if(typeof e!="function")return!1;try{return Reflect.construct(String,[],e),!0}catch{return!1}},x=e=>{if(!S(e.worker.default))throw new i("VALIDATION_ERROR","@lunora/platform-node: the worker module has no default export with a `fetch` handler");_(e.durableObjects);for(const t of e.durableObjects){T(t.name,e.dataDirectory);const o=Object.hasOwn(e.worker,t.className)?e.worker[t.className]:void 0;if(o===void 0)throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names class ${t.className}, which the worker module does not export`);if(!P(o))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names ${t.className}, which the worker module exports as something \`new\` cannot construct`)}const r=e.shardBinding??"SHARD";if(N(e.crons??{}).length>0&&!e.durableObjects.some(t=>t.name===r))throw new i("VALIDATION_ERROR",`@lunora/platform-node: the app declares crons, but no Durable Object binding is named ${r} to run them on`)},M=e=>{x(e);const r=e.worker.default,a={...e.env},t=[],o=w({label:"worker waitUntil task(s)",reportFailures:!0}),n=w({label:"worker request(s)",reportFailures:!1}),c=e.shardBinding??"SHARD";e.dataDirectory!==void 0&&p(e.dataDirectory,{recursive:!0});try{for(const s of e.durableObjects){const l=j(s,e,a,c);t.push(l),Object.defineProperty(a,s.name,{configurable:!0,enumerable:!0,value:I(l.directory),writable:!0})}}catch(s){try{b(t.splice(0))}catch(l){console.error("[@lunora/platform-node] closing the platforms of a host that failed to compose failed:",l)}throw s}const d={passThroughOnException:()=>{},waitUntil:o.track};let u;return{close:async s=>(k(s),u??=(async()=>{try{return await A([n,o,...t],s)}finally{b(t.splice(0))}})(),u),fetch:async s=>{const l=Promise.resolve(r.fetch(s,a,d));return n.track(l),l},rearmPersistedAlarms:()=>t.flatMap(s=>s.rearmPersistedAlarms())}};export{x as checkNodeAppHost,M as createNodeAppHost};
@@ -0,0 +1 @@
1
+ import{bindShardSockets as k,createNodeShardState as l}from"./bindShardSockets-DjLmRlIA.mjs";const y=(w,S)=>{const o=new WeakMap,i=new WeakSet,b=e=>{const t=[];let c=!0;const n=l(e,u=>{c&&t.push(u)}),s=new w(n,S);c=!1;const a=Promise.all(t).then(()=>{});return a.catch(()=>{}),{instance:s,ready:a}},r=async e=>{let t=o.get(e);t===void 0&&(t=b(e),o.set(e,t),!i.has(e)&&(t.instance.webSocketClose!==void 0||t.instance.webSocketMessage!==void 0)&&(i.add(e),k({webSocketClose:async(c,n,s,a)=>{await(await r(e)).webSocketClose?.(c,n,s,a)},webSocketMessage:async(c,n)=>{await(await r(e)).webSocketMessage?.(c,n)}},e.inbound)));try{await t.ready}catch(c){throw o.get(e)===t&&o.delete(e),c}return t.instance};return r};export{y as createNodeDurableObjectFactory};
@@ -1 +1 @@
1
- import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-ByuCR26s.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-DrUo8de-.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-C1SRJQhd.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as pe}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as we}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ge="__root__",ye=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>{if(o.functionPath===void 0)throw new d("VALIDATION_ERROR",o.workflow===void 0?`@lunora/platform-node: cron job "${o.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${o.name}" starts workflow "${o.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:o.args??{},expression:t,functionPath:o.functionPath,name:o.name}})),ve=(e,t)=>{const r=ye(e);if(r.length>0&&!t)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},w=(e,{databaseFile:t})=>{const r=N(t?e.trim():e);try{return F(r)}catch{try{return m(F(p(r)),M(r))}catch{return r}}},V=40,Re=e=>{let t=N(e.trim());const r=[t];for(let o=0;o<=V;o+=1){let i;try{i=X(t).isSymbolicLink()}catch(a){if(a.code==="ENOENT")return r;throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" could not be resolved — pass a path it can check`,{cause:a})}if(!i)return r;try{t=N(p(t),Y(t)),r.push(t)}catch(a){throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a symlink whose target could not be read`,{cause:a})}}throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a chain of more than ${String(V)} symlinks (a loop?) — pass the file itself`)},H=(e,t)=>{try{const r=$(e.trim(),{bigint:!0}),o=$(t.trim(),{bigint:!0});return r.dev===o.dev&&r.ino===o.ino}catch{return w(e,{databaseFile:!0}).toLowerCase()===w(t,{databaseFile:!0}).toLowerCase()}},Se=e=>{const t=e.trim();if(t===""||t===":memory:")throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is not durable — the mail queue and its sent ledger must survive a restart, so give mail a database file`);if(t.toLowerCase().startsWith("file:"))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is a file: URI — pass a plain filesystem path instead (better-sqlite3 does not read URIs, and would open a file by that literal name)`)},Ae=e=>({drain:async t=>{const r=P(t);try{return await D(e.drain(),r)?{failed:[],pending:[],timedOut:!1}:(console.error("[@lunora/platform-node] platform drain deadline passed with a mail poll still running"),{failed:[],pending:["a mail poll"],timedOut:!0})}finally{r.cancel()}},idle:()=>e.idle(),pending:()=>e.idle()?[]:["a mail poll"]}),be=(e,t)=>{const r=Re(e),o=r.at(-1)??e,i=[["the shard database (`path`)",t.path],["the .global() store (`globalTablesPath`)",t.globalTablesPath]];for(const[l,s]of i)if(s!==void 0&&s!==":memory:"&&s!==""&&H(s,o))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is ${l} "${s}" — give mail a database file of its own`);const{directory:a}=t;if(a===void 0)return;const u=w(a,{databaseFile:!1});if(r.some(l=>{const s=m(w(p(l),{databaseFile:!1}),M(l));return s.endsWith(k)&&p(s)===u}))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a ${k} file inside the shard registry's directory "${a}", which would open it as a shard — move it out of that directory`);let f;try{f=j(a).filter(l=>l.endsWith(k))}catch{return}const h=f.find(l=>H(m(a,l),o));if(h!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is the same file as the shard registry's shard "${m(a,h)}" — give mail a database file of its own`)},_e=(e,t)=>{if(e===void 0)return;const{path:r,...o}=e;Se(r),be(r,t);const i=new Z(r);try{return{close:()=>{i.close()},mail:de(i,o)}}catch(a){throw i.close(),a}},ke=(e,t)=>async(r,o,i)=>{if(re(r,t,ge))throw new d("BAD_REQUEST",oe);const a=await e({args:o,functionPath:r,id:i.id,identity:void 0,scheduledFor:i.scheduledFor,shardKey:t,traceparent:void 0});if(!a.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(a.status)}`)},Ke=(e={})=>{const t=[],{database:r,dispose:o,drain:i,host:a,pendingAlarms:u,pendingBackground:g,suspendAlarms:f,takeFailures:h}=ue(e);t.push(o);try{const l=ie(r),s=fe(e);t.push(n=>{s.close(n)});const{directory:O}=s,I=ee(O,e.onFetch!==void 0),B=te({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:I,schedulerSecret:e.dispatch?.schedulerSecret}),C=e.onFetch===void 0?void 0:ke(I,e.shardKey??"__root__"),{declareCrons:U,dispose:q,pendingDispatches:y,scheduler:W,suspend:J}=he(r,{...e,onDispatch:e.onDispatch??C}),{socket:K}=me(r);t.push(q),e.crons!==void 0&&U(ve(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const Q=e.queues===void 0?void 0:le(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),v=_e(e.mail,e);v!==void 0&&t.push(v.close);const R=v?.mail,x=e.objectStorageDirectory===void 0?void 0:ce({directory:e.objectStorageDirectory}),S=e.globalTablesPath===void 0?void 0:ne({path:e.globalTablesPath});S!==void 0&&t.push(()=>{S.dispose()});const G=e.workflows===void 0?void 0:pe({store:we(r),workflows:e.workflows}),E=n=>{const c=[];for(const b of t.toReversed())try{b(n)}catch(_){c.push(_)}if(c.length>0)throw new AggregateError(c,`@lunora/platform-node: ${String(c.length)} resource(s) failed to close`)},T=()=>[...g()>0||u()>0?["waitUntil work on the platform host"]:[],...y().labels],A=[{drain:async n=>{const c=P(n);try{const[b,_]=await Promise.all([D(i(),c),D(Promise.allSettled(y().waits),c)]);if(b&&_)return{failed:h(),pending:[],timedOut:!1};const L=T();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",L.join(", ")),{failed:h(),pending:L,timedOut:!0}}finally{c.cancel()}},idle:()=>g()===0&&u()===0&&y().waits.length===0,pending:T},s,...R===void 0?[]:[Ae(R)]];return{capabilities:z,close:E,directory:O,dispatch:n=>B(n),idle:()=>A.every(n=>n.idle()),pending:()=>A.flatMap(n=>n.pending()),drain:async n=>(ae(n),J(),f(),s.suspendAlarms(),se(A,n)),globalTables:S,kv:l,mail:R,objectStorage:x,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:Q,scheduler:W,shard:a,sockets:K,workflows:G,[Symbol.dispose]:()=>{E()}}}catch(l){for(const s of t.toReversed())try{s()}catch{}throw l}};export{ke as createJobDelivery,Ke as createNodePlatform};
1
+ import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-B3GAZkHT.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-DrUo8de-.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-D1r6M8Rg.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as pe}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as we}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ge="__root__",ye=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>{if(o.functionPath===void 0)throw new d("VALIDATION_ERROR",o.workflow===void 0?`@lunora/platform-node: cron job "${o.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${o.name}" starts workflow "${o.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:o.args??{},expression:t,functionPath:o.functionPath,name:o.name}})),ve=(e,t)=>{const r=ye(e);if(r.length>0&&!t)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},w=(e,{databaseFile:t})=>{const r=N(t?e.trim():e);try{return F(r)}catch{try{return m(F(p(r)),M(r))}catch{return r}}},V=40,Re=e=>{let t=N(e.trim());const r=[t];for(let o=0;o<=V;o+=1){let i;try{i=X(t).isSymbolicLink()}catch(a){if(a.code==="ENOENT")return r;throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" could not be resolved — pass a path it can check`,{cause:a})}if(!i)return r;try{t=N(p(t),Y(t)),r.push(t)}catch(a){throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a symlink whose target could not be read`,{cause:a})}}throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a chain of more than ${String(V)} symlinks (a loop?) — pass the file itself`)},H=(e,t)=>{try{const r=$(e.trim(),{bigint:!0}),o=$(t.trim(),{bigint:!0});return r.dev===o.dev&&r.ino===o.ino}catch{return w(e,{databaseFile:!0}).toLowerCase()===w(t,{databaseFile:!0}).toLowerCase()}},Se=e=>{const t=e.trim();if(t===""||t===":memory:")throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is not durable — the mail queue and its sent ledger must survive a restart, so give mail a database file`);if(t.toLowerCase().startsWith("file:"))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is a file: URI — pass a plain filesystem path instead (better-sqlite3 does not read URIs, and would open a file by that literal name)`)},Ae=e=>({drain:async t=>{const r=P(t);try{return await D(e.drain(),r)?{failed:[],pending:[],timedOut:!1}:(console.error("[@lunora/platform-node] platform drain deadline passed with a mail poll still running"),{failed:[],pending:["a mail poll"],timedOut:!0})}finally{r.cancel()}},idle:()=>e.idle(),pending:()=>e.idle()?[]:["a mail poll"]}),be=(e,t)=>{const r=Re(e),o=r.at(-1)??e,i=[["the shard database (`path`)",t.path],["the .global() store (`globalTablesPath`)",t.globalTablesPath]];for(const[l,s]of i)if(s!==void 0&&s!==":memory:"&&s!==""&&H(s,o))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is ${l} "${s}" — give mail a database file of its own`);const{directory:a}=t;if(a===void 0)return;const u=w(a,{databaseFile:!1});if(r.some(l=>{const s=m(w(p(l),{databaseFile:!1}),M(l));return s.endsWith(k)&&p(s)===u}))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a ${k} file inside the shard registry's directory "${a}", which would open it as a shard — move it out of that directory`);let f;try{f=j(a).filter(l=>l.endsWith(k))}catch{return}const h=f.find(l=>H(m(a,l),o));if(h!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is the same file as the shard registry's shard "${m(a,h)}" — give mail a database file of its own`)},_e=(e,t)=>{if(e===void 0)return;const{path:r,...o}=e;Se(r),be(r,t);const i=new Z(r);try{return{close:()=>{i.close()},mail:de(i,o)}}catch(a){throw i.close(),a}},ke=(e,t)=>async(r,o,i)=>{if(re(r,t,ge))throw new d("BAD_REQUEST",oe);const a=await e({args:o,functionPath:r,id:i.id,identity:void 0,scheduledFor:i.scheduledFor,shardKey:t,traceparent:void 0});if(!a.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(a.status)}`)},Ke=(e={})=>{const t=[],{database:r,dispose:o,drain:i,host:a,pendingAlarms:u,pendingBackground:g,suspendAlarms:f,takeFailures:h}=ue(e);t.push(o);try{const l=ie(r),s=fe(e);t.push(n=>{s.close(n)});const{directory:O}=s,I=ee(O,e.onFetch!==void 0),B=te({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:I,schedulerSecret:e.dispatch?.schedulerSecret}),C=e.onFetch===void 0?void 0:ke(I,e.shardKey??"__root__"),{declareCrons:U,dispose:q,pendingDispatches:y,scheduler:W,suspend:J}=he(r,{...e,onDispatch:e.onDispatch??C}),{socket:K}=me(r);t.push(q),e.crons!==void 0&&U(ve(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const Q=e.queues===void 0?void 0:le(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),v=_e(e.mail,e);v!==void 0&&t.push(v.close);const R=v?.mail,x=e.objectStorageDirectory===void 0?void 0:ce({directory:e.objectStorageDirectory}),S=e.globalTablesPath===void 0?void 0:ne({path:e.globalTablesPath});S!==void 0&&t.push(()=>{S.dispose()});const G=e.workflows===void 0?void 0:pe({store:we(r),workflows:e.workflows}),E=n=>{const c=[];for(const b of t.toReversed())try{b(n)}catch(_){c.push(_)}if(c.length>0)throw new AggregateError(c,`@lunora/platform-node: ${String(c.length)} resource(s) failed to close`)},T=()=>[...g()>0||u()>0?["waitUntil work on the platform host"]:[],...y().labels],A=[{drain:async n=>{const c=P(n);try{const[b,_]=await Promise.all([D(i(),c),D(Promise.allSettled(y().waits),c)]);if(b&&_)return{failed:h(),pending:[],timedOut:!1};const L=T();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",L.join(", ")),{failed:h(),pending:L,timedOut:!0}}finally{c.cancel()}},idle:()=>g()===0&&u()===0&&y().waits.length===0,pending:T},s,...R===void 0?[]:[Ae(R)]];return{capabilities:z,close:E,directory:O,dispatch:n=>B(n),idle:()=>A.every(n=>n.idle()),pending:()=>A.flatMap(n=>n.pending()),drain:async n=>(ae(n),J(),f(),s.suspendAlarms(),se(A,n)),globalTables:S,kv:l,mail:R,objectStorage:x,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:Q,scheduler:W,shard:a,sockets:K,workflows:G,[Symbol.dispose]:()=>{E()}}}catch(l){for(const s of t.toReversed())try{s()}catch{}throw l}};export{ke as createJobDelivery,Ke as createNodePlatform,ye as walkDeclaredCrons};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as U}from"node:async_hooks";import{LunoraError as X}from"@lunora/errors";import j from"better-sqlite3";import{p as J}from"./prepared-statement-3XBQZXtC.mjs";const G=2147483647,K=6,F=100,Z=4,L=10,b=r=>r===void 0?null:r,ee=(r,a)=>({get databaseSize(){const f=r.pragma("page_count",{simple:!0}),u=r.pragma("page_size",{simple:!0});return f*u},exec:(f,...u)=>{a("run SQL");const c=J(r,f),y=u.map(i=>b(i)),o=c.reader&&c.readonly;let n;const h=()=>(n===void 0&&(a("run SQL"),c.reader?n=c.all(...y):(c.run(...y),n=[])),n);o||h();const d=function*(){a("run SQL"),c.raw(!0);try{yield*c.iterate(...y)}finally{c.raw(!1)}};return{get columnNames(){return c.reader?c.columns().map(i=>i.name):void 0},[Symbol.iterator]:()=>h()[Symbol.iterator](),one:()=>{const i=h();if(i.length!==1)throw new Error(`expected exactly one row, got ${String(i.length)}`);return i[0]},...o?{raw:d}:{},toArray:()=>[...h()]}}}),re=(r,a,f,u,c=()=>{},y=()=>{})=>{let o,n,h=!1,d=0,i;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const O=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0"),M=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET scheduled_for = excluded.scheduled_for"),w=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO NOTHING"),R=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0"),N=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0 AND scheduled_for = ?"),S=e=>{e===void 0?O.run():M.run(e)},z=e=>w.run(e).changes>0,C=e=>N.run(e).changes>0;let g=!1,m;const E=new Set;let T,t=0;const l=()=>{n!==void 0&&(clearTimeout(n),n=void 0),g=!1},v=e=>{n=setTimeout(()=>{n=void 0,g=!1,e()},L),g=!0},I=()=>{const e=R.get();e!==void 0&&(o=e.scheduled_for,A(e.scheduled_for))},W=(e,s,_=t)=>{if(!r.open||o!==void 0||_!==t){e();return}if(r.inTransaction){E.add({retry:()=>{D(e,s,_)},settle:e}),T??=setTimeout(k,L);return}if(d+=1,d>K){d=0,e();return}const p=Date.now()+F*2**(d-1);if(z(p)){o=p,A(p),e();return}d=0,I(),e()},D=(e,s,_=t,p=0)=>{const B=d;try{W(e,s,_)}catch(q){if(d=B,r.open&&p+1<Z){E.add({retry:()=>{D(e,s,_,p+1)},settle:e}),T??=setTimeout(k,F*2**p);return}const P=new Date(s).toISOString();console.error("[@lunora/platform-node] the retry of the alarm due %s on shard %s could not be written after %d attempts, so that alarm is lost",P,u??"(unnamed)",p+1,q),y(`shard ${u??"(unnamed)"}: the retry of the alarm due ${P} could not be written`),e()}},k=()=>{if(T=void 0,r.open&&r.inTransaction){T=setTimeout(k,L);return}const e=[...E];E.clear();for(const s of e)s.retry()},x=(e,s=0)=>{if(h)return;const _=t;if(r.open&&r.inTransaction){v(()=>{x(e,s)});return}if(o=void 0,!!r.open){try{if(!C(e)){I();return}}catch{o=e,s<K&&(n=setTimeout(()=>{n=void 0,x(e,s+1)},F*2**s));return}c((async()=>{await f?.(),d=0})().catch(async p=>{console.error("[@lunora/platform-node] alarm handler on shard %s threw; retrying with backoff",u??"(unnamed)",p),await new Promise(B=>{D(B,e,_)})}))}},A=e=>{if(l(),h)return;const s=Math.max(0,e-Date.now());if(s>G){n=setTimeout(()=>{A(e)},G);return}n=setTimeout(()=>{n=void 0,x(e)},s)},Y={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(a.assertOwnTurn("delete an alarm"),d=0,S(void 0),a.inside()){i={at:void 0};return}t+=1,o=void 0,l()},get:()=>(i===void 0?o:i.at)??null,set:e=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");a.assertOwnTurn("set an alarm");const s=typeof e=="number"?e:e.getTime();if(d=0,S(s),a.inside()){i={at:s};return}t+=1,o=s,A(s)}},$=()=>{if(i===void 0)return;const{at:e}=i;if(i=void 0,t+=1,e===void 0){o=void 0,l();return}o=e,A(e)},H=()=>{if(m=void 0,!r.open)return;if(r.inTransaction){m=setTimeout(H,L);return}const e=R.get();e!==void 0&&(n===void 0||g||o!==e.scheduled_for)&&(o=e.scheduled_for,A(e.scheduled_for))},Q=()=>{i=void 0,m!==void 0&&clearTimeout(m),H()},V=()=>{l(),m!==void 0&&(clearTimeout(m),m=void 0),T!==void 0&&(clearTimeout(T),T=void 0);for(const e of E)console.error("[@lunora/platform-node] alarm retry on shard %s given up: the database closed while it waited for another transaction to end",u??"(unnamed)"),e.settle();E.clear()};return I(),{alarms:Y,commit:$,dispose:V,rollback:Q,suspend:()=>{h=!0,l(),m!==void 0&&(clearTimeout(m),m=void 0)}}},te=(r,a)=>{r.pragma("journal_mode = WAL");const f=new U;let u=!1;const c=t=>{if(u&&f.getStore()!==!0)throw new X("SHARD_UNAVAILABLE",`shard busy: cannot ${t} while another task holds this shard's transaction`)},y=ee(r,c),o=new Set,n=[],{alarms:h,commit:d,dispose:i,suspend:O,rollback:M}=re(r,{assertOwnTurn:c,inside:()=>f.getStore()===!0},a.onAlarm,a.shardKey,t=>{o.add(t),t.then(()=>o.delete(t)).catch(l=>{o.delete(t),console.error("[@lunora/platform-node] an alarm delivery on shard %s failed outside its retry handling",a.shardKey??"(unnamed)",l),n.push(`shard ${a.shardKey??"(unnamed)"}: an alarm delivery failed outside its retry handling`)})},t=>{n.push(t)}),w=new Set,R=new U;let N=Promise.resolve();const S=async t=>{if(R.getStore()===!0)return await t();const l=N;let v=()=>{};N=new Promise(I=>{v=I}),await l;try{return await R.run(!0,t)}finally{v()}},z=t=>S(t),C=async t=>{r.exec("BEGIN"),u=!0;try{const l=await f.run(!0,t);return r.exec("COMMIT"),u=!1,d(),l}catch(l){u=!1;try{r.exec("ROLLBACK")}catch{}throw M(),l}},g=t=>S(async()=>C(t)),m={alarms:h,runSerialized:z,shardKey:a.shardKey,sql:y,transaction:g,waitUntil:t=>{const l=t.catch(v=>{console.error("[@lunora/platform-node] work handed to waitUntil on shard %s failed",a.shardKey??"(unnamed)",v)}).finally(()=>{w.delete(l)});w.add(l)}};return{alarmsSettled:()=>o.size===0?void 0:Promise.allSettled(o),database:r,dispose:()=>{i(),r.open&&r.close()},drain:async()=>{for(;w.size>0||o.size>0;)await Promise.allSettled([...w,...o])},host:m,pendingAlarms:()=>o.size,pendingBackground:()=>w.size,suspendAlarms:O,takeFailures:()=>n.splice(0)}},le=(r={})=>{const a=new j(r.path??":memory:");try{return te(a,r)}catch(f){throw a.close(),f}};export{le as createNodeShardHost};
@@ -0,0 +1 @@
1
+ import{mkdirSync as P,readdirSync as W}from"node:fs";import{join as b}from"node:path";import{LunoraError as U}from"@lunora/errors";import x from"better-sqlite3";import{startDrainDeadline as z,settlesBefore as K}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as T}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as V}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeSocketHost as X}from"./createNodeSocketHost-ByOmEGFe.mjs";const v=".sqlite3",F=n=>n.replaceAll(/[^\da-z._-]/gu,s=>[...Buffer.from(s,"utf8")].map(d=>`%${d.toString(16).padStart(2,"0").toUpperCase()}`).join("")),G=n=>decodeURIComponent(n),J=(n,s)=>{const d=s.slice(0,-v.length),l=b(n,s);let u;try{u=G(d)}catch{throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const f=`${F(u)}${v}`;if(f!==s)throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" was written under an older shard-key encoding. It decodes to shard key "${u}", which this build stores as "${f}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${l}" "${b(n,f)}"`);return u},Q=(n,s)=>{let d;try{return d=new x(n,{fileMustExist:!0,readonly:!0}),d.prepare("SELECT 1 FROM _lunora_alarm LIMIT 1").get()!==void 0}catch(l){return console.error("[@lunora/platform-node] could not check shard %s for a persisted alarm, so it is opened to re-arm any",s,l),!0}finally{d?.close()}},k=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Y=(n,s)=>{const d=[k(s.requests,"request in flight","requests in flight"),k(s.alarms,"alarm running","alarms running"),k(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ie=(n={})=>{const s=new Map;let d="open",l=!1;const u=()=>{l=!0;for(const e of s.values())e.suspendAlarms()},f=()=>{if(d!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${d}, so it opens no shard and takes no request`)},m=new Map,B=async(e,t)=>{const r=Promise.resolve().then(t),o=r.then(()=>{},()=>{});let a=m.get(e);return a===void 0&&(a=new Set,m.set(e,a)),a.add(o),o.finally(()=>{a.delete(o),a.size===0&&m.get(e)===a&&m.delete(e)}).catch(()=>{}),r},S=new Set,h=new Set,E=[];if(n.directory!==void 0){P(n.directory,{recursive:!0});for(const e of W(n.directory))e.endsWith(v)&&S.add(J(n.directory,e))}const $=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:b(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:c,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=V({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e});let A;try{A=X(i),o={inbound:A,kv:T(i),shard:w,shardKey:e,sockets:A.socket}}catch(O){throw c(),O}return s.set(e,{alarmsSettled:a,dispose:c,drain:A.drain,drainHost:g,pendingAlarms:_,pendingBackground:j,shard:o,suspendAlarms:L,takeFailures:C}),S.add(e),l&&L(),o},H=e=>({fetch:async t=>{const r=$(e),{onFetch:o}=n;return o===void 0?new Response(e):B(e,()=>o(t,r))}}),I=()=>[...E.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],p=()=>{const e=new Map,t=a=>{let i=e.get(a);return i===void 0&&(i={alarms:0,background:0,closing:!1,requests:0},e.set(a,i)),i},r=[];for(const[a,i]of m)r.push(...i),t(a).requests+=i.size;for(const[a,i]of s){const c=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();c!==void 0&&(t(a).closing=!0,r.push(c)),g>0&&(t(a).background=g),w>0&&(t(a).alarms=w),(g>0||w>0)&&r.push(i.drainHost())}return{labels:[...e].map(([a,i])=>Y(a,i)),waits:r}},N=(e,t)=>{const r=t.drain(),o=t.alarmsSettled();return[...m.get(e)??[],...o===void 0?[]:[o],...r===void 0?[]:[r]]},R=()=>{d!=="open"&&s.size===0&&(d="closed")},q=(e,t)=>{try{t.dispose()}catch(r){return r??new Error(`shard ${e} failed to close`)}s.delete(e)},y=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{h.has(e)&&s.get(e)===t&&y(e,t)}).catch(()=>{});return}h.delete(e);const o=q(e,t);o!==void 0&&(console.error("[@lunora/platform-node] shard %s failed to close after the work using it settled",e,o),E.push(`shard ${e} failed to close after the work using it settled`)),R()},D=(e,t,r)=>{const o=q(e,t);return o===void 0?h.delete(e):r&&!h.has(e)&&(h.add(e),y(e,t)),o},M=(e,t)=>{e.length>0&&console.error("[@lunora/platform-node] closed %d shard(s) with a request, alarm handler or socket close handler still running: %s",e.length,e.join(", "));for(const{error:r,key:o}of t)console.error("[@lunora/platform-node] shard %s failed to close",o,r);if(t.length>0)throw new AggregateError(t.map(({error:r})=>r),`@lunora/platform-node: ${String(t.length)} shard(s) failed to close: ${t.map(({key:r})=>r).join(", ")}`)};return{close:e=>{d==="open"&&(d="closing");const t=[],r=[];u();for(const[o,a]of s){const i=N(o,a);if(i.length===0||e?.force===!0){i.length>0&&t.push(o);const c=D(o,a,i.length>0);c!==void 0&&r.push({error:c,key:o})}else h.has(o)||(h.add(o),y(o,a))}R(),M(t,r)},drain:async e=>{const t=z(e);try{for(let r=p();r.waits.length>0;r=p())if(!await K(Promise.allSettled(r.waits),t)){const o=p().labels;return console.error("[@lunora/platform-node] shard drain deadline passed with work still running: %s",o.join(", ")),{failed:I(),pending:o,timedOut:!0}}return{failed:I(),pending:[],timedOut:!1}}finally{t.cancel()}},directory:{get:e=>H(String(e)),getByName:e=>H(e),idForName:e=>e},idle:()=>p().waits.length===0,pending:()=>p().labels,rearmPersistedAlarms:()=>{f();const{directory:e}=n;if(e===void 0)return[];const t=[];for(const r of S)if(!s.has(r)&&Q(b(e,`${F(r)}${v}`),r))try{$(r),t.push(r)}catch(o){console.error("[@lunora/platform-node] could not open shard %s to re-arm its persisted alarm",r,o)}return t},listShardKeys:()=>[...S],shardFor:$,suspendAlarms:u}};export{v as SHARD_FILE_SUFFIX,ie as createNodeShardRegistry};