@lunora/codegen 1.0.0-alpha.381 → 1.0.0-alpha.383

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 (50) hide show
  1. package/dist/index.d.mts +207 -95
  2. package/dist/index.d.ts +207 -95
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{GENERATED_HEADER-DPEvCN8Z.mjs → GENERATED_HEADER-Bzf6ZJ9r.mjs} +1 -1
  5. package/dist/packem_shared/{MUTATORS_FILENAME-Ipxibja6.mjs → MUTATORS_FILENAME-BGvYo46g.mjs} +1 -1
  6. package/dist/packem_shared/{NOTIFY_FILENAME-B-t7jQSm.mjs → NOTIFY_FILENAME-BJJObZHG.mjs} +1 -1
  7. package/dist/packem_shared/{OPENRPC_VERSION-DA0ZNkhl.mjs → OPENRPC_VERSION-CSjT8wJW.mjs} +1 -1
  8. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-D3x_KiFb.mjs → SCHEMA_SNAPSHOT_FILENAME-kN0pgKNu.mjs} +9 -9
  9. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs +2 -0
  10. package/dist/packem_shared/{SHAPES_FILENAME-mgEi072Z.mjs → SHAPES_FILENAME-KyidzoqS.mjs} +1 -1
  11. package/dist/packem_shared/SchemaSnapshotParseError-ycDz8gOB.mjs +17 -0
  12. package/dist/packem_shared/{buildOpenApiDocument-Ct2wK_Tj.mjs → buildOpenApiDocument-afHH7rN5.mjs} +1 -1
  13. package/dist/packem_shared/{context-property-calls-DKMO9ShK.mjs → context-property-calls-B75cjwpy.mjs} +1 -1
  14. package/dist/packem_shared/{context-root-BPfMNAJM.mjs → context-root-D4Njep-A.mjs} +1 -1
  15. package/dist/packem_shared/{database-calls-hLzaOquW.mjs → database-calls-aAjZJdma.mjs} +1 -1
  16. package/dist/packem_shared/{discoverFunctions-a0IT8OSb.mjs → discoverFunctions-CoQM_L6f.mjs} +1 -1
  17. package/dist/packem_shared/{discoverHttpRoutes-DHDfKLoa.mjs → discoverHttpRoutes-BQM2CPSF.mjs} +1 -1
  18. package/dist/packem_shared/discoverHyperdriveCalls-PUg-BESh.mjs +1 -0
  19. package/dist/packem_shared/{discoverInserts-IAa3lRR4.mjs → discoverInserts-DldQpEfF.mjs} +1 -1
  20. package/dist/packem_shared/discoverMaskProcedures-_Ey4eJLn.mjs +1 -0
  21. package/dist/packem_shared/discoverMigrations-E9k4Ykku.mjs +1 -0
  22. package/dist/packem_shared/{discoverQueries-DZOGiEPs.mjs → discoverQueries-Bq2hqYHP.mjs} +1 -1
  23. package/dist/packem_shared/discoverR2sqlCalls-CeNnalpk.mjs +1 -0
  24. package/dist/packem_shared/{discoverRlsProcedures-B0DYk-gW.mjs → discoverRlsProcedures-MboagP9z.mjs} +1 -1
  25. package/dist/packem_shared/{discoverSchema-DmkjooXZ.mjs → discoverSchema-Cycd1-H0.mjs} +1 -1
  26. package/dist/packem_shared/{emitAgents-CrSmVS4d.mjs → emitAgents-BeM6PZv4.mjs} +1 -1
  27. package/dist/packem_shared/{emitApi-D6uqyYd_.mjs → emitApi-GFmStqmq.mjs} +1 -1
  28. package/dist/packem_shared/{emitApp-DT4eMX6J.mjs → emitApp-D-6FIpYb.mjs} +65 -47
  29. package/dist/packem_shared/{emitCrons-C3RiGYk7.mjs → emitCrons-Drdn8Mjn.mjs} +1 -1
  30. package/dist/packem_shared/{emitDataModel-BMMht_iZ.mjs → emitDataModel-LTnwnhV6.mjs} +1 -1
  31. package/dist/packem_shared/{emitDrizzleSchema-BmCxM6tO.mjs → emitDrizzleSchema-CM9jh_F0.mjs} +1 -1
  32. package/dist/packem_shared/{emitFunctions-NGByI1FZ.mjs → emitFunctions-CfSXBV_A.mjs} +1 -1
  33. package/dist/packem_shared/{emitServer-4NV3vaOg.mjs → emitServer-4l7MPmK0.mjs} +1 -1
  34. package/dist/packem_shared/emitShard-B4fVJcJA.mjs +1 -0
  35. package/dist/packem_shared/{index-BjDVAPNW.mjs → index-11LAY5JO.mjs} +1 -1
  36. package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
  37. package/dist/packem_shared/{qualifiers-CPQCkXC4.mjs → qualifiers-D1Q_3wo2.mjs} +1 -1
  38. package/dist/packem_shared/{server-BY1v1bTx.mjs → server-D69SOfX8.mjs} +1 -1
  39. package/dist/packem_shared/{shard-DmDBaK79.mjs → shard-CB0Ospyw.mjs} +1 -1
  40. package/dist/packem_shared/{shard-runtime-BtEGoPTf.mjs → shard-runtime-lkQU8trx.mjs} +72 -68
  41. package/dist/packem_shared/{shared-BErjtci3.mjs → shared-A1XHcT4t.mjs} +1 -1
  42. package/package.json +4 -4
  43. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs +0 -2
  44. package/dist/packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs +0 -18
  45. package/dist/packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs +0 -1
  46. package/dist/packem_shared/discoverMaskProcedures-Bj6fPF4u.mjs +0 -1
  47. package/dist/packem_shared/discoverMigrations-Bv8kNIgy.mjs +0 -1
  48. package/dist/packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs +0 -1
  49. package/dist/packem_shared/emitShard-VIGqeQvE.mjs +0 -1
  50. package/dist/packem_shared/parse-validator-CP5CL6Q7.mjs +0 -1
