@lunora/codegen 1.0.0-alpha.380 → 1.0.0-alpha.382

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 CHANGED
@@ -4218,7 +4218,9 @@ declare const emitContainers: (containers: ReadonlyArray<ContainerIR>, jurisdict
4218
4218
  * `workflows[].class_name` to be exported by the deployed worker. Returns ""
4219
4219
  * when the project declares no workflows (the file is not written then).
4220
4220
  */
4221
- declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
4221
+ declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>, options?: {
4222
+ lazy?: boolean;
4223
+ }) => string;
4222
4224
  /**
4223
4225
  * Emit `_generated/agents.ts` — one `WorkflowEntrypoint` class per `defineAgent`
4224
4226
  * export, each a thin subclass of `LunoraWorkflow` (`@lunora/workflow/do`)
@@ -4228,7 +4230,9 @@ declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
4228
4230
  * deployed worker. Returns "" when the project declares no agents (the file is
4229
4231
  * not written then).
4230
4232
  */
4231
- declare const emitAgents: (agents: ReadonlyArray<AgentIR>) => string;
4233
+ declare const emitAgents: (agents: ReadonlyArray<AgentIR>, options?: {
4234
+ lazy?: boolean;
4235
+ }) => string;
4232
4236
  declare const GENERATED_HEADER = "// GENERATED by @lunora/codegen — do not edit.\n// Run `lunora codegen` to regenerate.\n\n";
4233
4237
  /** Which capability methods the generated `defineApp` builder exposes — one flag per package-backed feature the app actually uses. */
