@lunora/codegen 1.0.0-alpha.419 → 1.0.0-alpha.420
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.mts +20 -4
- package/dist/index.d.ts +20 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BljJJD8u.mjs +56 -0
- package/dist/packem_shared/{emitApp-CBE_wZAT.mjs → emitApp-LFKtDRYu.mjs} +26 -28
- package/package.json +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DX6xdqWK.mjs +0 -56
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APP_METHOD_CAPABILITIES as
|
|
1
|
+
import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as L,I as $,G as y}from"./shared-Cn7dMQ_u.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...T.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>I(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,P=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);
|
|
@@ -382,7 +382,7 @@ const buildGlobalCdcApplier =
|
|
|
382
382
|
|
|
383
383
|
return request.changes.length;
|
|
384
384
|
};
|
|
385
|
-
`:"",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(async () => (await import("postgres")).default(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}']:[]],
|
|
385
|
+
`:"",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(async () => (await import("postgres")).default(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>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," 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>;"]:[]],W=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
|
|
386
386
|
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
|
|
387
387
|
this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
|
|
388
388
|
|
|
@@ -456,7 +456,7 @@ const buildGlobalCdcApplier =
|
|
|
456
456
|
this.storageDeclaration = declaration;
|
|
457
457
|
|
|
458
458
|
return this;
|
|
459
|
-
}`]:[],...
|
|
459
|
+
}`]:[],...W(e)],U=e=>{const t=a=>e.hasScheduler?`
|
|
460
460
|
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" 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
|
|
461
461
|
? {
|
|
462
462
|
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 }) => {
|
|
@@ -567,7 +567,7 @@ const buildGlobalCdcApplier =
|
|
|
567
567
|
: {}),`]:[],...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 r.length>0?`
|
|
568
568
|
${r.join(`
|
|
569
569
|
`)}
|
|
570
|
-
`:""},F=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],Q=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],J=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],K=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, applySqlMigrationFiles, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],V=e=>e?['import notifyConfig from "../notify.js";']:[],Y=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],X=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Z=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,
|
|
570
|
+
`:""},F=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],Q=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],J=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],K=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, applySqlMigrationFiles, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],V=e=>e?['import notifyConfig from "../notify.js";']:[],Y=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],X=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Z=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,o=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.studioAssetsBinding!==void 0&&(e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc)?["loadStudioDocument"]:[],...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((i,u)=>i.localeCompare(u)).join(", ")} } from "${o}";`,`import { ${l} } from "${o}";`]},ee=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:o,hasScheduler:d,hasStorage:l,hasWorkflow:i}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...z(t,r),...K(a),...s?['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(n),...J(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";']:[],...i?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...Y(e),...Z(e),"",...F(e.identity),...X(e),...a||s?['import schema from "../schema.js";']:[],...V(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['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";']:[]]},S=e=>e.authClaims===void 0||e.authClaims.length===0?void 0:JSON.stringify(e.authClaims),te=e=>{const t=S(e);return t===void 0?"":`, ${t}`},re=e=>{const t=S(e);return t===void 0?"":`
|
|
571
571
|
claims: ${t},`},ae=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
|
|
572
572
|
// The schema's jurisdiction pins the auth object like every other DO.
|
|
573
573
|
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",se=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>([
|
|
@@ -584,7 +584,7 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${se(t.shardMode)}],`
|
|
|
584
584
|
|
|
585
585
|
if (adminRevocations) {
|
|
586
586
|
options.adminRevocations = adminRevocations;
|
|
587
|
-
}`],E=e=>(e.liveStreamDeclarations??[]).map(t=>{if(L(t.exportName,"live stream export name")
|
|
587
|
+
}`],E=e=>(e.liveStreamDeclarations??[]).map(t=>{if(L(t.exportName,"live stream export name"),!$.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),ie=e=>p(e)?[" httpRouter: liveStreamRouter([",...E(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],le=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ce=e=>p(e)?`liveStreamRouter([
|
|
588
588
|
${E(e).join(`
|
|
589
589
|
`)}
|
|
590
590
|
], host)`:"host",de=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],he=e=>[...ne(e),...e.hasAdminRevocations===!1?[]:oe,...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
@@ -868,14 +868,13 @@ ${E(e).join(`
|
|
|
868
868
|
}`]:[],...de(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
869
869
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
870
870
|
`)}
|
|
871
|
-
};`]:[]],ue=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,"]:[]," }),"]:[],pe=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
|
|
871
|
+
};`]:[]],ue=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,"]:[]," }),"]:[],pe=e=>{const t=[[e.wantsArchitecture,"architecture","architecture","architecture"],[e.wantsOpenApi,"openApiSpec","openapi","openApiSpec"],[e.wantsOpenRpc,"openRpcSpec","openrpc","openRpcSpec"]],{studioAssetsBinding:r}=e;return t.flatMap(([a,s,n,o])=>a?r===void 0?[` ${s}: () => import("./${n}.js").then((module) => module.${o}),`]:[` ${s}: () => loadStudioDocument((env as Record<string, unknown>)[${JSON.stringify(r)}], ${JSON.stringify(n)}),`]:[])},me=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)},`]:[],...pe(e),...ue(e),...ie(e),...le(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),",...e.spaAssetsBindings===void 0||e.spaAssetsBindings.length===0?[]:[` spaAssets: (${e.spaAssetsBindings.map(t=>`(env as Record<string, unknown>)[${JSON.stringify(t)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],be=e=>e?`
|
|
872
872
|
/** The identity memo per \`env\` object, owned by one assembled worker. */
|
|
873
873
|
type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
|
|
874
|
-
`:"",R=e=>e.hasAuth
|
|
874
|
+
`:"",R=e=>e.hasAuth,ge=e=>R(e)?`
|
|
875
875
|
/** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
|
|
876
876
|
interface DeferredModules {
|
|
877
|
-
|
|
878
|
-
`)}
|
|
877
|
+
auth: typeof LunoraAuthModule;
|
|
879
878
|
}
|
|
880
879
|
|
|
881
880
|
let deferredModules: Promise<DeferredModules> | undefined;
|
|
@@ -884,17 +883,16 @@ let deferredModules: Promise<DeferredModules> | undefined;
|
|
|
884
883
|
const loadDeferredModules = (): Promise<DeferredModules> =>
|
|
885
884
|
(deferredModules ??= (async (): Promise<DeferredModules> => {
|
|
886
885
|
return {
|
|
887
|
-
|
|
888
|
-
`)}
|
|
886
|
+
auth: await import("./authModule.js"),
|
|
889
887
|
};
|
|
890
888
|
})());
|
|
891
|
-
|
|
889
|
+
`:"",ve=(e,t)=>{const r=`buildWorker(rawEnv as Env${t})`,a=e?`
|
|
892
890
|
await ensureAuth(env);`:"",s=e?`
|
|
893
891
|
await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
|
|
894
892
|
const target = (await authReady(rawEnv as Env)) ? (worker ??= ${r}) : ${r};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
|
|
895
|
-
worker ??= ${r};`}},
|
|
896
|
-
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},
|
|
897
|
-
`:"",
|
|
893
|
+
worker ??= ${r};`}},ye=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
|
|
894
|
+
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},De=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
|
|
895
|
+
`:"",fe=e=>{const t=e.emailAgents??[];if(t.length===0)return"";const r=a=>t.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
|
|
898
896
|
`);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
|
|
899
897
|
${r(" ")}
|
|
900
898
|
]);
|
|
@@ -913,14 +911,14 @@ ${r(" ")}
|
|
|
913
911
|
return agentEmail(message, rawEnv, context);
|
|
914
912
|
};
|
|
915
913
|
|
|
916
|
-
`},
|
|
914
|
+
`},we=e=>e.securityHeaders===void 0?"":`
|
|
917
915
|
/**
|
|
918
916
|
* \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
|
|
919
917
|
* the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
|
|
920
918
|
* \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
|
|
921
919
|
*/
|
|
922
920
|
const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
|
|
923
|
-
`,
|
|
921
|
+
`,ke=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),Ae=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=M(r),n=he(r),o=a?` let auth: LunoraAuth | null = null;
|
|
924
922
|
let authInit: Promise<void> | null = null;
|
|
925
923
|
// One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
|
|
926
924
|
// \`assemble()\` has its own auth closure and must not share.
|
|
@@ -991,8 +989,8 @@ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.s
|
|
|
991
989
|
return false;
|
|
992
990
|
},
|
|
993
991
|
);
|
|
994
|
-
`:"",{asyncIfDeferred:l,deferredArgument:
|
|
995
|
-
host ? withFrameworkWorker(${ce(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,O=r.hasFramework?"host?: FrameworkHostHandler":"",q=
|
|
992
|
+
`:"",{asyncIfDeferred:l,deferredArgument:i,deferredParameter:u,loadDeferredLine:h}=ye(r),{ensureAuthCall:D,ensureRawAuthCall:A,eventWorker:m,eventWorkerLine:b}=ve(a,i),g=`${a?"() => auth, identityMemos":"() => null"}${i}`,x=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,C=r.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
|
|
993
|
+
host ? withFrameworkWorker(${ce(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,O=r.hasFramework?"host?: FrameworkHostHandler":"",q=fe(r),N=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
996
994
|
public build(): ComposedApp {
|
|
997
995
|
return this.assemble();
|
|
998
996
|
}${r.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}${ee(r).join(`
|
|
@@ -1003,7 +1001,7 @@ type Selector<Env, T> = (env: Env) => T | undefined;
|
|
|
1003
1001
|
|
|
1004
1002
|
/** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
1005
1003
|
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
1006
|
-
${
|
|
1004
|
+
${we(r)}${be(a)}${ge(r)}${r.jurisdiction?`
|
|
1007
1005
|
// Module scope, so every isolate loading this script (the worker and each Durable
|
|
1008
1006
|
// Object class it exports) knows the schema's jurisdiction before a request runs.
|
|
1009
1007
|
// \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
|
|
@@ -1028,7 +1026,7 @@ interface ComposedApp extends LunoraWorker {
|
|
|
1028
1026
|
* first request so per-isolate singletons are built once.
|
|
1029
1027
|
*/
|
|
1030
1028
|
class AppBuilder<Env extends object> {
|
|
1031
|
-
${
|
|
1029
|
+
${B(r).join(`
|
|
1032
1030
|
`)}
|
|
1033
1031
|
|
|
1034
1032
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
@@ -1037,7 +1035,7 @@ ${H(r).join(`
|
|
|
1037
1035
|
|
|
1038
1036
|
`)}
|
|
1039
1037
|
|
|
1040
|
-
${
|
|
1038
|
+
${N}
|
|
1041
1039
|
|
|
1042
1040
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
1043
1041
|
private assemble(${O}): ComposedApp {
|
|
@@ -1047,14 +1045,14 @@ ${T}
|
|
|
1047
1045
|
// build, so the first request constructs them and every later request on
|
|
1048
1046
|
// the same isolate reuses them.
|
|
1049
1047
|
let worker: LunoraWorker | null = null;
|
|
1050
|
-
${
|
|
1048
|
+
${o}${d}
|
|
1051
1049
|
${C}
|
|
1052
1050
|
|
|
1053
1051
|
const composed: ComposedApp = {
|
|
1054
1052
|
ShardDO,
|
|
1055
1053
|
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
1056
1054
|
const env = rawEnv as Env;${h}${D}
|
|
1057
|
-
worker ??= buildWorker(env${
|
|
1055
|
+
worker ??= buildWorker(env${i});
|
|
1058
1056
|
|
|
1059
1057
|
return worker.fetch(request, rawEnv, context);
|
|
1060
1058
|
},
|
|
@@ -1063,7 +1061,7 @@ ${C}
|
|
|
1063
1061
|
return ${m}.scheduled(controller, rawEnv, context);
|
|
1064
1062
|
},
|
|
1065
1063
|
serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${A}
|
|
1066
|
-
worker ??= buildWorker(rawEnv as Env${
|
|
1064
|
+
worker ??= buildWorker(rawEnv as Env${i});
|
|
1067
1065
|
|
|
1068
1066
|
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
1069
1067
|
},${r.hasQueue||r.hasFramework?`
|
|
@@ -1096,7 +1094,7 @@ ${P(r)}${G(r.hasStorage)}
|
|
|
1096
1094
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
1097
1095
|
private buildWorkerOptions(env: Env, ${x}): WorkerOptions {
|
|
1098
1096
|
const options: WorkerOptions = {
|
|
1099
|
-
${
|
|
1097
|
+
${me(r).join(`
|
|
1100
1098
|
`)}
|
|
1101
1099
|
};
|
|
1102
1100
|
|
|
@@ -1160,5 +1158,5 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
1160
1158
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
1161
1159
|
|
|
1162
1160
|
export { AppBuilder, defineApp${r.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
|
|
1163
|
-
export type { ${
|
|
1164
|
-
`};export{
|
|
1161
|
+
export type { ${ke(r)} };
|
|
1162
|
+
`};export{Ae as emitApp,De as emitAuthModule};
|