@@ -1,11 +1,11 @@
1
- import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as L}from"./schema-BgM8A3XV.mjs";import{a as j,I as $,G as w}from"./shared-BErjtci3.mjs";const G={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},k=e=>[...N.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[G]:[]],S=e=>k(e).length>0,E=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(r=>L(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,P=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as N,I as L,G as y}from"./shared-A1XHcT4t.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...q.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(r=>I(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
2
2
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
3
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
4
  const namespace = this.schedulerDeclaration?.namespace(env);
5
5
 
6
6
  return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
7
7
  }
8
- `:"",M=e=>e?`
8
+ `:"",G=e=>e?`
9
9
  /**
10
10
  * One bucket's \`Storage\`, signing under the name it is registered as.
11
11
  *
@@ -114,7 +114,7 @@ import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";impor
114
114
  storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
115
115
  };
116
116
  }
117
- `:"",B=e=>e?`
117
+ `:"",P=e=>e?`
118
118
  /**
119
119
  * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
120
120
  *
@@ -250,11 +250,12 @@ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector =
250
250
  * \`startLine\` plus positional counting would mis-attribute every row after
251
251
  * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
252
252
  * falls back to the position-derived count otherwise. A dry run is passed through and writes nothing;
253
- * \`onConflict: "replace"\` overwrites a row whose \`_id\` already exists instead of reporting a conflict.
253
+ * \`onConflict: "replace"\` overwrites a row whose \`_id\` already exists instead of reporting a conflict, and a row's
254
+ * \`op: "delete"\` removes the stored row it names.
254
255
  */
255
256
  const buildGlobalImporter =
256
257
  (database: D1DatabaseLike, cdc: boolean) =>
257
- (request: { dryRun?: boolean; onConflict?: "replace" | "skip"; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
258
+ (request: { dryRun?: boolean; onConflict?: "replace" | "skip"; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; op?: "delete"; table: string }>; startLine?: number }) => {
258
259
  const exec = buildExec(database);
259
260
  // Same reason the PITR applier carries it: a bulk import that skips the
260
261
  // changelog restores rows no downstream consumer is ever told about.
@@ -264,7 +265,7 @@ const buildGlobalImporter =
264
265
  dryRun: request.dryRun === true,
265
266
  exec,
266
267
  onConflict: request.onConflict ?? "skip",
267
- rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
268
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, ...(row.op === undefined ? {} : { op: row.op }), table: row.table })),
268
269
  ...(request.startLine === undefined ? {} : { startLine: request.startLine }),