4234
4238
  interface EmitAppOptions {
@@ -4321,6 +4325,13 @@ interface EmitAppOptions {
4321
4325
  * auth object (codegen refuses a project it can see doing that).
4322
4326
  */
4323
4327
  jurisdictionPinsAuth?: boolean;
4328
+ /**
4329
+ * The lazy function registry is selected (`--lazy-functions`). The modules the
4330
+ * worker reaches only from an event entry — the push-queue registry and the
4331
+ * `onEmail` agent definitions — then load with `import()` on that event instead
4332
+ * of at isolate startup. Absent or `false` keeps the eager output unchanged.
4333
+ */
4334
+ lazyFunctions?: boolean;
4324
4335
  /**
4325
4336
  * Every `defineLiveStream` the app declares, read from its literals. With `liveStreams` set, the worker mounts
4326
4337
  * each stream's connect and control routes itself (`liveStreamRouter`), so the app mounts none.
package/dist/index.d.ts CHANGED
@@ -4218,7 +4218,9 @@ declare const emitContainers: (containers: ReadonlyArray<ContainerIR>, jurisdict
4218
4218
  * `workflows[].class_name` to be exported by the deployed worker. Returns ""
4219
4219
  * when the project declares no workflows (the file is not written then).
4220
4220
  */
4221
- declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
4221
+ declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>, options?: {
4222
+ lazy?: boolean;
4223
+ }) => string;
4222
4224
  /**
4223
4225
  * Emit `_generated/agents.ts` — one `WorkflowEntrypoint` class per `defineAgent`
4224
4226
  * export, each a thin subclass of `LunoraWorkflow` (`@lunora/workflow/do`)
@@ -4228,7 +4230,9 @@ declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
4228
4230
  * deployed worker. Returns "" when the project declares no agents (the file is
4229
4231
  * not written then).
4230
4232
  */
4231
- declare const emitAgents: (agents: ReadonlyArray<AgentIR>) => string;
4233
+ declare const emitAgents: (agents: ReadonlyArray<AgentIR>, options?: {
4234
+ lazy?: boolean;
4235
+ }) => string;
4232
4236
  declare const GENERATED_HEADER = "// GENERATED by @lunora/codegen — do not edit.\n// Run `lunora codegen` to regenerate.\n\n";
4233
4237
  /** Which capability methods the generated `defineApp` builder exposes — one flag per package-backed feature the app actually uses. */
4234
4238
  interface EmitAppOptions {
@@ -4321,6 +4325,13 @@ interface EmitAppOptions {
4321
4325
  * auth object (codegen refuses a project it can see doing that).
4322
4326
  */
4323
4327
  jurisdictionPinsAuth?: boolean;
4328
+ /**
4329
+ * The lazy function registry is selected (`--lazy-functions`). The modules the
4330
+ * worker reaches only from an event entry — the push-queue registry and the
4331
+ * `onEmail` agent definitions — then load with `import()` on that event instead
4332
+ * of at isolate startup. Absent or `false` keeps the eager output unchanged.
4333
+ */
4334
+ lazyFunctions?: boolean;
4324
4335
  /**
4325
4336
  * Every `defineLiveStream` the app declares, read from its literals. With `liveStreams` set, the worker mounts
4326
4337
  * each stream's connect and control routes itself (`liveStreamRouter`), so the app mounts none.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DKYJ2K4t.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CN8HACEL.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-a0IT8OSb.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DHDfKLoa.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs";import{default as J}from"./packem_shared/discoverInserts-IAa3lRR4.mjs";import{d as X}from"./packem_shared/index-BjDVAPNW.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Ipxibja6.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-B-t7jQSm.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-DZOGiEPs.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-B0DYk-gW.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-D4Em7RoZ.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-Ct2wK_Tj.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DA0ZNkhl.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CJ3djlcz.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as gr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-BmCxM6tO.mjs";import{e as Ur}from"./packem_shared/server-BY1v1bTx.mjs";import{e as Hr}from"./packem_shared/shard-DmDBaK79.mjs";import{G as Br}from"./packem_shared/shared-BErjtci3.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{t as Yr,u as Xr,v as Zr}from"./packem_shared/shard-runtime-BtEGoPTf.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-D6uqyYd_.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-C3RiGYk7.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-BMMht_iZ.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-NGByI1FZ.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,gr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DKYJ2K4t.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CN8HACEL.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-a0IT8OSb.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DHDfKLoa.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs";import{default as J}from"./packem_shared/discoverInserts-IAa3lRR4.mjs";import{d as X}from"./packem_shared/index-BjDVAPNW.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Ipxibja6.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-B-t7jQSm.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-DZOGiEPs.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-B0DYk-gW.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-D9kGG9Mu.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-Ct2wK_Tj.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DA0ZNkhl.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CQyAtphV.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as gr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-BmCxM6tO.mjs";import{e as Ur}from"./packem_shared/server-BY1v1bTx.mjs";import{e as Hr}from"./packem_shared/shard-DNXF9VZ5.mjs";import{G as Br}from"./packem_shared/shared-BErjtci3.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{t as Yr,u as Xr,v as Zr}from"./packem_shared/shard-runtime-Bg8MOBzw.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-D6uqyYd_.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-C3RiGYk7.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-BMMht_iZ.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-NGByI1FZ.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,gr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as z,readFileSync as Xe,mkdirSync as qt,writeFileSync as Sr,rmSync as Ne,readdirSync as Rn}from"node:fs";import{dirname as jt,join as E,relative as Fn}from"node:path";import{performance as xt}from"node:perf_hooks";import{runAdvisor as Ar}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as yr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as br}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ht,ts as Nr,VariableDeclarationKind as Gt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as de,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as Pr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Ln,limitNameOf as Dn,optionsObjectLiteral as Mn,handlerOf as wr,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Yt,returningFunctionOf as Ot,walkChain as Ir,RUN_METHODS as _n,functionReferenceSegments as Tr,isTestPath as Cr,isFunctionLike as oe,functionKeyOf as zn,withSourceListMemo as Or}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as M,g as Qt,c as S,a as tt,w as Xt,k as kr,l as Rr,h as Fr,m as Lr,j as kt,i as Dr}from"./attribution-DUbGYT4N.mjs";import{a as zs,r as St,i as Y,b as Mr,m as Kn,c as st,e as Jt,E as $n,C as Bn,d as _r,f as zr,g as Kr}from"./context-root-BPfMNAJM.mjs";import{a as I,i as Vn,c as te,d as Un,e as $r,f as Br,g as Wn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Vr}from"./property-name-7cBlgK_O.mjs";import{b as Ur,a as nt}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as Wr}from"./parse-validator-CP5CL6Q7.mjs";import qr from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as qn}from"./database-calls-hLzaOquW.mjs";import jr from"./discoverHyperdriveCalls-i8Zcf64H.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as jn,d as Hr}from"./index-BjDVAPNW.mjs";import{MUTATORS_FILENAME as Gr,isDefineMutatorCallee as Yr,mutatorServerImplOf as Qr,discoverMutators as Xr}from"./MUTATORS_FILENAME-Ipxibja6.mjs";import Jr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Zr,discoverNotifyCalls as eo}from"./NOTIFY_FILENAME-B-t7jQSm.mjs";import to from"./discoverR2sqlCalls-Lq6G--TZ.mjs";import so from"./discoverRlsProcedures-B0DYk-gW.mjs";import{s as es,n as no}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as io,redact as ro,isHeuristicSecretKind as oo,isSecretishName as ao}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Hn,readMergeDurableObjects as co}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as lo,r as uo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as fo,discoverWorkflows as go}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as po}from"./json-data-Chfs2Cz5.mjs";import{a as mo,I as ho,g as vo,G as Gn,d as Eo,i as xo}from"./shared-BErjtci3.mjs";import{createCodegenProject as So}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as zE,refreshCodegenProject as KE,tsconfigFingerprint as $E}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Ao,usedCapabilities as yo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Yn,isHyperdriveGlobalTable as Qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bo}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as No}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import Po from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as wo,fileWiresRequestSecretTool as Io,createTargetScope as To,discoverFeatureUsage as Co}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Xn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Oo,findProjectConfigFile as ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ro}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as Fo}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Lo}from"./readServiceBindings-BA49C6aN.mjs";import Do from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as Mo,readTargetDiagnostics as _o,vectorizeDimensionDiagnostics as zo,liveStreamsDeliveryAuthorizationDiagnostic as Ko,socketRoutesDeliveryAuthorizationDiagnostic as $o,studioPlatformFor as Bo,platformFeatureAvailable as Vo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Uo}from"./schema-BgM8A3XV.mjs";import{b as Jn,e as Wo}from"./shard-DmDBaK79.mjs";import{e as qo,a as jo}from"./server-BY1v1bTx.mjs";import{emitDataModel as Ho}from"./emitDataModel-BMMht_iZ.mjs";import{i as Go,a as Yo,e as Qo,b as Xo,d as Jo,c as Zo}from"./unwrap-handler-return-eQRIZSOX.mjs";import ea from"./discoverFunctions-a0IT8OSb.mjs";import ta from"./discoverHttpRoutes-DHDfKLoa.mjs";import sa from"./discoverInserts-IAa3lRR4.mjs";import{e as Zn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import na from"./discoverMigrations-Bv8kNIgy.mjs";import ia from"./discoverQueries-DZOGiEPs.mjs";import ra from"./discoverRlsMetadata-Dq6iSXnC.mjs";import oa from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as aa}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as la,emitApp as da}from"./emitApp-D4Em7RoZ.mjs";import{readJsonSync as ua}from"@visulima/fs";import{buildSchemaSnapshot as fa}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as ga,emitOpenApiModule as pa}from"./buildOpenApiDocument-Ct2wK_Tj.mjs";import{buildOpenRpcDocument as ma,emitOpenRpcModule as ha}from"./OPENRPC_VERSION-DA0ZNkhl.mjs";import{w as va,u as Ea,v as xa,t as Sa,x as Aa}from"./shard-runtime-BtEGoPTf.mjs";import{emitCollections as ya,emitSeed as ba,emitApi as Na,emitInternalApi as Pa}from"./emitApi-D6uqyYd_.mjs";import{emitCrons as wa,emitScheduler as Ia,emitShardRegistry as Ta,emitDurableObjects as Ca,emitVectors as Oa,emitWranglerCronTriggers as ka}from"./emitCrons-C3RiGYk7.mjs";import Ra from"./emitDrizzleSchema-BmCxM6tO.mjs";import{LAZY_FUNCTION_DIRECTORY as ei,emitFunctions as Fa,emitLazyFunctionModules as La}from"./emitFunctions-NGByI1FZ.mjs";const Da=(e,t=!1)=>{if(e.length===0)return"";const s=Eo(t),n=e.map(c=>{if(mo(c.exportName,"live stream export name"),!ho.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{vo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as z,readFileSync as Xe,mkdirSync as qt,writeFileSync as Sr,rmSync as Ne,readdirSync as Rn}from"node:fs";import{dirname as jt,join as E,relative as Fn}from"node:path";import{performance as xt}from"node:perf_hooks";import{runAdvisor as Ar}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as yr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as br}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ht,ts as Nr,VariableDeclarationKind as Gt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as de,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as Pr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Ln,limitNameOf as Dn,optionsObjectLiteral as Mn,handlerOf as wr,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Yt,returningFunctionOf as Ot,walkChain as Ir,RUN_METHODS as _n,functionReferenceSegments as Tr,isTestPath as Cr,isFunctionLike as oe,functionKeyOf as zn,withSourceListMemo as Or}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as M,g as Qt,c as S,a as tt,w as Xt,k as kr,l as Rr,h as Fr,m as Lr,j as kt,i as Dr}from"./attribution-DUbGYT4N.mjs";import{a as zs,r as St,i as Y,b as Mr,m as Kn,c as st,e as Jt,E as $n,C as Bn,d as _r,f as zr,g as Kr}from"./context-root-BPfMNAJM.mjs";import{a as I,i as Vn,c as te,d as Un,e as $r,f as Br,g as Wn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Vr}from"./property-name-7cBlgK_O.mjs";import{b as Ur,a as nt}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as Wr}from"./parse-validator-CP5CL6Q7.mjs";import qr from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as qn}from"./database-calls-hLzaOquW.mjs";import jr from"./discoverHyperdriveCalls-i8Zcf64H.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as jn,d as Hr}from"./index-BjDVAPNW.mjs";import{MUTATORS_FILENAME as Gr,isDefineMutatorCallee as Yr,mutatorServerImplOf as Qr,discoverMutators as Xr}from"./MUTATORS_FILENAME-Ipxibja6.mjs";import Jr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Zr,discoverNotifyCalls as eo}from"./NOTIFY_FILENAME-B-t7jQSm.mjs";import to from"./discoverR2sqlCalls-Lq6G--TZ.mjs";import so from"./discoverRlsProcedures-B0DYk-gW.mjs";import{s as es,n as no}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as io,redact as ro,isHeuristicSecretKind as oo,isSecretishName as ao}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Hn,readMergeDurableObjects as co}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as lo,r as uo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as fo,discoverWorkflows as go}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as po}from"./json-data-Chfs2Cz5.mjs";import{a as mo,I as ho,g as vo,G as Gn,d as Eo,i as xo}from"./shared-BErjtci3.mjs";import{createCodegenProject as So}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as zE,refreshCodegenProject as KE,tsconfigFingerprint as $E}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Ao,usedCapabilities as yo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Yn,isHyperdriveGlobalTable as Qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bo}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as No}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import Po from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as wo,fileWiresRequestSecretTool as Io,createTargetScope as To,discoverFeatureUsage as Co}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Xn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Oo,findProjectConfigFile as ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ro}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as Fo}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Lo}from"./readServiceBindings-BA49C6aN.mjs";import Do from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as Mo,readTargetDiagnostics as _o,vectorizeDimensionDiagnostics as zo,liveStreamsDeliveryAuthorizationDiagnostic as Ko,socketRoutesDeliveryAuthorizationDiagnostic as $o,studioPlatformFor as Bo,platformFeatureAvailable as Vo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Uo}from"./schema-BgM8A3XV.mjs";import{b as Jn,e as Wo}from"./shard-DNXF9VZ5.mjs";import{e as qo,a as jo}from"./server-BY1v1bTx.mjs";import{emitDataModel as Ho}from"./emitDataModel-BMMht_iZ.mjs";import{i as Go,a as Yo,e as Qo,b as Xo,d as Jo,c as Zo}from"./unwrap-handler-return-eQRIZSOX.mjs";import ea from"./discoverFunctions-a0IT8OSb.mjs";import ta from"./discoverHttpRoutes-DHDfKLoa.mjs";import sa from"./discoverInserts-IAa3lRR4.mjs";import{e as Zn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import na from"./discoverMigrations-Bv8kNIgy.mjs";import ia from"./discoverQueries-DZOGiEPs.mjs";import ra from"./discoverRlsMetadata-Dq6iSXnC.mjs";import oa from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as aa}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as la,emitApp as da}from"./emitApp-D9kGG9Mu.mjs";import{readJsonSync as ua}from"@visulima/fs";import{buildSchemaSnapshot as fa}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as ga,emitOpenApiModule as pa}from"./buildOpenApiDocument-Ct2wK_Tj.mjs";import{buildOpenRpcDocument as ma,emitOpenRpcModule as ha}from"./OPENRPC_VERSION-DA0ZNkhl.mjs";import{w as va,u as Ea,v as xa,t as Sa,x as Aa}from"./shard-runtime-Bg8MOBzw.mjs";import{emitCollections as ya,emitSeed as ba,emitApi as Na,emitInternalApi as Pa}from"./emitApi-D6uqyYd_.mjs";import{emitCrons as wa,emitScheduler as Ia,emitShardRegistry as Ta,emitDurableObjects as Ca,emitVectors as Oa,emitWranglerCronTriggers as ka}from"./emitCrons-C3RiGYk7.mjs";import Ra from"./emitDrizzleSchema-BmCxM6tO.mjs";import{LAZY_FUNCTION_DIRECTORY as ei,emitFunctions as Fa,emitLazyFunctionModules as La}from"./emitFunctions-NGByI1FZ.mjs";const Da=(e,t=!1)=>{if(e.length===0)return"";const s=Eo(t),n=e.map(c=>{if(mo(c.exportName,"live stream export name"),!ho.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{vo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${v}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -27,5 +27,5 @@ ${i}
27
27
 
28
28
  Install them with your package manager, then re-run codegen.`)},Up="env.ts",Wp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return nt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},qp=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&nt(n.getModuleSpecifierValue())}return!1},jp=e=>{if(r.isIdentifier(e))return Wp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&qp(t)}return!1},Hp=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!jp(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ae(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=tt(s,"member");a!==void 0&&t.push({exportName:a})}return t},Gp=(e,t)=>{const s=E(t,Up);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Hp(n);if(i.length!==0){if(i.length>1)throw ae(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Yp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Qp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Xp=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Jp=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Zp=new Set(["durable"]),em=new Set(["rollback"]),Ki=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},tm="defineApp",be="app",An=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===be&&s.getInitializer()?.getText()===t)||t===be&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===be),sm=e=>{if(e===void 0||!Oo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===be;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===be;if(r.isVariableDeclaration(t))return An(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&An(e.getSourceFile(),s)},nm="AppBuilder",$i=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},im=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===nm&&s.getDeclarations().some(n=>$i(n))},rm=e=>e.getText()===tm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||$i(t)),Bi=(e,t,s=new Set)=>{const n=Ze(t);if(n===void 0||!r.isIdentifier(n))return!1;if(rm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return sm(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Bi(e,a.getInitializer(),s)}}return!1},Vi=(e,t)=>{const s=Yt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Bi(e,s.object)||im(s.object))},om=new Map([["defineContainer",{keys:Qp,signal:"containerEgressPolicy"}],["defineStep",{keys:em,signal:"workflowRollback"}],["stream",{keys:Zp,signal:"durableStreams"}]]),am=(e,t)=>{const s=om.get(Ki(t));if(s!==void 0)return t.getArguments().some(n=>Jp(Xp(e,n),s.keys))?s.signal:void 0},cm=(e,t)=>Yp[Ki(t)]??(Vi(e,t)?"deliveryAuthorization":void 0),lm=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=wo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=x(o,d.CallExpression);for(const c of a){const l=am(o,c)??cm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Wn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Ht({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Xe(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Vi(i,o))}return n},dm=(e,t)=>{const s=To();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Io(i,s))return!0}return!1},um="createWorker",fm="extend",yn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,bn=e=>{const t=[],s=yn(F(e,"backupCron"));s!==void 0&&t.push(s);const n=F(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=yn(i.getNameNode());o!==void 0&&t.push(o)}return t},gm=e=>{const t=I(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===um)return r.isObjectLiteralExpression(s)?bn(s):[];if(t!==fm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Ln(s.getBody());return n===void 0?[]:bn(n)},pm=(e,t)=>{const s=[];for(const{filePath:n}of Je(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression))s.push(...gm(o))}return[...new Set(s)]},Ui=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Ui(e.inner)},mm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Ui(n);return i!==void 0&&t.has(i)}))},hm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},vm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=rd(s,t),a=Gp(s,t),c=go(s,t),{queues:l,topics:u}=Ro(s,t),f=Lo(n),g=bo(s,t);hm(c,g);const m=No(s,t),v=Do(s,t),B=Po(s,t,c,g),fe=pm(s,t),N=lm(s,t,ko(n)),V=Fo(s,t),G=dm(s,t),D=Co(s,t);D.browser=D.browser||V.usesSandboxBrowser;const R=Rt(n,e.target),O=Mo(D,R,{agents:g.length>0,commitOrderedTables:i.tables.some(_=>_.commitOrdered===!0),cronTriggers:B.length>0,crossShardFanout:i.tables.some(_=>Uo(_)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(_=>_.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(_=>_.sandbox===!0),deliveryAuthorization:N.deliveryAuthorization,durableStreams:N.durableStreams,globalTables:i.tables.some(_=>_.shardMode==="global"),liveContext:N.liveContext,liveStreams:N.liveStreams,typedWebSockets:N.typedWebSockets,queues:l.length>0,relationGraph:mm(i),secretValues:G,secrets:N.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(_=>_.schedules!==void 0)}),W=O.usage,J=yo(W),se=O.signals.vectorStore!==!1,ne=O.signals.services===!1?[]:f,ce=Xn(n),$=ce??new Set,P=$.has("lunorash");Vp(i,ce,{hasVectors:se,scheduler:W.scheduler||B.length>0,storage:W.storage||v.rules.length>0||Object.keys(Jn(i)).length>0,usage:W});const k=z(E(t,"flags.ts")),Ce=z(E(t,"notify.ts"));return{agents:g,capabilities:J,containers:m,crons:B,dataModelContent:Ho(i),declaredDependencies:ce,dependencies:$,entryCronTriggers:fe,env:a,featureUsage:W,hasFlags:k,hasNotify:Ce,identity:o,platformGate:{...O,diagnostics:[..._o(n,e.target),...O.diagnostics,...zo(R,i.vectorIndexes),...N.liveStreams&&N.deliveryAuthorization?[Ko(R)]:[],...N.socketRoutes&&N.deliveryAuthorization?[$o(R)]:[]]},queues:l,serverContent:qo({agents:g,capabilities:J,containers:m,env:a,hasVectors:se,hasFlags:k,hasNotify:Ce,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:v.rules.map(_=>_.bucket),topics:u,useUmbrella:P,workflows:c}),services:ne,storageRulesMetadata:v,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:P,workflows:c}},Wi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Em=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},xm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Sm=/^[\w$]+:[\w$]+$/u,Am=(e,t)=>{const s=zn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Nn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},ym=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Nn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Gt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Nn(s):void 0}}},bm=(e,t,s)=>({schedule:{argKeys:ym(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Nm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(_n.has(s))return Am(s,n);if((s==="runAfter"||s==="runAt")&&Em(t)){const l=zn(i)??(r.isStringLiteral(i)&&Sm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...bm(s,n,o)}}const a=xm.get(s),c=a===void 0?void 0:Wi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Pm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),qi=e=>Nr.isOptionalChain(e.compilerNode),wm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:oe(t)?t.getFirstAncestor(oe)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Pm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&qi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&zg(s)),Im=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(oe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(oe),i))===!0},Tm=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),Cm=(e,t)=>{if(qi(e)||t==="schedule"&&Im(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(wm(s,i)){if(!Tm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Pn=(e,t,s)=>{if(s===void 0)return;const n=Cm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Om=(e,t)=>[...C(e,t,(s,n)=>Pn(s,n,Nm(s))),...ie(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Wi(s,"services");return Pn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],km=new Set(["boolean","number","object","string"]),Rm=e=>{const t=e.getName();if(!km.has(t))return;const s=e.getExpression();return Y(s,["flags"])||Y(s,["flags","details"])?t:void 0},Fm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Rm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Lm=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression)){const a=Fm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Dm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||Go(o))return;const a=e.getSourceFile().getFilePath();if(Yo(i,e,a)){const c=Qo(i,e,a,0,new Set);return c===void 0&&Xo(o),c}return o},Mm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Vr(t.getNameNode());return s===void 0||s==="namespace"}),_m=(e,t)=>{for(const{filePath:s}of Je(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of x(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Mm(a)))return i}}},zm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Km=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ae(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${zm}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},$m="room:",Bm="__lunora_socket__:",Vm=/^[A-Za-z]\w*$/u,wn=e=>Vm.test(e),Um=e=>`${e}:`.startsWith($m)||`${e}:`.startsWith(Bm),ji=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Hi=e=>ji(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),In=e=>A(e),ls=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),le=(e,t)=>{const s=ae(e,`defineLiveStream ${t}`);return new L("LIVE_STREAM_NOT_LITERAL",s.message)},Gi=(e,t,s)=>{const n=ls(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw le(n??e,`needs ${s} so codegen can read its topics`);if(Hi(i))throw le(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Wm=(e,t)=>{const s=In(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw le(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Hi(n))throw le(n,`cannot spread into or compute the keys of topic "${s}"`);if(!wn(s)||Um(s))throw new L("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(ls(n,"key")===void 0)return{fields:[],name:s};const a=Gi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>In(l)),c=a.find(l=>!wn(l));if(c!==void 0)throw new L("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},qm=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw le(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(ji(n))throw le(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ls(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw le(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Gi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:w(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Wm(a,l))}},jm=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new L("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},Hm=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Gm=(e,t)=>x(e,d.CallExpression).filter(s=>Wn(s,"defineLiveStream")).map(s=>{const n=Hm(s),i=r.isVariableDeclaration(n)?tt(n,"binding"):void 0;if(i===void 0)throw new L("LIVE_STREAM_NOT_EXPORTED",ae(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return qm(s,i,t)}),Ym=(e,t)=>{const s=y(t).flatMap(n=>Gm(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return jm(s),s},Qm=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Xm=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Qm(e):!0,Yi=(e,t=!1)=>{for(const s of e.getProperties()){if(Xm(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Yi(n,!0))return!0}return!1},Jm=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Zn(n))for(const o of Zt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Yi(a)))return!0}}return!1},Zm=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=We(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=We(a);c!==void 0&&s.push({column:c,strategy:jn(a),table:i})}}return s},eh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Zn(i))for(const a of Zt(o))for(const c of Zm(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},th=["providerSubscriptionId","state"],sh=["providerEventId","processedAt"],Tn=(e,t)=>t.every(s=>s in e.shape),nh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Tn(t,th)&&Tn(s,sh)},ih=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],rh=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},oh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},ah="@lunora/privacy",Qi="userId",Cn=new Set(["user","users"]),ch=e=>e.replaceAll("\\","/"),lh="privacy",dh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),ot=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ie=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",ds=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),uh=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},at=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},fh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=uh(s,"tables"),i=ot(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:ds(n).map(a=>Ie(a)))t.datasets.set(o,i)},us=8,he=(e,t=0)=>{if(t>us)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return he(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:he(i,t+1)},gh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:he(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?ds(n):[],o=new Set(i.map(a=>Ie(a)));for(const a of ih)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?ot(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ie(a)==="user"&&t.userTables.add(c))}},On=(e,t,s)=>{t.datasets.set(ot(e.getArguments()[0])??s,s)},ph=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ie(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Xi=(e,t=0)=>{const s=he(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>us)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Xi(i.getExpression(),t+1):[ph(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},mh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Xi(t)},hh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:he(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?ds(n):[])t.excluded.set(Ie(i),r.isPropertyAssignment(i)?ot(i.getInitializer())??"":"")},vh=(e,t)=>{switch(at(e)){case"actionCacheDataset":{On(e,t,"actionCache");break}case"authDataset":{gh(e,t);break}case"defineDataset":{fh(e,t);break}case"documentHistoryDataset":{On(e,t,"documentHistory");break}}},fs=e=>e!==void 0&&r.isCallExpression(e)&&at(e)==="defineDataset",Ji=e=>e!==void 0&&r.isCallExpression(e)&&dh.has(at(e)??""),Eh=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(fs(i)||Ji(i))?n:void 0},Zi=(e,t,s=0)=>{const n=he(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>us)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Zi(i.getExpression(),t,s+1))return!1}else if(!fs(i)&&!Ji(i)){const o=r.isIdentifier(i)?Eh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},xh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Zi(t,s)?s:void 0},Sh=(e,t)=>{const s=[];for(const i of x(e,d.CallExpression))if(vh(i,t),at(i)==="definePrivacy"){const o=mh(i);hh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:xh(o)})}return{declared:x(e,d.VariableDeclaration).filter(i=>fs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Ah=(e,t)=>{const s=E(t,"schema.ts"),n=[...y(t),...z(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>ch(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},yh=(e,t,s)=>{if(s?.has(ah)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Cn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Cn)},i=[],o=[];for(const f of Ah(e,t)){const g=Sh(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:rh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},er=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&er(n,t)),bh=(e,t)=>e.extensionKey!==lh&&(Qi in e.shape||Object.values(e.shape).some(s=>er(s,t))),Nh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Qi}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Ph=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>bh(o,t.userTables)).map(o=>o.name),[n]=oh(s,t.classifications);if(n!==void 0)throw new L("PRIVACY_COVERAGE",Nh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new L("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},wh=(e,t)=>{const s=Bo(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Ih=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),kn=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Th="",Ch=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Oh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Gt.Const?t.getInitializer():void 0},Ve=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ve(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Oh(e);if(n!==void 0)return Ve(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},kh=(e,t)=>{if(Ih.has(e))return{method:e,tables:Ve(t)??[Th]}},Ct=(e,t,s)=>e===void 0?void 0:{...e,fields:Ch(t,e.method,s)},Rh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Gt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!K(s.getExpression())))return s.getName()},Fh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Rh(n);if(i!==void 0)return kn.has(s)?Ct({method:s,tables:[i]},e,1):void 0;if(K(n))return Ct(kh(s,e.getArguments()[0]),e,2);if(kn.has(s)&&r.isPropertyAccessExpression(n)&&K(n.getExpression()))return Ct({method:s,tables:[n.getName()]},e,1)},Lh=(e,t)=>C(e,t,(s,n)=>{const i=Fh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Dh=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Mh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return ss(e,t).opaque},_h=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=te(a);c!==void 0&&Mh(a,c.receiver)&&s.push(Dh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},zh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(..._h(i,w(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Kh=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Qe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),tr=e=>!e.isAny(),sr=e=>{const t=e.getType();if(!tr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Kh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},$h=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},nr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Bh=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),Vh={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},Uh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Wh={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},qh=(e,t,s)=>{if(!t.some(i=>Dr(i)))return Vh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Uh.has(s.typeName)&&!n&&!t.some(i=>ca(i))?Wh:nr},ir=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Bh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},jh=(e,t,s)=>{const n=[];for(const i of X(e)){const o=r.isIdentifier(i.getNameNode())?kt(i):[i.getName()],c=o.some(u=>Qe(s,t,u))||!$h(i)?void 0:sr(i),[l=i.getName()]=o;c!==void 0&&n.push(ir(t,l,c,i.getStartLineNumber(),qh(i,o,c)))}return n},Hh=(e,t,s)=>{if(Qe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=sr(i.getExpression());o!==void 0&&n.push(ir(t,"default",o,i.getStartLineNumber(),nr))}return n},Gh=(e,t,s)=>[...jh(e,t,s),...Hh(e,t,s)],Yh=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>kt(n).some(i=>Qe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=kt(n).find(o=>Qe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Qh=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),Xh=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Gh(c,l,s)),i.push(...Yh(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!tr(a.getType()))&&n.push(Qh(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Jh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},Zh=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},ev=(e,t)=>C(e,t,(s,n)=>Jh(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:Zh(s)}:void 0),rr=e=>e==="@lunora/workflow",tv=e=>new Set(e.getImportDeclarations().filter(t=>rr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),sv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),nv=(e,t)=>{const s=Vn(e,"defineWorkflowEvent",rr),n=tv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of x(e,d.CallExpression)){if(!sv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?tt(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new L("WORKFLOW_EVENT_NOT_LITERAL",ae(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:w(t,e.getFilePath()),type:l.getLiteralValue()})}return i},iv=(e,t)=>{const s=y(t).flatMap(i=>nv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new L("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Te=(e,t)=>{z(e)&&Xe(e,"utf8")===t||Sr(e,t,"utf8")},rv=(e,t)=>{if(t===""){Ne(e,{force:!0});return}Te(e,t)},ov=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Ne(s,{force:!0,recursive:!0});return}if(z(s))for(const n of Rn(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[Fn(e,i)]===void 0&&Ne(i)}for(const[n,i]of Object.entries(t))qt(jt(E(e,n)),{recursive:!0}),Te(E(e,n),i)},av=(e,t,s)=>{const n=E(e,t);if(Object.keys(s).length===0){Ne(n,{force:!0,recursive:!0});return}if(z(n))for(const i of Rn(n,{recursive:!0,withFileTypes:!0})){const o=E(i.parentPath,i.name);i.isFile()&&s[Fn(n,o)]===void 0&&Ne(o)}for(const[i,o]of Object.entries(s)){const a=E(n,i);qt(jt(a),{recursive:!0}),Te(a,o)}},cv=e=>{try{const t=ua(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ue=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},lv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,dv=(e,t)=>{z(e)||qt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Te(E(e,n.name),n.content),s.push(n.name);break}case"directory":{av(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{ov(e,n.files),s.push(...Object.keys(n.files));break}default:rv(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},uv=e=>{const t=cv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=ga({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ma({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
29
  `,openApiModuleContent:pa(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
- `,openRpcModuleContent:ha(i)}},fv=".lunora-schema.json",gv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},pv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new L("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new L("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},mv=8,hv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:v}=e,B=()=>Zo(()=>{const D=ea(l,a,{lazyFunctions:o}),R=Xr(l,a);return{functions:D,httpRoutes:ta(l,a),mutators:R}});let{erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B();Sn([...N,...G].map(D=>D.filePath)),Sn(V.filter(D=>D.stream).map(D=>D.filePath),"http-stream");for(let D=1;;D+=1){const R=u?N:N.filter(P=>P.channel?.kind!=="room"&&P.lifecycle!=="socket"),O=Na({agents:t,functions:R,httpRoutes:V,mutators:G,useUmbrella:m,workflows:v}),W={agents:t,functions:R,lazyFunctions:o,migrations:c,mutators:G,shapes:f,useUmbrella:m,usesSandbox:g},J=Fa(W),se=La(W),ne=Pa({functions:N,useUmbrella:m}),ce=E(a,"_generated",ei),$=[[s,O],[i,ne],[n,J],...Object.entries(se).map(([P,k])=>[E(ce,P),k])];if(D>=mv||$.every(([P,k])=>lv(l,P,k)))return{apiContent:O,erased:fe,functions:N,functionModulesContent:se,functionsContent:J,httpRoutes:V,internalContent:ne,mutators:G};for(const[P,k]of $)Ue(l,P,k);({erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B())}},vv=e=>{const t=gv(),s=t?xt.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!z(o))throw new L("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??So(n);Wr(Dm);const c=oa(a,o,e.projectRoot);Ph(c.tables,yh(a,n,Xn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:B,env:fe,featureUsage:N,hasFlags:V,hasNotify:G,identity:D,platformGate:R,queues:O,serverContent:W,services:J,storageRulesMetadata:se,topics:ne,usesSandbox:ce,useUmbrella:$,workflows:P}=vm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Km(c,c.jurisdiction===void 0?void 0:_m(a,n));const k=E(n,"_generated"),Ce=E(k,"dataModel.ts"),_=E(k,"server.ts"),or=E(k,"api.ts"),ar=E(k,"internal.ts"),cr=E(k,"functions.ts");Ue(a,Ce,m),Ue(a,_,W);const gs=Object.fromEntries(J.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(jo(p,k))));for(const[p,Et]of Object.entries(gs))Ue(a,E(k,p),Et);const Oe=na(a,n),ge=aa(a,n),ct=R.signals.typedWebSockets!==!1,{apiContent:ps,erased:lr,functions:Z,functionModulesContent:ms,functionsContent:hs,httpRoutes:lt,internalContent:vs,mutators:dt}=hv({agents:l,apiPath:or,generatedFunctionsPath:cr,internalPath:ar,lazyFunctions:i,roomsSupported:ct,lunoraDirectory:n,migrations:Oe,project:a,shapes:ge,useUmbrella:$,usesSandbox:ce,workflows:P}),Es=lo(a,n),ut=uo(Es,c,[...Z,...lt].map(p=>p.filePath)),ke=Es.length>0,Re=e.lint===!1&&!ke?void 0:{callEdges:Om(a,n),inserts:sa(a,n),queries:ia(a,n,Z),tableWrites:Lh(a,n),workflowCalls:ev(a,n)},Fe=e.lint===!1||Re===void 0?void 0:vp(a,n,{callSites:Re,containers:f,crons:g,functions:Z,modules:ut,mutators:dt,queues:O,schema:c,shapes:ge,workflows:P,wranglerVariables:e.wranglerVariables}),xs=Fe===void 0?[]:Np(e.projectRoot,[...Ar(Fe,{source:"static"}),...Xh(a,n,{byName:new Set([...P,...O,...l,...f].map(p=>p.exportName)),byPath:new Set([...Z,...dt,...ge,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...zh(a,n),...Jo(lr,n),...va(O,e.wranglerQueueProducers)]),dr=ra(a,n),Ss=eh(a,n);pv(ge,Ss,Jm(a,n));const ur=V?Lm(a,n):[],ft=R.signals.vectorStore!==!1,fr=Vo(Rt(e.projectRoot,e.target),"deliveryAuthorization"),ve=wh(N,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:nh(c.tables),queueCount:O.length,storageColumnCount:Object.keys(Jn(c)).length,storageRuleCount:se.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Rt(e.projectRoot,e.target),vectorStoreSupported:ft,workflowCount:P.length}),As=t?xt.now():0,gt=fa(c,Oe.map(p=>p.id)),pt=Ym(a,n),ys=Wo({advisories:xs.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Fe?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:fe,flagKeys:ur,hasFlags:V,hasNotify:G,hasRooms:ct&&Z.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||Z.some(p=>xo(p)),hasSecretValues:R.signals.secretValues===!0,hasSockets:ct&&Z.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:ft,liveStreamDeclarations:pt,liveStreams:R.signals.liveStreams===!0,maskMetadata:Ss,mutators:dt,queues:O,rlsMetadata:dr,schema:c,schemaSnapshot:gt,shapes:ge,services:J,storageRules:se,studioFeatures:ve,topics:ne,useUmbrella:$,workflowEvents:iv(a,n),workflows:P}),bs=ya(ge,v.has("@lunora/db"),$),Ns=Ea(f,c.jurisdiction),Ps=xa(P),ws=Sa(l),Is=Aa(O,e.wranglerQueueProducers),Ts=Da(pt,$),Cs=wa(g),gr=Ia(ve.scheduler),pr=Ta(c.tables,$,c.jurisdiction),mr=co(e.projectRoot)?Ca($):"",Os=Oa(c.vectorIndexes),Le=Ra(c,$),ks=ba(v.has("@lunora/seed")),De=e.apiSpec??"openapi",mt=De==="openapi"||De==="both",ht=De==="openrpc"||De==="both",Rs=la(v.has("@lunora/auth")),Fs=da({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAuth:v.has("@lunora/auth"),hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue")||z(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Yn(p)),hasHyperdriveGlobal:c.tables.some(p=>Qn(p)),hasKvIntrospector:ve.kv,hasNotify:G,hasQueue:O.some(p=>p.mode==="push"),liveStreams:R.signals.liveStreams===!0,liveStreamsWithheld:R.liveStreamsWithheld,liveStreamDeclarations:pt,hasScheduler:ve.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:ve.storage,hasDeliveryAuthorization:fr,hasVectors:ft,hasWorkflow:P.length>0,identity:D,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:$,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:mt,wantsOpenRpc:ht}),{openApiContent:Ls,openApiModuleContent:Ds,openRpcContent:Ms,openRpcModuleContent:_s}=uv({functions:Z,httpRoutes:lt,modules:ut,projectRoot:e.projectRoot,wantsArchitecture:ke}),Ee=ke&&Re!==void 0?Kp({...Re,crons:g,functions:Z,httpRoutes:lt,modules:ut,queues:O,schema:c,services:J,topics:ne,workflows:P}):void 0,vt=E(n,fv),hr=z(vt),vr=e.dryRun?[]:dv(k,[{content:Fs,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ps,kind:"always",name:"api.ts"},{content:vs,kind:"always",name:"internal.ts"},{content:W,kind:"always",name:"server.ts"},{content:hs,kind:"always",name:"functions.ts"},{files:ms,kind:"directory",name:ei},{content:ys,kind:"always",name:"shard.ts"},{content:Cs,kind:"always",name:"crons.ts"},{content:Os,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ns,kind:"optional",name:"containers.ts"},{content:Ps,kind:"optional",name:"workflows.ts"},{content:ws,kind:"optional",name:"agents.ts"},{content:Is,kind:"optional",name:"queues.ts"},{content:Ts,kind:"optional",name:"live.ts"},{content:gr,kind:"optional",name:"scheduler.ts"},{content:pr,kind:"optional",name:"shardRegistry.ts"},{content:mr,kind:"optional",name:"durableObjects.ts"},{content:ks,kind:"optional",name:"seed.ts"},{content:Rs,kind:"optional",name:"authModule.ts"},{content:bs,kind:"optional",name:"collections.ts"},{files:gs,kind:"services"},{content:mt?Ls:"",kind:"optional",name:"openapi.json"},{content:mt?Ds:"",kind:"optional",name:"openapi.ts"},{content:ht?Ms:"",kind:"optional",name:"openrpc.json"},{content:ht?_s:"",kind:"optional",name:"openrpc.ts"},{content:Ee===void 0?"":`${JSON.stringify(Ee,void 0,2)}
30
+ `,openRpcModuleContent:ha(i)}},fv=".lunora-schema.json",gv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},pv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new L("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new L("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},mv=8,hv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:v}=e,B=()=>Zo(()=>{const D=ea(l,a,{lazyFunctions:o}),R=Xr(l,a);return{functions:D,httpRoutes:ta(l,a),mutators:R}});let{erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B();Sn([...N,...G].map(D=>D.filePath)),Sn(V.filter(D=>D.stream).map(D=>D.filePath),"http-stream");for(let D=1;;D+=1){const R=u?N:N.filter(P=>P.channel?.kind!=="room"&&P.lifecycle!=="socket"),O=Na({agents:t,functions:R,httpRoutes:V,mutators:G,useUmbrella:m,workflows:v}),W={agents:t,functions:R,lazyFunctions:o,migrations:c,mutators:G,shapes:f,useUmbrella:m,usesSandbox:g},J=Fa(W),se=La(W),ne=Pa({functions:N,useUmbrella:m}),ce=E(a,"_generated",ei),$=[[s,O],[i,ne],[n,J],...Object.entries(se).map(([P,k])=>[E(ce,P),k])];if(D>=mv||$.every(([P,k])=>lv(l,P,k)))return{apiContent:O,erased:fe,functions:N,functionModulesContent:se,functionsContent:J,httpRoutes:V,internalContent:ne,mutators:G};for(const[P,k]of $)Ue(l,P,k);({erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B())}},vv=e=>{const t=gv(),s=t?xt.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!z(o))throw new L("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??So(n);Wr(Dm);const c=oa(a,o,e.projectRoot);Ph(c.tables,yh(a,n,Xn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:B,env:fe,featureUsage:N,hasFlags:V,hasNotify:G,identity:D,platformGate:R,queues:O,serverContent:W,services:J,storageRulesMetadata:se,topics:ne,usesSandbox:ce,useUmbrella:$,workflows:P}=vm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Km(c,c.jurisdiction===void 0?void 0:_m(a,n));const k=E(n,"_generated"),Ce=E(k,"dataModel.ts"),_=E(k,"server.ts"),or=E(k,"api.ts"),ar=E(k,"internal.ts"),cr=E(k,"functions.ts");Ue(a,Ce,m),Ue(a,_,W);const gs=Object.fromEntries(J.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(jo(p,k))));for(const[p,Et]of Object.entries(gs))Ue(a,E(k,p),Et);const Oe=na(a,n),ge=aa(a,n),ct=R.signals.typedWebSockets!==!1,{apiContent:ps,erased:lr,functions:Z,functionModulesContent:ms,functionsContent:hs,httpRoutes:lt,internalContent:vs,mutators:dt}=hv({agents:l,apiPath:or,generatedFunctionsPath:cr,internalPath:ar,lazyFunctions:i,roomsSupported:ct,lunoraDirectory:n,migrations:Oe,project:a,shapes:ge,useUmbrella:$,usesSandbox:ce,workflows:P}),Es=lo(a,n),ut=uo(Es,c,[...Z,...lt].map(p=>p.filePath)),ke=Es.length>0,Re=e.lint===!1&&!ke?void 0:{callEdges:Om(a,n),inserts:sa(a,n),queries:ia(a,n,Z),tableWrites:Lh(a,n),workflowCalls:ev(a,n)},Fe=e.lint===!1||Re===void 0?void 0:vp(a,n,{callSites:Re,containers:f,crons:g,functions:Z,modules:ut,mutators:dt,queues:O,schema:c,shapes:ge,workflows:P,wranglerVariables:e.wranglerVariables}),xs=Fe===void 0?[]:Np(e.projectRoot,[...Ar(Fe,{source:"static"}),...Xh(a,n,{byName:new Set([...P,...O,...l,...f].map(p=>p.exportName)),byPath:new Set([...Z,...dt,...ge,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...zh(a,n),...Jo(lr,n),...va(O,e.wranglerQueueProducers)]),dr=ra(a,n),Ss=eh(a,n);pv(ge,Ss,Jm(a,n));const ur=V?Lm(a,n):[],ft=R.signals.vectorStore!==!1,fr=Vo(Rt(e.projectRoot,e.target),"deliveryAuthorization"),ve=wh(N,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:nh(c.tables),queueCount:O.length,storageColumnCount:Object.keys(Jn(c)).length,storageRuleCount:se.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Rt(e.projectRoot,e.target),vectorStoreSupported:ft,workflowCount:P.length}),As=t?xt.now():0,gt=fa(c,Oe.map(p=>p.id)),pt=Ym(a,n),ys=Wo({advisories:xs.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Fe?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:fe,flagKeys:ur,hasFlags:V,hasNotify:G,hasRooms:ct&&Z.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||Z.some(p=>xo(p)),hasSecretValues:R.signals.secretValues===!0,hasSockets:ct&&Z.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:ft,liveStreamDeclarations:pt,liveStreams:R.signals.liveStreams===!0,maskMetadata:Ss,mutators:dt,queues:O,rlsMetadata:dr,schema:c,schemaSnapshot:gt,shapes:ge,services:J,storageRules:se,studioFeatures:ve,topics:ne,useUmbrella:$,workflowEvents:iv(a,n),workflows:P}),bs=ya(ge,v.has("@lunora/db"),$),Ns=Ea(f,c.jurisdiction),Ps=xa(P,{lazy:i}),ws=Sa(l,{lazy:i}),Is=Aa(O,e.wranglerQueueProducers),Ts=Da(pt,$),Cs=wa(g),gr=Ia(ve.scheduler),pr=Ta(c.tables,$,c.jurisdiction),mr=co(e.projectRoot)?Ca($):"",Os=Oa(c.vectorIndexes),Le=Ra(c,$),ks=ba(v.has("@lunora/seed")),De=e.apiSpec??"openapi",mt=De==="openapi"||De==="both",ht=De==="openrpc"||De==="both",Rs=la(v.has("@lunora/auth")),Fs=da({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAuth:v.has("@lunora/auth"),hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue")||z(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Yn(p)),hasHyperdriveGlobal:c.tables.some(p=>Qn(p)),hasKvIntrospector:ve.kv,hasNotify:G,hasQueue:O.some(p=>p.mode==="push"),liveStreams:R.signals.liveStreams===!0,liveStreamsWithheld:R.liveStreamsWithheld,liveStreamDeclarations:pt,hasScheduler:ve.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:ve.storage,hasDeliveryAuthorization:fr,hasVectors:ft,hasWorkflow:P.length>0,identity:D,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,lazyFunctions:i,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:$,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:mt,wantsOpenRpc:ht}),{openApiContent:Ls,openApiModuleContent:Ds,openRpcContent:Ms,openRpcModuleContent:_s}=uv({functions:Z,httpRoutes:lt,modules:ut,projectRoot:e.projectRoot,wantsArchitecture:ke}),Ee=ke&&Re!==void 0?Kp({...Re,crons:g,functions:Z,httpRoutes:lt,modules:ut,queues:O,schema:c,services:J,topics:ne,workflows:P}):void 0,vt=E(n,fv),hr=z(vt),vr=e.dryRun?[]:dv(k,[{content:Fs,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ps,kind:"always",name:"api.ts"},{content:vs,kind:"always",name:"internal.ts"},{content:W,kind:"always",name:"server.ts"},{content:hs,kind:"always",name:"functions.ts"},{files:ms,kind:"directory",name:ei},{content:ys,kind:"always",name:"shard.ts"},{content:Cs,kind:"always",name:"crons.ts"},{content:Os,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ns,kind:"optional",name:"containers.ts"},{content:Ps,kind:"optional",name:"workflows.ts"},{content:ws,kind:"optional",name:"agents.ts"},{content:Is,kind:"optional",name:"queues.ts"},{content:Ts,kind:"optional",name:"live.ts"},{content:gr,kind:"optional",name:"scheduler.ts"},{content:pr,kind:"optional",name:"shardRegistry.ts"},{content:mr,kind:"optional",name:"durableObjects.ts"},{content:ks,kind:"optional",name:"seed.ts"},{content:Rs,kind:"optional",name:"authModule.ts"},{content:bs,kind:"optional",name:"collections.ts"},{files:gs,kind:"services"},{content:mt?Ls:"",kind:"optional",name:"openapi.json"},{content:mt?Ds:"",kind:"optional",name:"openapi.ts"},{content:ht?Ms:"",kind:"optional",name:"openrpc.json"},{content:ht?_s:"",kind:"optional",name:"openrpc.ts"},{content:Ee===void 0?"":`${JSON.stringify(Ee,void 0,2)}
31
31
  `,kind:"optional",name:"architecture.json"},{content:Ee===void 0?"":$p(Ee),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!hr||e.updateSchemaBaseline===!0)&&Te(vt,yr(gt)),t){const p=xt.now(),Et=Math.round(p-s),Er=Math.round(As-s),xr=Math.round(p-As);console.error(`@lunora/codegen: codegen took ${Et.toString()}ms (discovery ${Er.toString()}ms, emit ${xr.toString()}ms)`)}return{advisories:xs,advisorContext:Fe,agents:l,architecture:Ee,containers:f,cronTriggers:[...new Set([...ka(g),...B])],generated:{agents:ws,api:ps,app:Fs,authModule:Rs,collections:bs,containers:Ns,crons:Cs,dataModel:m,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:ms,functions:hs,internal:vs,live:Ts,openApi:Ls,openApiModule:Ds,openRpc:Ms,openRpcModule:_s,queues:Is,seed:ks,server:W,shard:ys,vectors:Os,workflows:Ps},migrations:Oe,outputDirectory:k,platformDiagnostics:R.diagnostics,queues:O,schemaSnapshot:gt,schemaSnapshotPath:vt,workflows:P,writtenFiles:vr}},DE=e=>Or(()=>vv(e));export{fv as SCHEMA_SNAPSHOT_FILENAME,So as createCodegenProject,zE as findTsconfig,KE as refreshCodegenProject,DE as runCodegen,$E as tsconfigFingerprint};
@@ -1 +1 @@
1
- import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-BtEGoPTf.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
1
+ import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-Bg8MOBzw.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
@@ -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-BErjtci3.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
  *
@@ -339,12 +339,12 @@ const buildGlobalCdcApplier =
339
339
 
340
340
  return request.changes.length;
341
341
  };
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} */
342
+ `:"",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
343
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
344
344
  this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
345
345
 
346
346
  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. */
347
+ }`),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
348
  public admin(selector: Selector<Env, string>): this {
349
349
  this.adminToken = selector;
350
350
 
@@ -408,7 +408,7 @@ const buildGlobalCdcApplier =
408
408
  this.storageDeclaration = declaration;
409
409
 
410
410
  return this;
411
- }`]:[],...H(e)],F=e=>{const r=a=>e.hasScheduler?`
411
+ }`]:[],..._(e)],H=e=>{const r=a=>e.hasScheduler?`
412
412
  ...(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
413
  ? {
414
414
  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 +516,13 @@ const buildGlobalCdcApplier =
516
516
  ? {
517
517
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
518
518
  }
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?`
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) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
520
520
  ${t.join(`
521
521
  `)}
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?`
522
+ `:""},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
523
  // 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(`
524
+ 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>([
525
+ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`).join(`
526
526
  `)}
527
527
  ]);
528
528
 
@@ -531,10 +531,10 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${ae(r.shardMode)}],`
531
531
 
532
532
  if (shardRegistry) {
533
533
  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(`
534
+ }`]:[]],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([
535
+ ${S(e).join(`
536
536
  `)}
537
- ], host)`:"host",le=e=>[...ne(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
537
+ ], host)`:"host",oe=e=>[...re(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
538
538
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
539
539
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
540
540
  const source = workflowEnv as Record<string, unknown>;
@@ -658,7 +658,7 @@ ${D(e).join(`
658
658
  // Memoised on the declaration: each worker built for a new \`env\` runs
659
659
  // these options again, and \`options(env)\` rebuilds every plugin.
660
660
  discoveryPaths,
661
- internalSecret,${re(e)}
661
+ internalSecret,${ee(e)}
662
662
  namespace,
663
663
  ...(objectName === undefined ? {} : { objectName }),
664
664
  });
@@ -800,10 +800,10 @@ ${D(e).join(`
800
800
  }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
801
801
  ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
802
802
  `)}
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>,"," 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?`
803
+ };`]:[]],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
804
  /** The identity memo per \`env\` object, owned by one assembled worker. */
805
805
  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`
806
+ `:"",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
807
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
808
808
  interface DeferredModules {
809
809
  ${t.map(([a,n])=>` ${a}: ${n};`).join(`
@@ -820,13 +820,32 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
820
820
  `)}
821
821
  };
822
822
  })());
823
- `},ue=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
823
+ `},he=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
824
824
  await ensureAuth(env);`:"",n=e?`
825
825
  await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"target",eventWorkerLine:`
826
826
  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;
827
+ worker ??= ${t};`}},ue=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
828
+ 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";
829
+ `:"",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(`
830
+ `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
831
+ ${t(" ")}
832
+ ]);
833
+
834
+ `:` let agentEmail: ReturnType<typeof dispatchAgentEmail> | undefined;
835
+
836
+ composed.email = async (message, rawEnv, context) => {
837
+ if (agentEmail === undefined) {
838
+ const [{ dispatchAgentEmail: dispatch }, lunoraAgentDefinitions] = await Promise.all([import("@lunora/agent/inbound"), import("../agents.js")]);
839
+
840
+ agentEmail ??= dispatch([
841
+ ${t(" ")}
842
+ ]);
843
+ }
844
+
845
+ return agentEmail(message, rawEnv, context);
846
+ };
847
+
848
+ `},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
849
  let authInit: Promise<void> | null = null;
831
850
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
832
851
  // \`assemble()\` has its own auth closure and must not share.
@@ -897,16 +916,11 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
897
916
  return false;
898
917
  },
899
918
  );
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. */
919
+ `:"",{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 =>
920
+ 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
921
  public build(): ComposedApp {
908
922
  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(`
923
+ }${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
924
  `)}
911
925
 
912
926
  /** 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 +928,7 @@ type Selector<Env, T> = (env: Env) => T | undefined;
914
928
 
915
929
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
916
930
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
917
- ${de(a)}${he(t)}${t.jurisdiction?`
931
+ ${ce(a)}${de(t)}${t.jurisdiction?`
918
932
  // Module scope, so every isolate loading this script (the worker and each Durable
919
933
  // Object class it exports) knows the schema's jurisdiction before a request runs.
920
934
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
@@ -939,32 +953,32 @@ interface ComposedApp extends LunoraWorker {
939
953
  * first request so per-isolate singletons are built once.
940
954
  */
941
955
  class AppBuilder<Env extends object> {
942
- ${_(t).join(`
956
+ ${B(t).join(`
943
957
  `)}
944
958
 
945
959
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
946
960
 
947
- ${U(t).join(`
961
+ ${W(t).join(`
948
962
 
949
963
  `)}
950
964
 
951
- ${I}
965
+ ${T}
952
966
 
953
967
  /** 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)}});
968
+ private assemble(${C}): ComposedApp {
969
+ const ShardDO = createShardDO({${H(t)}});
956
970
 
957
971
  // Per-isolate singletons: the worker (and auth instance) are expensive to
958
972
  // build, so the first request constructs them and every later request on
959
973
  // the same isolate reuses them.
960
974
  let worker: LunoraWorker | null = null;
961
975
  ${i}${d}
962
- ${O}
976
+ ${x}
963
977
 
964
978
  const composed: ComposedApp = {
965
979
  ShardDO,
966
980
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
967
- const env = rawEnv as Env;${h}${A}
981
+ const env = rawEnv as Env;${h}${D}
968
982
  worker ??= buildWorker(env${o});
969
983
 
970
984
  return worker.fetch(request, rawEnv, context);
@@ -973,7 +987,7 @@ ${O}
973
987
 
974
988
  return ${b}.scheduled(controller, rawEnv, context);
975
989
  },
976
- serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${x}
990
+ serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${R}
977
991
  worker ??= buildWorker(rawEnv as Env${o});
978
992
 
979
993
  return worker.serverQuery(request, rawEnv, reference, args, options);
@@ -984,7 +998,7 @@ ${O}
984
998
  },`:""}
985
999
  };
986
1000
 
987
- ${q} if (this.emailHandler) {
1001
+ ${O} if (this.emailHandler) {
988
1002
  const handler = this.emailHandler;
989
1003
 
990
1004
  composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
@@ -1003,11 +1017,11 @@ ${t.hasFramework?`
1003
1017
  `:""}
1004
1018
  return composed;
1005
1019
  }
1006
- ${P(t)}${M(t.hasStorage)}
1020
+ ${$(t)}${G(t.hasStorage)}
1007
1021
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1008
- private buildWorkerOptions(env: Env, ${C}): WorkerOptions {
1022
+ private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
1009
1023
  const options: WorkerOptions = {
1010
- ${ce(t).join(`
1024
+ ${le(t).join(`
1011
1025
  `)}
1012
1026
  };
1013
1027
 
@@ -1028,7 +1042,7 @@ ${s.join(`
1028
1042
  return options;
1029
1043
  }
1030
1044
  }
1031
- ${B(t.hasGlobal)}
1045
+ ${P(t.hasGlobal)}
1032
1046
  /**
1033
1047
  * Shape of the project's root \`lunora.config.*\`.
1034
1048
  *
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DmDBaK79.mjs";import"./shard-runtime-BtEGoPTf.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DNXF9VZ5.mjs";import"./shard-runtime-Bg8MOBzw.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -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-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-Bg8MOBzw.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=` /**
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
@@ -1,4 +1,4 @@
1
- import{LunoraError as N}from"@lunora/errors";import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as k}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{a as l,G as g,I as R}from"./shared-BErjtci3.mjs";import{s as w}from"./platform-8oj7iXQy.mjs";const U=e=>e?{importFragment:"serveRelationFanout, ",override:`
1
+ import{LunoraError as k}from"@lunora/errors";import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as R}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{a as l,G as f,I as w}from"./shared-BErjtci3.mjs";import{s as S}from"./platform-8oj7iXQy.mjs";const Q=e=>e?{importFragment:"serveRelationFanout, ",override:`
2
2
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
3
3
  this.ensureServable();
4
4
 
@@ -6,14 +6,14 @@ import{LunoraError as N}from"@lunora/errors";import{r as b}from"./json-data-Chfs
6
6
 
7
7
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
8
  }
9
- `}:{importFragment:"",override:""},f=(e,r,t,{cast:n="",sync:a=[]}={})=>{const u=`throw new Error(${JSON.stringify(r)});`,c=t.map(s=>` ${s}: ${a===!0||a.includes(s)?"":"async "}() => {
10
- ${u}
9
+ `}:{importFragment:"",override:""},y=(e,r,t,{cast:n="",sync:s=[]}={})=>{const i=`throw new Error(${JSON.stringify(r)});`,c=t.map(u=>` ${u}: ${s===!0||s.includes(u)?"":"async "}() => {
10
+ ${i}
11
11
  },`).join(`
12
12
  `);return`
13
13
  const ${e} = {
14
14
  ${c}
15
15
  }${n};
16
- `},h={build:"",configField:"",contextField:"",importLines:[],stub:""},Q=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
16
+ `},x={build:"",configField:"",contextField:"",importLines:[],stub:""},M=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
17
17
  /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
18
18
  const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.stringify(r)).join(", ")}]);
19
19
  `,override:`
@@ -22,26 +22,26 @@ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.string
22
22
 
23
23
  return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
24
24
  }
25
- `},M=(e,r)=>e?{build:`
25
+ `},K=(e,r)=>e?{build:`
26
26
  const flags: import("${r}").LunoraFlags = createFlags(flagsConfig, env, {
27
27
  provider: () => config.flags?.(env),
28
28
  targetingKey: () => flagsConfig.identify?.({ identity: readIdentity() ?? null, userId: readUserId() ?? null }),
29
29
  });
30
30
  `,configField:`
31
31
  flags?: (env: Record<string, unknown>) => import("${r}").Provider;`,contextField:`
32
- flags,`,importLines:[`import { createFlags } from "${r}";`,'import flagsConfig from "../flags.js";'],stub:""}:h,K=e=>e?{build:`
32
+ flags,`,importLines:[`import { createFlags } from "${r}";`,'import flagsConfig from "../flags.js";'],stub:""}:x,H=e=>e?{build:`
33
33
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
34
34
  `,configField:"",contextField:`
35
35
  notify,
36
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:h,H=e=>e?{build:`
36
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:x,G=e=>e?{build:`
37
37
  const envConfig = lunoraEnvContract.${e.exportName}(env);
38
38
  `,configField:"",contextField:`
39
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:h,G=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=o=>`
39
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:x,V=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=a=>`
40
40
  const env = (this.env ?? {}) as Record<string, unknown>;
41
41
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
42
42
  provider: () => config.flags?.(env),
43
- targetingKey: ${o},
44
- });`,a=`
43
+ targetingKey: ${a},
44
+ });`,s=`
45
45
  /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
46
46
  const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
47
47
  `,c=`
@@ -66,7 +66,7 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
66
66
 
67
67
  return { configured: true, flags: evaluations };
68
68
  }
69
- `,s=`
69
+ `,u=`
70
70
  protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<unknown> {${n("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
71
71
  const key = typeof args.key === "string" ? args.key : "";
72
72
 
@@ -99,7 +99,7 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
99
99
 
100
100
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
101
101
  }
102
- `;return{constant:a,evaluateOverride:c,subscriptionOverride:s}},S=()=>({build:`
102
+ `;return{constant:s,evaluateOverride:c,subscriptionOverride:u}},L=()=>({build:`
103
103
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
104
104
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
105
105
  // function path + trace id into createAi, which folds them into the
@@ -116,9 +116,9 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
116
116
  telemetry: { metrics, trace },
117
117
  });
118
118
  `,configField:`
119
- ai?: (env: Record<string, unknown>) => AiBindingLike;`,importLines:['import type { AiBindingLike, LunoraAi } from "@lunora/ai/create";','import { createAi } from "@lunora/ai/create";'],stub:""}),L=()=>({build:`
119
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,importLines:['import type { AiBindingLike, LunoraAi } from "@lunora/ai/create";','import { createAi } from "@lunora/ai/create";'],stub:""}),A=()=>({build:`
120
120
  const access = lazyAccessFacade(readIdentity, readUserId);
121
- `,configField:"",importLines:['import { lazyAccessFacade } from "@lunora/cloudflare-access/context";'],stub:""}),A=()=>({build:`
121
+ `,configField:"",importLines:['import { lazyAccessFacade } from "@lunora/cloudflare-access/context";'],stub:""}),_=()=>({build:`
122
122
  const r2sqlEnv = env as Record<string, unknown>;
123
123
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
124
124
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -129,36 +129,36 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
129
129
  ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
130
130
  : r2sqlStub;
131
131
  `,configField:`
132
- r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:f("r2sqlStub: R2SqlClient","ctx.r2sql: no R2 SQL credentials found. Set `R2_SQL_TOKEN`, `R2_SQL_ACCOUNT_ID` (or `CLOUDFLARE_ACCOUNT_ID`), and `R2_SQL_BUCKET` in your env/.dev.vars, or pass an `r2sql` config thunk to createShardDO().",["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}),_=()=>({build:`
132
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:y("r2sqlStub: R2SqlClient","ctx.r2sql: no R2 SQL credentials found. Set `R2_SQL_TOKEN`, `R2_SQL_ACCOUNT_ID` (or `CLOUDFLARE_ACCOUNT_ID`), and `R2_SQL_BUCKET` in your env/.dev.vars, or pass an `r2sql` config thunk to createShardDO().",["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}),C=()=>({build:`
133
133
  const x402: X402Pay = config.x402
134
134
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
135
135
  : x402Stub;
136
136
  `,configField:`
137
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:f("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),C={access:L,ai:S,r2sql:A,x402:_},F=e=>e.shardBinding==="bespoke",E=e=>typeof e.shardBinding=="object",m=" ",O=(e,r,t)=>{const n=`${e}Binding`,{factory:a}=t;let u=`(${n} as ${r})`;if(a!==void 0){const c=`${n} as ${t.bindingType??r}`;u=a.option===void 0?`${a.name}(${c})`:`${a.name}({ ${a.option}: ${c} })`}return`${n} ? ${u} : ${e}Stub`},P=(e,r,t)=>{const n=O(e,r,t),a=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
138
- `,u=t.unvouchableReads??[];return u.length===0?`
139
- ${a}${m}const ${e}: ${r} = ${n};
137
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:y("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),F={access:A,ai:L,r2sql:_,x402:C},E=e=>e.shardBinding==="bespoke",O=e=>typeof e.shardBinding=="object",m=" ",P=(e,r,t)=>{const n=`${e}Binding`,{factory:s}=t;let i=`(${n} as ${r})`;if(s!==void 0){const c=`${n} as ${t.bindingType??r}`;i=s.option===void 0?`${s.name}(${c})`:`${s.name}({ ${s.option}: ${c} })`}return`${n} ? ${i} : ${e}Stub`},q=(e,r,t)=>{const n=P(e,r,t),s=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
138
+ `,i=t.unvouchableReads??[];return i.length===0?`
139
+ ${s}${m}const ${e}: ${r} = ${n};
140
140
  `:`
141
- ${a}${m}// ${t.envName} is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
141
+ ${s}${m}// ${t.envName} is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
142
142
  ${m}// when a value changes — a subscription that read one can never be proven
143
143
  ${m}// current on reconnect and must re-snapshot. Reads only; writes stay unstamped.
144
144
  ${m}const ${e}: ${r} = markUnvouchableReads(${n}, options.onRead, [
145
- ${u.map(c=>`${m} ${JSON.stringify(c)},`).join(`
145
+ ${i.map(c=>`${m} ${JSON.stringify(c)},`).join(`
146
146
  `)}
147
147
  ${m}]);
148
- `},q=(e,r,t)=>{const{binding:n,clientType:a}=t,u=f(`${e}Stub: ${a}`,t.missingMessage,t.stubMethods,{sync:t.syncStubMethods});if(n===void 0){const o=t.instrument===void 0?`config.${e}(env)`:`this.${t.instrument}(config.${e}(env), logFunctionPath, traceAnchor, observability)`;return{build:`
149
- ${m}const ${e}: ${a} = config.${e} ? ${o} : ${e}Stub;
148
+ `},W=(e,r,t)=>{const{binding:n,clientType:s}=t,i=y(`${e}Stub: ${s}`,t.missingMessage,t.stubMethods,{sync:t.syncStubMethods});if(n===void 0){const a=t.instrument===void 0?`config.${e}(env)`:`this.${t.instrument}(config.${e}(env), logFunctionPath, traceAnchor, observability)`;return{build:`
149
+ ${m}const ${e}: ${s} = config.${e} ? ${a} : ${e}Stub;
150
150
  `,configField:`
151
- ${e}?: (env: Record<string, unknown>) => ${a};`,importLines:[`import type { ${a} } from "${r}";`],stub:u}}const c=n.bindingType??a,s=[...new Set([c,a])].toSorted((o,i)=>o.localeCompare(i));return{build:P(e,a,n),configField:`
152
- ${e}?: (env: Record<string, unknown>) => ${c};`,importLines:[`import type { ${s.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:u}},V=e=>{const r=[],t=[];let n="",a="",u="",c="",s="";for(const o of k.filter(({key:i})=>e.has(i))){let i;if(F(o))i=C[o.key]();else if(E(o))i=q(o.contextProperty,o.moduleSpecifier,o.shardBinding);else continue;const d=o.contextProperty;t.push(...i.importLines),a+=i.configField,s+=i.stub,o.tier==="every"?(u+=i.build,c+=`
153
- ${d},`):(n+=i.build,r.push(d))}return{actionBuild:n,actionFields:r,configFields:a,everyBuild:u,everyFields:c,importLines:t,stubs:s}},J=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(i=>{l(i.exportName,`container export "${i.exportName}"`),l(i.className,`container class "${i.className}"`);const d=i.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${i.exportName}\` definition (binding \`${i.bindingName}\`). */
154
- export class ${i.className} extends ${d} {
151
+ ${e}?: (env: Record<string, unknown>) => ${s};`,importLines:[`import type { ${s} } from "${r}";`],stub:i}}const c=n.bindingType??s,u=[...new Set([c,s])].toSorted((a,o)=>a.localeCompare(o));return{build:q(e,s,n),configField:`
152
+ ${e}?: (env: Record<string, unknown>) => ${c};`,importLines:[`import type { ${u.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:i}},J=e=>{const r=[],t=[];let n="",s="",i="",c="",u="";for(const a of R.filter(({key:o})=>e.has(o))){let o;if(E(a))o=F[a.key]();else if(O(a))o=W(a.contextProperty,a.moduleSpecifier,a.shardBinding);else continue;const d=a.contextProperty;t.push(...o.importLines),s+=o.configField,u+=o.stub,a.tier==="every"?(i+=o.build,c+=`
153
+ ${d},`):(n+=o.build,r.push(d))}return{actionBuild:n,actionFields:r,configFields:s,everyBuild:i,everyFields:c,importLines:t,stubs:u}},Y=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(o=>{l(o.exportName,`container export "${o.exportName}"`),l(o.className,`container class "${o.className}"`);const d=o.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
154
+ export class ${o.className} extends ${d} {
155
155
  public constructor(ctx: ConstructorParameters<typeof ${d}>[0], env: Record<string, unknown>) {
156
- super(ctx, env, ${i.exportName}, "${i.exportName}"${t});
156
+ super(ctx, env, ${o.exportName}, "${o.exportName}"${t});
157
157
  }
158
158
  }
159
159
  `}).join(`
160
- `),a=e.map(i=>i.exportName).join(", "),u=e.some(i=>i.sandbox===!0),c=e.some(i=>i.sandbox!==!0)?`import { LunoraContainer } from "@lunora/container/do";
161
- `:"";return`${g}/**
160
+ `),s=e.map(o=>o.exportName).join(", "),i=e.some(o=>o.sandbox===!0),c=e.some(o=>o.sandbox!==!0)?`import { LunoraContainer } from "@lunora/container/do";
161
+ `:"";return`${f}/**
162
162
  * Container-enabled Durable Object classes for the containers declared in
163
163
  * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
164
164
  * requires each \`containers[].class_name\` to be exported by the worker:
@@ -170,19 +170,19 @@ export class ${i.className} extends ${d} {
170
170
  * \`handle.egress\` controls) routes container outbound traffic through this
171
171
  * WorkerEntrypoint, so it too must be exported by the deployed worker.
172
172
  */
173
- ${c}${u?`import { LunoraSandboxContainer } from "@lunora/container/sandbox";
173
+ ${c}${i?`import { LunoraSandboxContainer } from "@lunora/container/sandbox";
174
174
  `:""}
175
- import { ${a} } from "../containers.js";
175
+ import { ${s} } from "../containers.js";
176
176
 
177
177
  export { ContainerProxy } from "@lunora/container/do";
178
- ${u?`
178
+ ${i?`
179
179
  /**
180
180
  * \`DirectoryBackup\` and \`S3Mount\` route a \`sandbox: true\` container's storage
181
181
  * traffic through these WorkerEntrypoints, so the deployed worker must export them.
182
182
  */
183
183
  export { DirectoryBackupGateway, S3Gateway } from "@lunora/container/sandbox";
184
184
  `:""}
185
- ${n}`},Y=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`container export "${n.exportName}"`),l(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const a=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${a} },`}).join(`
185
+ ${n}`},z=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`container export "${n.exportName}"`),l(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const s=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${s} },`}).join(`
186
186
  `);return{build:`
187
187
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${r?JSON.stringify(r):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
188
188
  `,contextField:`
@@ -191,14 +191,14 @@ ${n}`},Y=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],
191
191
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
192
192
  ${t}
193
193
  ];
194
- `}},X=e=>{if(e.length===0)return"";const r=e.map(n=>(l(n.exportName,`workflow export "${n.exportName}"`),l(n.className,`workflow class "${n.className}"`),`/** WorkflowEntrypoint for the \`${n.exportName}\` definition, reached as \`ctx.exports.${n.className}\`. */
195
- export class ${n.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${n.exportName}>, WorkflowOutputOf<typeof ${n.exportName}>> {
194
+ `}},X=(e,r={})=>{if(e.length===0)return"";const t=r.lazy===!0,n=e.map(i=>{l(i.exportName,`workflow export "${i.exportName}"`),l(i.className,`workflow class "${i.className}"`);const c=t?`async () => (await import("../workflows.js")).${i.exportName}`:i.exportName;return`/** WorkflowEntrypoint for the \`${i.exportName}\` definition, reached as \`ctx.exports.${i.className}\`. */
195
+ export class ${i.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${i.exportName}>, WorkflowOutputOf<typeof ${i.exportName}>> {
196
196
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
197
- super(ctx, env, ${n.exportName}, "${n.exportName}");
197
+ super(ctx, env, ${c}, "${i.exportName}");
198
198
  }
199
199
  }
200
- `)).join(`
201
- `),t=e.map(n=>n.exportName).join(", ");return`${g}/**
200
+ `}).join(`
201
+ `),s=e.map(i=>i.exportName).join(", ");return`${f}/**
202
202
  * WorkflowEntrypoint classes for the workflows declared in
203
203
  * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
204
204
  * requires each \`workflows[].class_name\` to be exported by the worker:
@@ -207,7 +207,7 @@ export class ${n.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${n.e
207
207
  */
208
208
  import LunoraWorkflow from "@lunora/workflow/do";
209
209
 
210
- import { ${t} } from "../workflows.js";
210
+ import ${t?"type ":""}{ ${s} } from "../workflows.js";
211
211
 
212
212
  /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
213
213
  type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
@@ -219,37 +219,41 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
219
219
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
220
220
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
221
221
 
222
- ${r}`},z=e=>{if(e.length===0)return"";const t=e.filter(s=>s.voice).length>0,n=e.map(s=>{l(s.exportName,`agent export "${s.exportName}"`),l(s.className,`agent class "${s.className}"`);const o=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent, reached as \`ctx.exports.${s.className}\`. */
223
- export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
222
+ ${n}`},Z=(e,r={})=>{if(e.length===0)return"";const n=e.filter(o=>o.voice).length>0,s=r.lazy===!0&&!n,i=e.map(o=>{l(o.exportName,`agent export "${o.exportName}"`),l(o.className,`agent class "${o.className}"`);const d=`/** WorkflowEntrypoint for the \`${o.exportName}\` agent, reached as \`ctx.exports.${o.className}\`. */
223
+ export class ${o.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
224
224
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
225
- super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
225
+ super(ctx, env, ${s?`async () => {
226
+ const [{ compileAgentWorkflow }, { ${o.exportName}: definition }] = await Promise.all([import("@lunora/agent"), import("../agents.js")]);
227
+
228
+ return compileAgentWorkflow(definition, "${o.exportName}");
229
+ }`:`compileAgentWorkflow(${o.exportName}, "${o.exportName}")`}, "${o.exportName}");
226
230
  }
227
231
  }
228
- `;if(!s.voice)return o;const i=s.voiceClassName??"",d=s.voiceBindingName??"";l(i,`agent voice class "${i}"`);const p=`
229
- /** Voice-session Durable Object for the \`${s.exportName}\` agent (binding \`${d}\`). */
230
- export class ${i} extends VoiceSessionDO {
232
+ `;if(!o.voice)return d;const p=o.voiceClassName??"",g=o.voiceBindingName??"";l(p,`agent voice class "${p}"`);const N=`
233
+ /** Voice-session Durable Object for the \`${o.exportName}\` agent (binding \`${g}\`). */
234
+ export class ${p} extends VoiceSessionDO {
231
235
  public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
232
- super(ctx, env, ${s.exportName}, "${s.exportName}");
236
+ super(ctx, env, ${o.exportName}, "${o.exportName}");
233
237
  }
234
238
  }
235
- `;return`${o}${p}`}).join(`
236
- `),a=e.map(s=>s.exportName).join(", ");return`${g}/**
239
+ `;return`${d}${N}`}).join(`
240
+ `),c=e.map(o=>o.exportName).join(", ");let u='import { compileAgentWorkflow } from "@lunora/agent";';return n?u='import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':s&&(u=""),`${f}/**
237
241
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
238
242
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
239
243
  * Workflow. Re-export them from your worker entry — wrangler requires each
240
244
  * \`workflows[].class_name\` to be exported by the worker:
241
245
  *
242
- * \`export * from "./lunora/_generated/agents.js";\`${t?"\n *\n * Voice-enabled agents ALSO get a `VoiceSessionDO` subclass here — a real\n * Durable Object (unlike the Workflow), so wrangler needs both its\n * `durable_objects` binding and its `class_name` export (the same re-export\n * line covers it).":""}
246
+ * \`export * from "./lunora/_generated/agents.js";\`${n?"\n *\n * Voice-enabled agents ALSO get a `VoiceSessionDO` subclass here — a real\n * Durable Object (unlike the Workflow), so wrangler needs both its\n * `durable_objects` binding and its `class_name` export (the same re-export\n * line covers it).":""}
243
247
  */
244
248
  import LunoraWorkflow from "@lunora/workflow/do";
245
- ${t?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
246
- import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
247
-
248
- import { ${a} } from "../agents.js";
249
-
250
- ${n}`},y=e=>e.env===void 0?"the top level":`env.${e.env}`,v=(e,r)=>{const t=e.filter(o=>o.mode==="push"),n=new Map(t.map(o=>[o.bindingName,o])),a=new Map(e.map(o=>[o.name,o])),u=new Map(t.map(o=>[o.name,o])),c=new Map,s=[];for(const o of r){const i=n.get(o.binding);if(i===void 0||o.queue===i.name)continue;const d=a.get(o.queue);if(d!==void 0){s.push(`${y(o)} maps \`${o.binding}\` to "${o.queue}", the declared name of queue \`${d.exportName}\` — batches for "${o.queue}" go to \`${d.exportName}\`, never \`${i.exportName}\`.`);continue}const p=u.get(o.queue);if(p===void 0)u.set(o.queue,i),c.set(o.queue,o);else if(p!==i){const x=c.get(o.queue);s.push(`"${o.queue}" is aliased to \`${p.exportName}\` by ${x===void 0?"an earlier producer":y(x)} and to \`${i.exportName}\` by ${y(o)} — batches for it go to \`${p.exportName}\`.`)}}return{conflicts:s,routes:u}},Z=(e,r)=>v(e,r).conflicts.map(t=>({cacheKey:`queue_alias_conflict:${t}`,categories:["SCHEMA"],description:"Codegen routes a delivered batch by its queue name. A wrangler.jsonc producer that maps a queue's binding to another name adds that name as a route, so it must not be another queue's declared name or an alias another scope gives a different queue.",detail:t,facing:"INTERNAL",level:"WARN",metadata:{},name:"queue_alias_conflict",remediation:"Give each queue a distinct name in every `env.<name>` block of wrangler.jsonc, then rerun codegen.",title:"Queue name routes to a different handler than wrangler.jsonc implies"})),ee=(e,r=[])=>{const t=e.filter(c=>c.mode==="push");if(t.length===0)return"";for(const c of t)l(c.exportName,`queue export "${c.exportName}"`);const n=[...Map.groupBy(t,c=>c.filePath)].map(([c,s])=>`import { ${s.map(o=>o.exportName).join(", ")} } from "../${c}.js";`).join(`
251
- `),{routes:a}=v(e,r),u=[...a].map(([c,s])=>` ${JSON.stringify(c)}: { binding: ${JSON.stringify(s.bindingName)}, definition: ${s.exportName}, exportName: ${JSON.stringify(s.exportName)} },`).join(`
252
- `);return`${g}/**
249
+ ${u===""?"":`${u}
250
+ `}import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
251
+ ${s?"":`
252
+ import { ${c} } from "../agents.js";
253
+ `}
254
+ ${i}`},h=e=>e.env===void 0?"the top level":`env.${e.env}`,$=(e,r)=>{const t=e.filter(a=>a.mode==="push"),n=new Map(t.map(a=>[a.bindingName,a])),s=new Map(e.map(a=>[a.name,a])),i=new Map(t.map(a=>[a.name,a])),c=new Map,u=[];for(const a of r){const o=n.get(a.binding);if(o===void 0||a.queue===o.name)continue;const d=s.get(a.queue);if(d!==void 0){u.push(`${h(a)} maps \`${a.binding}\` to "${a.queue}", the declared name of queue \`${d.exportName}\` — batches for "${a.queue}" go to \`${d.exportName}\`, never \`${o.exportName}\`.`);continue}const p=i.get(a.queue);if(p===void 0)i.set(a.queue,o),c.set(a.queue,a);else if(p!==o){const g=c.get(a.queue);u.push(`"${a.queue}" is aliased to \`${p.exportName}\` by ${g===void 0?"an earlier producer":h(g)} and to \`${o.exportName}\` by ${h(a)} — batches for it go to \`${p.exportName}\`.`)}}return{conflicts:u,routes:i}},ee=(e,r)=>$(e,r).conflicts.map(t=>({cacheKey:`queue_alias_conflict:${t}`,categories:["SCHEMA"],description:"Codegen routes a delivered batch by its queue name. A wrangler.jsonc producer that maps a queue's binding to another name adds that name as a route, so it must not be another queue's declared name or an alias another scope gives a different queue.",detail:t,facing:"INTERNAL",level:"WARN",metadata:{},name:"queue_alias_conflict",remediation:"Give each queue a distinct name in every `env.<name>` block of wrangler.jsonc, then rerun codegen.",title:"Queue name routes to a different handler than wrangler.jsonc implies"})),te=(e,r=[])=>{const t=e.filter(c=>c.mode==="push");if(t.length===0)return"";for(const c of t)l(c.exportName,`queue export "${c.exportName}"`);const n=[...Map.groupBy(t,c=>c.filePath)].map(([c,u])=>`import { ${u.map(a=>a.exportName).join(", ")} } from "../${c}.js";`).join(`
255
+ `),{routes:s}=$(e,r),i=[...s].map(([c,u])=>` ${JSON.stringify(c)}: { binding: ${JSON.stringify(u.bindingName)}, definition: ${u.exportName}, exportName: ${JSON.stringify(u.exportName)} },`).join(`
256
+ `);return`${f}/**
253
257
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
254
258
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
255
259
  * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
@@ -261,9 +265,9 @@ ${n}
261
265
 
262
266
  /** Wrangler queue name (declared, or a per-environment rename) → { binding, definition, exportName } for batch routing. */
263
267
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
264
- ${u}
268
+ ${i}
265
269
  };
266
- `},te=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`workflow export "${t.exportName}"`),l(t.className,`workflow class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
270
+ `},ne=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`workflow export "${t.exportName}"`),l(t.className,`workflow class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
267
271
  `);return{build:`
268
272
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS, this.state.exports);
269
273
  `,contextField:`
@@ -272,7 +276,7 @@ ${u}
272
276
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
273
277
  ${r}
274
278
  ];
275
- `}},ne=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`queue export "${t.exportName}"`),l(t.bindingName,`queue binding "${t.bindingName}"`);const r=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
279
+ `}},re=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`queue export "${t.exportName}"`),l(t.bindingName,`queue binding "${t.bindingName}"`);const r=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
276
280
  `);return{build:`
277
281
  const queues = createQueueContext(env, LUNORA_QUEUES);
278
282
  `,contextField:`
@@ -281,7 +285,7 @@ ${r}
281
285
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
282
286
  ${r}
283
287
  ];
284
- `}},re=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const a=w(r,n.exportName).map(u=>`{ binding: "${u.bindingName}", exportName: "${u.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${a}] },`}).join(`
288
+ `}},oe=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const s=S(r,n.exportName).map(i=>`{ binding: "${i.bindingName}", exportName: "${i.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${s}] },`}).join(`
285
289
  `);return{build:`
286
290
  const topics = createTopicContext(env, LUNORA_TOPICS);
287
291
  `,contextField:`
@@ -290,7 +294,7 @@ ${r}
290
294
  const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
291
295
  ${t}
292
296
  ];
293
- `}},oe=(e,r)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(l(n.name,`service "${n.name}"`),l(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
297
+ `}},se=(e,r)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(l(n.name,`service "${n.name}"`),l(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
294
298
  `);return{build:`
295
299
  const services = createServices(env, LUNORA_SERVICES);
296
300
  `,importLines:[`import type { ServiceBindingSpec } from "${r}";`,`import { createServices } from "${r}";`],specs:`
@@ -298,7 +302,7 @@ ${t}
298
302
  const LUNORA_SERVICES: ReadonlyArray<ServiceBindingSpec> = [
299
303
  ${t}
300
304
  ];
301
- `}},se=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`agent export "${n.exportName}"`),l(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
305
+ `}},ae=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`agent export "${n.exportName}"`),l(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
302
306
  `);return{build:`
303
307
  const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports });
304
308
  `,contextField:r?`
@@ -309,14 +313,14 @@ ${t}
309
313
  const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
310
314
  ${t}
311
315
  ];
312
- `}},$=(e,r,t,n,a)=>({constant:`
313
- ${a}
316
+ `}},v=(e,r,t,n,s)=>({constant:`
317
+ ${s}
314
318
  const ${e} = ${b(n,r)};
315
319
  `,override:`
316
320
  protected override ${t}(): ${r} {
317
321
  return ${e};
318
322
  }
319
- `}),ae=(e,r)=>{if(e.length===0)return{constant:"",override:""};const t={...r.length===0?{}:{eventTypes:r.map(n=>n.type)},workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return $("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},ie=(e,r)=>{if(e.length===0||r.length===0)return{constant:"",override:""};for(const t of r)if(l(t.exportName,"workflow event export name"),!R.test(t.filePath))throw new N("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe workflow event file path: ${JSON.stringify(t.filePath)}`);return{constant:`
323
+ `}),ie=(e,r)=>{if(e.length===0)return{constant:"",override:""};const t={...r.length===0?{}:{eventTypes:r.map(n=>n.type)},workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return v("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},ce=(e,r)=>{if(e.length===0||r.length===0)return{constant:"",override:""};for(const t of r)if(l(t.exportName,"workflow event export name"),!w.test(t.filePath))throw new k("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe workflow event file path: ${JSON.stringify(t.filePath)}`);return{constant:`
320
324
  /** Declared workflow events (\`defineWorkflowEvent\` exports), loaded by type when an admin \`sendWorkflowEvent\` parses its payload. */
321
325
  const LUNORA_WORKFLOW_EVENTS: ReadonlyMap<string, () => Promise<{ payload: { parse: (value: unknown) => unknown } }>> = new Map([
322
326
  ${r.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").then((module) => module.${t.exportName})],`).join(`
@@ -326,7 +330,7 @@ ${r.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").
326
330
  protected override async workflowEvent(type: string): Promise<{ payload: { parse: (value: unknown) => unknown } } | undefined> {
327
331
  return LUNORA_WORKFLOW_EVENTS.get(type)?.();
328
332
  }
329
- `}},ce=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return $("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},W=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],ue=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
333
+ `}},ue=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return v("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},T=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],le=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
330
334
  const paymentsByContext = new WeakMap<object, LunoraPayment>();
331
335
  `,configField:`
332
336
  payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
@@ -341,4 +345,4 @@ ${r.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").
341
345
  }
342
346
 
343
347
  return payments;
344
- },`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",W,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},le=(e,r,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SensitiveScope",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{M as a,G as b,H as c,ne as d,V as e,re as f,oe as g,Y as h,te as i,se as j,ue as k,ae as l,ie as m,ce as n,Q as o,le as p,U as q,f as r,K as s,z as t,J as u,X as v,Z as w,ee as x};
348
+ },`,stub:y("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",T,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},de=(e,r,t,n,s)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SensitiveScope",...s?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{K as a,V as b,G as c,re as d,J as e,oe as f,se as g,z as h,ne as i,ae as j,le as k,ie as l,ce as m,ue as n,M as o,de as p,Q as q,y as r,H as s,Z as t,Y as u,X as v,ee as w,te as x};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.380",
3
+ "version": "1.0.0-alpha.382",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,15 +50,15 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "1.0.0-alpha.277",
54
- "@lunora/agent": "1.0.0-alpha.268",
55
- "@lunora/container": "1.0.0-alpha.102",
53
+ "@lunora/advisor": "1.0.0-alpha.278",
54
+ "@lunora/agent": "1.0.0-alpha.270",
55
+ "@lunora/container": "1.0.0-alpha.103",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
- "@lunora/platform": "1.0.0-alpha.76",
58
- "@lunora/queue": "1.0.0-alpha.136",
59
- "@lunora/scheduler": "1.0.0-alpha.161",
60
- "@lunora/values": "1.0.0-alpha.88",
61
- "@lunora/workflow": "1.0.0-alpha.103",
57
+ "@lunora/platform": "1.0.0-alpha.77",
58
+ "@lunora/queue": "1.0.0-alpha.137",
59
+ "@lunora/scheduler": "1.0.0-alpha.162",
60
+ "@lunora/values": "1.0.0-alpha.89",
61
+ "@lunora/workflow": "1.0.0-alpha.105",
62
62
  "@visulima/fs": "7.0.0",
63
63
  "jiti": "^2.7.0",
64
64
  "quicktype-core": "^26.0.0",