269
270
  });
270
271
  };
@@ -339,12 +340,12 @@ const buildGlobalCdcApplier =
339
340
 
340
341
  return request.changes.length;
341
342
  };
342
- `:"",W=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],_=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...S(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...c(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],H=e=>k(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
343
+ `:"",M=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],B=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...c(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],_=e=>f(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
343
344
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
344
345
  this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
345
346
 
346
347
  return this;
347
- }`),U=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
348
+ }`),W=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
348
349
  public admin(selector: Selector<Env, string>): this {
349
350
  this.adminToken = selector;
350
351
 
@@ -408,7 +409,7 @@ const buildGlobalCdcApplier =
408
409
  this.storageDeclaration = declaration;
409
410
 
410
411
  return this;
411
- }`]:[],...H(e)],F=e=>{const r=a=>e.hasScheduler?`
412
+ }`]:[],..._(e)],H=e=>{const r=a=>e.hasScheduler?`
412
413
  ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
413
414
  ? {
414
415
  d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null | undefined }) => {
@@ -516,13 +517,13 @@ const buildGlobalCdcApplier =
516
517
  ? {
517
518
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
518
519
  }
519
- : {}),`]:[],...c(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...S(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
520
+ : {}),`]:[],...c(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
520
521
  ${t.join(`
521
522
  `)}
522
- `:""},Q=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],J=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],K=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],V=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],Y=e=>e?['import notifyConfig from "../notify.js";']:[],X=e=>E(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Z=e=>E(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],ee=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:s}=e,i=s?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],l=[...t||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},te=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:s,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...z(r,t),...V(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...J(s),...K(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...X(e),...ee(e),"",...Q(e.identity),...Z(e),...a||n?['import schema from "../schema.js";']:[],...Y(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},re=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
523
+ `:""},U=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],F=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],Q=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],z=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],K=e=>e?['import notifyConfig from "../notify.js";']:[],V=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Y=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],X=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:s}=e,i=s?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],l=[...t||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},Z=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:s,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...F(r,t),...J(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...Q(s),...z(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...V(e),...X(e),"",...U(e.identity),...Y(e),...a||n?['import schema from "../schema.js";']:[],...K(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},ee=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
523
524
  // The schema's jurisdiction pins the auth object like every other DO.
524
- jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",ae=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,ne=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
525
- ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${ae(r.shardMode)}],`).join(`
525
+ jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",te=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,re=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
526
+ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`).join(`
526
527
  `)}
527
528
  ]);
528
529
 
@@ -531,10 +532,10 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${ae(r.shardMode)}],`
531
532
 
532
533
  if (shardRegistry) {
533
534
  options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
534
- }`]:[]],D=e=>(e.liveStreamDeclarations??[]).map(r=>{if(j(r.exportName,"live stream export name"),!$.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),se=e=>p(e)?[" httpRouter: liveStreamRouter([",...D(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],oe=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],ie=e=>p(e)?`liveStreamRouter([
535
- ${D(e).join(`
535
+ }`]:[]],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(N(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),ae=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ne=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],se=e=>p(e)?`liveStreamRouter([
536
+ ${S(e).join(`
536
537
  `)}
537
- ], host)`:"host",le=e=>[...ne(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
538
+ ], host)`:"host",oe=e=>[...re(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
538
539
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
539
540
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
540
541
  const source = workflowEnv as Record<string, unknown>;
@@ -553,10 +554,12 @@ ${D(e).join(`
553
554
  // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
554
555
  // land here, and without it they are reported, not written.
555
556
  options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
556
- // The importer above skips the write for a dry run, and
557
- // overwrites an existing \`_id\` under \`onConflict: "replace"\`.
557
+ // The importer above skips the write for a dry run, overwrites an
558
+ // existing \`_id\` under \`onConflict: "replace"\`, and removes the row
559
+ // an \`op: "delete"\` row names.
558
560
  options.importGlobalsSupportsDryRun = true;
559
561
  options.importGlobalsSupportsReplace = true;
562
+ options.importGlobalsSupportsDelete = true;
560
563
  // The read/replay half of the same admin plane. Each one is the
561
564
  // only reason its endpoint can see the global storage plane at
562
565
  // all, and every one of them fails SILENTLY when unset — export
@@ -595,6 +598,7 @@ ${D(e).join(`
595
598
  });
596
599
  options.importGlobalsSupportsDryRun = true;
597
600
  options.importGlobalsSupportsReplace = true;
601
+ options.importGlobalsSupportsDelete = true;
598
602
  options.exportGlobals = (request) => exportHyperdriveGlobalRows({ engine, exec: exec(), schema: hyperdriveSchema, tables: request.tables });
599
603
  options.syncGlobals = async (request) => {
600
604
  const page = await readHyperdriveGlobalCdc(engine, exec(), request);
@@ -658,7 +662,7 @@ ${D(e).join(`
658
662
  // Memoised on the declaration: each worker built for a new \`env\` runs
659
663
  // these options again, and \`options(env)\` rebuilds every plugin.
660
664
  discoveryPaths,
661
- internalSecret,${re(e)}
665
+ internalSecret,${ee(e)}
662
666
  namespace,
663
667
  ...(objectName === undefined ? {} : { objectName }),
664
668
  });
@@ -800,10 +804,10 @@ ${D(e).join(`
800
804
  }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
801
805
  ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
802
806
  `)}
803
- };`]:[]],ce=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...e.hasQueue?[` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],...se(e),...oe(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],de=e=>e?`
807
+ };`]:[]],ie=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY"}, {`," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],le=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...ie(e),...ae(e),...ne(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],ce=e=>e?`
804
808
  /** The identity memo per \`env\` object, owned by one assembled worker. */
805
809
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
806
- `:"",R=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,he=e=>{if(!R(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n,s])=>[a,n,s]);return`
810
+ `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,de=e=>{if(!E(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n,s])=>[a,n,s]);return`
807
811
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
808
812
  interface DeferredModules {
809
813
  ${t.map(([a,n])=>` ${a}: ${n};`).join(`
@@ -820,13 +824,32 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
820
824
  `)}
821
825
  };
822
826
  })());
823
- `},ue=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
827
+ `},he=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
824
828
  await ensureAuth(env);`:"",n=e?`
825
829
  await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"target",eventWorkerLine:`
826
830
  const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"worker",eventWorkerLine:`
827
- worker ??= ${t};`}},pe=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
828
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ye=e=>e?`${w}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
829
- `:"",be=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),fe=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=W(t),s=le(t),i=a?` let auth: LunoraAuth | null = null;
831
+ worker ??= ${t};`}},ue=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
832
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ye=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
833
+ `:"",pe=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(n=>`${a}{ agent: lunoraAgentDefinitions.${n.exportName}, className: ${JSON.stringify(n.className)} },`).join(`
834
+ `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
835
+ ${t(" ")}
836
+ ]);
837
+
838
+ `:` let agentEmail: ReturnType<typeof dispatchAgentEmail> | undefined;
839
+
840
+ composed.email = async (message, rawEnv, context) => {
841
+ if (agentEmail === undefined) {
842
+ const [{ dispatchAgentEmail: dispatch }, lunoraAgentDefinitions] = await Promise.all([import("@lunora/agent/inbound"), import("../agents.js")]);
843
+
844
+ agentEmail ??= dispatch([
845
+ ${t(" ")}
846
+ ]);
847
+ }
848
+
849
+ return agentEmail(message, rawEnv, context);
850
+ };
851
+
852
+ `},be=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),fe=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=M(t),s=oe(t),i=a?` let auth: LunoraAuth | null = null;
830
853
  let authInit: Promise<void> | null = null;
831
854
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
832
855
  // \`assemble()\` has its own auth closure and must not share.
@@ -897,16 +920,11 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
897
920
  return false;
898
921
  },
899
922
  );
900
- `:"",{asyncIfDeferred:l,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=pe(t),{ensureAuthCall:A,ensureRawAuthCall:x,eventWorker:b,eventWorkerLine:m}=ue(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,C=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,O=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
901
- host ? withFrameworkWorker(${ie(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,T=t.hasFramework?"host?: FrameworkHostHandler":"",y=t.emailAgents??[],q=y.length>0?` composed.email = dispatchAgentEmail([
902
- ${y.map(f=>` { agent: lunoraAgentDefinitions.${f.exportName}, className: ${JSON.stringify(f.className)} },`).join(`
903
- `)}
904
- ]);
905
-
906
- `:"",I=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
923
+ `:"",{asyncIfDeferred:l,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=ue(t),{ensureAuthCall:D,ensureRawAuthCall:R,eventWorker:b,eventWorkerLine:m}=he(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,A=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,x=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
924
+ host ? withFrameworkWorker(${se(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,C=t.hasFramework?"host?: FrameworkHostHandler":"",O=pe(t),T=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
907
925
  public build(): ComposedApp {
908
926
  return this.assemble();
909
- }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${w}${te(t).join(`
927
+ }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${Z(t).join(`
910
928
  `)}
911
929
 
912
930
  /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
@@ -914,7 +932,7 @@ type Selector<Env, T> = (env: Env) => T | undefined;
914
932
 
915
933
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
916
934
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
917
- ${de(a)}${he(t)}${t.jurisdiction?`
935
+ ${ce(a)}${de(t)}${t.jurisdiction?`
918
936
  // Module scope, so every isolate loading this script (the worker and each Durable
919
937
  // Object class it exports) knows the schema's jurisdiction before a request runs.
920
938
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
@@ -939,32 +957,32 @@ interface ComposedApp extends LunoraWorker {
939
957
  * first request so per-isolate singletons are built once.
940
958
  */
941
959
  class AppBuilder<Env extends object> {
942
- ${_(t).join(`
960
+ ${B(t).join(`
943
961
  `)}
944
962
 
945
963
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
946
964
 
947
- ${U(t).join(`
965
+ ${W(t).join(`
948
966
 
949
967
  `)}
950
968
 
951
- ${I}
969
+ ${T}
952
970
 
953
971
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
954
- private assemble(${T}): ComposedApp {
955
- const ShardDO = createShardDO({${F(t)}});
972
+ private assemble(${C}): ComposedApp {
973
+ const ShardDO = createShardDO({${H(t)}});
956
974
 
957
975
  // Per-isolate singletons: the worker (and auth instance) are expensive to
958
976
  // build, so the first request constructs them and every later request on
959
977
  // the same isolate reuses them.
960
978
  let worker: LunoraWorker | null = null;
961
979
  ${i}${d}
962
- ${O}
980
+ ${x}
963
981
 
964
982
  const composed: ComposedApp = {
965
983
  ShardDO,
966
984
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
967
- const env = rawEnv as Env;${h}${A}
985
+ const env = rawEnv as Env;${h}${D}
968
986
  worker ??= buildWorker(env${o});
969
987
 
970
988
  return worker.fetch(request, rawEnv, context);
@@ -973,7 +991,7 @@ ${O}
973
991
 
974
992
  return ${b}.scheduled(controller, rawEnv, context);
975
993
  },
976
- serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${x}
994
+ serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${R}
977
995
  worker ??= buildWorker(rawEnv as Env${o});
978
996
 
979
997
  return worker.serverQuery(request, rawEnv, reference, args, options);
@@ -984,7 +1002,7 @@ ${O}
984
1002
  },`:""}
985
1003
  };
986
1004
 
987
- ${q} if (this.emailHandler) {
1005
+ ${O} if (this.emailHandler) {
988
1006
  const handler = this.emailHandler;
989
1007
 
990
1008
  composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
@@ -1003,11 +1021,11 @@ ${t.hasFramework?`
1003
1021
  `:""}
1004
1022
  return composed;
1005
1023
  }
1006
- ${P(t)}${M(t.hasStorage)}
1024
+ ${$(t)}${G(t.hasStorage)}
1007
1025
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1008
- private buildWorkerOptions(env: Env, ${C}): WorkerOptions {
1026
+ private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
1009
1027
  const options: WorkerOptions = {
1010
- ${ce(t).join(`
1028
+ ${le(t).join(`
1011
1029
  `)}
1012
1030
  };
1013
1031
 
@@ -1028,7 +1046,7 @@ ${s.join(`
1028
1046
  return options;
1029
1047
  }
1030
1048
  }
1031
- ${B(t.hasGlobal)}
1049
+ ${P(t.hasGlobal)}
1032
1050
  /**
1033
1051
  * Shape of the project's root \`lunora.config.*\`.
1034
1052
  *
@@ -1,4 +1,4 @@
1
- import{G as a,d as c}from"./shared-BErjtci3.mjs";import{i as y}from"./schema-BgM8A3XV.mjs";const f=s=>s?`${a}/**
1
+ import{G as a,d as c}from"./shared-A1XHcT4t.mjs";import{i as y}from"./schema-BgM8A3XV.mjs";const f=s=>s?`${a}/**
2
2
  * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
3
3
  * forward it — wrangler binds only what the entry exports:
4
4
  *
@@ -1,4 +1,4 @@
1
- import{r as k}from"./qualifiers-CPQCkXC4.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-BErjtci3.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
1
+ import{r as k}from"./qualifiers-D1Q_3wo2.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-A1XHcT4t.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
2
2
  `),n=t?`
3
3
  ${t}
4
4
  `:"",N=e.commitOrdered===!0?`
@@ -1,4 +1,4 @@
1
- import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-BMMht_iZ.mjs";import{r as m}from"./qualifiers-CPQCkXC4.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-BErjtci3.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
1
+ import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-LTnwnhV6.mjs";import{r as m}from"./qualifiers-D1Q_3wo2.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-A1XHcT4t.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
2
2
  `),n=e.indexes.length>0?`, (t) => ({
3
3
  ${e.indexes.map(o=>I(o)).join(`
4
4
  `)}
@@ -1,4 +1,4 @@
1
- import{LunoraError as A}from"@lunora/errors";import{L as de,s as j,G as D,d as U,I as T,b as M,r as he,c as me}from"./shared-BErjtci3.mjs";import{v as pe}from"./parse-validator-CP5CL6Q7.mjs";import{renderAgentFunctionRegistry as ge,renderSandboxFunctionRegistry as fe}from"./emitApi-D6uqyYd_.mjs";import{b as ye,a as $e,r as I,c as we}from"./qualifiers-CPQCkXC4.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const ke=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),J=r=>r.column!==void 0,Re=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
1
+ import{LunoraError as A}from"@lunora/errors";import{L as de,s as j,G as D,d as U,I as T,b as M,r as he,c as me}from"./shared-A1XHcT4t.mjs";import{v as pe}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as ge,renderSandboxFunctionRegistry as fe}from"./emitApi-GFmStqmq.mjs";import{b as ye,a as $e,r as I,c as we}from"./qualifiers-D1Q_3wo2.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const ke=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),J=r=>r.column!==void 0,Re=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
2
2
  `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
3
3
  `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
4
4
  `;case"null":return`if (${t} !== null) return DEFER;
@@ -1 +1 @@
1
- import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-BY1v1bTx.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
1
+ import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-D69SOfX8.mjs";import"./shared-A1XHcT4t.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
@@ -0,0 +1 @@
1
+ import"./SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CB0Ospyw.mjs";import"./shard-runtime-lkQU8trx.mjs";import"./shared-A1XHcT4t.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -1 +1 @@
1
- import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{b as m,d as p}from"./attribution-DUbGYT4N.mjs";import{t as d}from"./database-calls-hLzaOquW.mjs";import{w as g,c as h}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{b as m,d as p}from"./attribution-DUbGYT4N.mjs";import{t as d}from"./database-calls-aAjZJdma.mjs";import{w as g,c as h}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{Node as i,VariableDeclarationKind as E}from"ts-morph";import{diagnosticAt as h}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as A}from"./property-name-7cBlgK_O.mjs";let g;const q=e=>{g=e},k=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),N=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},T=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),L=new Set(["strip"]),l=new Set,f=new Set,v=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&i.isShorthandPropertyAssignment(r)){const n=r.getValueSymbol();r=(n?.getAliasedSymbol()??n)?.getValueDeclaration()}if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},w=e=>{const t=e.getParent();return!i.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===E.Const},u=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return u(e.getExpression());if(i.isObjectLiteralExpression(e))return e;if(i.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),n=r!==void 0&&i.isPropertyAssignment(r)?r.getInitializer():void 0;return n===void 0?void 0:u(n)}if(!i.isIdentifier(e)||l.has(e))return;const t=v(e);if(!(t===void 0||!w(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},D="v",R=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===D},d=e=>{if(i.isIdentifier(e)&&!l.has(e)){const t=v(e);if(t!==void 0&&R(t)){l.add(e);try{return d(t)}finally{l.delete(e)}}}return i.isCallExpression(e)?C(e):{kind:"any",sourceText:e.getText()}},S=e=>{const t=u(e);if(t===void 0||f.has(t))return{};f.add(t);try{return x(t)}finally{f.delete(t)}},b=(e,t=new Set)=>{const r=u(e);if(r===void 0||t.has(r))return!1;t.add(r);try{return r.getProperties().every(n=>i.isSpreadAssignment(n)?b(n.getExpression(),t):i.isPropertyAssignment(n)||i.isShorthandPropertyAssignment(n))}finally{t.delete(r)}},P=e=>{if(e===void 0||!i.isExpression(e))return{kind:"object",shape:{},unresolvedShape:!0};const t=S(e);return b(e)?{kind:"object",shape:t}:{kind:"object",shape:t,unresolvedShape:!0}},V=e=>{throw h(e,`computed property name ${e.getText()} must be a string literal — codegen resolves object keys statically.`)},x=e=>{const t={};for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){Object.assign(t,S(r.getExpression()));continue}const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const a=n?r.getNameNode():r.getInitializer();if(!a)continue;const s=r.getNameNode(),o=A(s)??V(s);if(!k.test(o))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(o)}`);t[o]=d(a)}return t},c=(e,t)=>e&&i.isExpression(e)?d(e):t,O=e=>e.sensitive===!0?!0:[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(r=>r!==void 0&&O(r)),M=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),$=e=>{const t=e&&g?g(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},F=(e,t,r)=>{if(T.has(e))return{kind:e};const[n,a]=t;switch(e){case"array":return{inner:c(n,{kind:"any"}),kind:"array"};case"from":return $(n);case"id":{if(!n||!i.isStringLiteral(n))throw h(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:M(n)};case"object":return P(n);case"optional":return{inner:c(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:c(n,{kind:"string"}),kind:"record",valueType:c(a,{kind:"any"})};case"sensitive":return{...c(n,{kind:"any"}),sensitive:!0};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(s=>i.isExpression(s)).map(s=>d(s))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},j=e=>{const[t]=e;if(e.length!==1||t===void 0||!i.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},C=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const a=t.getExpression(),s=i.isExpression(a)?d(a):{kind:"any"};if(p.has(r))return N(s,r);if(!m.has(r))return s;const o=r==="max"&&s.kind==="string"?j(n):void 0;return o!==void 0?{...s,hasRefinement:!0,stringMaxLength:Math.min(s.stringMaxLength??o,o)}:{...s,hasRefinement:!0,unmodelledRefinement:!0}}return F(r,n,e)};export{d as a,x as p,u as r,q as s,O as v};
@@ -1 +1 @@
1
- import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-BErjtci3.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
1
+ import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-A1XHcT4t.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
@@ -1,4 +1,4 @@
1
- import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-BErjtci3.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{mtimeMs:o,size:a}=Le(t);return`${String(o)}:${String(a)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
1
+ import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-A1XHcT4t.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{mtimeMs:o,size:a}=Le(t);return`${String(o)}:${String(a)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
2
2
  `)},tt=t=>Ge(d(t)).startsWith("@")?d(d(t)):d(t),se=(t,o)=>!y(o,t).startsWith("..")&&!t.split(ue).includes("node_modules"),ie=(t,o)=>{const a=[];let e=t;for(;e!==d(e)&&!D(h(e,"package.json"));)a.push(e),e=d(e);if(D(h(e,"package.json"))){for(const s of[...a,e,h(e,"package.json")])o.add(s);return e}},at=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==d(e);)a.add(e),e=d(e);a.add(e)},rt=(t,o)=>{const a=new Set;t.some(e=>se(e,o))&&ie(o,a);for(const e of t){if(se(e,o)){for(let n=d(e);n!==o&&n!==d(n);n=d(n))a.add(n);continue}const s=ie(d(e),a);s===void 0?at(d(e),o,a):a.add(tt(s))}return[...a].map(e=>[e,T(e)])},xe=new Map,le=([t,o])=>{try{return T(t)===o}catch{return!1}},ot=(t,o,a)=>{const e=xe.get(t);return e?.optionsKey===o&&e.stamps.every(n=>le(n))&&e.directories.every(n=>le(n))&&a!==void 0&&e.tree===a?e.files:void 0},nt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,s])=>Math.floor(Number.parseFloat(s))<=a);o.tree!==void 0&&e&&xe.set(t,{...o,tree:o.tree})},st=(t,o)=>({directories:rt(o,t),stamps:o.map(a=>[a,T(a)])}),ht=(t,o)=>{const a=d(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||_e(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const s=h(o,"services",t.name),n=c.findConfigFile(a,i=>c.sys.fileExists(i)),l=new He({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:s,rootDir:a},skipAddingFilesFromTsConfig:!0,...n===void 0?{}:{tsConfigFilePath:n}}),m=JSON.stringify([t.name,t.main,t.wranglerPath,o]),v=JSON.stringify(l.getCompilerOptions()),w=et(a,Ve(o)),g=ot(m,v,w);if(g!==void 0)return g;const A=Date.now();l.addSourceFileAtPath(t.main),l.resolveSourceFileDependencies();const $=l.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>D(i)),{directories:F,stamps:S}=st(a,$),u={...l.getCompilerOptions(),preserveSymlinks:!0},O=new Map(l.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Y(s,a,i),i])),f={};for(const i of l.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const B=O.get(he(i.filePath));if(B===void 0)continue;const R=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const k of Xe(R).toReversed()){const x=c.resolveModuleName(k.text,B,u,c.sys).resolvedModule?.resolvedFileName;if(x===void 0)continue;const I=Y(s,a,x),W=O.has(I)?I:x;b=`${b.slice(0,k.getStart(R))}${JSON.stringify(ye(d(i.filePath),W))}${b.slice(k.getEnd())}`}f[y(o,i.filePath)]=`${pe}${b}`}if(f[y(o,Y(s,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return nt(m,{files:f,optionsKey:v,directories:F,stamps:S,tree:w},A),f},it=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const s of Object.values(e.shape)){const n=Ke(s);n.kind==="storage"&&typeof n.bucket=="string"&&n.bucket!==""&&a.add(n.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,s)=>e.localeCompare(s))]},ft=({agents:t=[],capabilities:o=new Set,containers:a=[],env:e,hasVectors:s=!0,hasFlags:n=!1,hasNotify:l=!1,identity:m,queues:v=[],schema:w,services:g=[],storageRuleBuckets:A=[],topics:$=[],useUmbrella:F=!1,workflows:S=[]}={})=>{const u=Ue(F),O=it(w??{tables:[]},A).map(r=>JSON.stringify(r)).join(" | "),f=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",i=[...new Set(a.map(r=>f(r)))].toSorted((r,p)=>r.localeCompare(p)),B=a.length>0?`import type { ${i.join(", ")} } from "@lunora/container";
3
3
  `:"",R=a.length>0?`
4
4
  readonly containers: {${a.map(r=>`
@@ -1,4 +1,4 @@
1
- import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Xt,hashSchemaSnapshot as Zt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as er,isD1GlobalTable as tr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as rr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as nr,a as ar,b as sr,c as or,d as ir,f as dr,g as cr,h as lr,i as ur,j as hr,k as pr,l as mr,m as fr,n as gr,o as br,p as yr,q as wr,s as vr}from"./shard-runtime-BtEGoPTf.mjs";import{u as F,h as kr,s as Sr,a as Rr,I as xr,c as Ar,G as Or,d as Dr}from"./shared-BErjtci3.mjs";import{p as Tr}from"./platform-8oj7iXQy.mjs";import{i as _r}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Ir=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Er=` /**
1
+ import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Xt,hashSchemaSnapshot as Zt}from"./SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs";import{isHyperdriveGlobalTable as er,isD1GlobalTable as tr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as rr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as nr,a as ar,b as sr,c as or,d as ir,f as dr,g as cr,h as lr,i as ur,j as hr,k as pr,l as mr,m as fr,n as gr,o as br,p as yr,q as wr,s as vr}from"./shard-runtime-lkQU8trx.mjs";import{u as F,h as kr,s as Sr,a as Rr,I as xr,c as Ar,G as Or,d as Dr}from"./shared-A1XHcT4t.mjs";import{p as Tr}from"./platform-8oj7iXQy.mjs";import{i as _r}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Ir=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Er=` /**
2
2
  * The bare writer every admin/maintenance entry point writes through.
3
3
  *
4
4
  * Admin and maintenance writes go through the SAME reactive-cache hooks as a