@lunora/codegen 1.0.0-alpha.351 → 1.0.0-alpha.353

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.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.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-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as g}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-isdHqPIt.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-C3QumE88.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-CScPrUD-.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs";import{default as P}from"./packem_shared/discoverCrons-B1_NUt19.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-DjRHg-Zk.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BQk3SX8D.mjs";import{default as K}from"./packem_shared/discoverFunctions-CJG4S6CK.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DCDgDIYv.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-CL-d0IVo.mjs";import{default as J}from"./packem_shared/discoverInserts-BcoTjXqI.mjs";import{d as X}from"./packem_shared/index-CN8FVvr-.mjs";import{default as $}from"./packem_shared/discoverMigrations-BWxx8Wv9.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Cy9h3EVW.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-mFJNU8qY.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-9to_l_Kh.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-CxQRVuIV.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Civ-7SiI.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4oeTYEM.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-Cl6UKT7L.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-D0B4nCmG.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage--Z1vx7GM.mjs";import{default as he}from"./packem_shared/discoverSchema-Cwt-DQgh.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-DVJbfDZ8.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CitX6ziW.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-kXq07aGl.mjs";import{emitApp as je}from"./packem_shared/emitApp-UV2Ugx7C.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-DWdj2jvW.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DfSmacMR.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-smszfFJZ.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-H9eQX4ui.mjs";import{default as vr}from"./packem_shared/fingerprintSchemaSources-BKXkgkj4.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.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-bct1OuH5.mjs";import{e as Ur}from"./packem_shared/server-DlEPJi5i.mjs";import{e as Hr}from"./packem_shared/shard-B5e5ovr_.mjs";import{G as Br}from"./packem_shared/shared-8vTRkL2-.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-ClPr_MXM.mjs";import{s as Yr,t as Xr,u as Zr}from"./packem_shared/shard-runtime-ByYXjCKY.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-zynTVppI.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-lc-hnJYn.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-CuFqq97x.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-D7mopPiT.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,g 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,ve 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,vr 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-C7Um0EnM.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-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as g}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-isdHqPIt.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-C3QumE88.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-CScPrUD-.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs";import{default as P}from"./packem_shared/discoverCrons-B1_NUt19.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-DjRHg-Zk.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BQk3SX8D.mjs";import{default as K}from"./packem_shared/discoverFunctions-CJG4S6CK.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DCDgDIYv.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-CL-d0IVo.mjs";import{default as J}from"./packem_shared/discoverInserts-BcoTjXqI.mjs";import{d as X}from"./packem_shared/index-CN8FVvr-.mjs";import{default as $}from"./packem_shared/discoverMigrations-BWxx8Wv9.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Cy9h3EVW.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-mFJNU8qY.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-9to_l_Kh.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-CxQRVuIV.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Civ-7SiI.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4oeTYEM.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-Cl6UKT7L.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-D0B4nCmG.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage--Z1vx7GM.mjs";import{default as he}from"./packem_shared/discoverSchema-Cwt-DQgh.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-DVJbfDZ8.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CitX6ziW.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-kXq07aGl.mjs";import{emitApp as je}from"./packem_shared/emitApp-C0shqv7S.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-DWdj2jvW.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DfSmacMR.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-D4reO9Yr.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-H9eQX4ui.mjs";import{default as vr}from"./packem_shared/fingerprintSchemaSources-BKXkgkj4.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.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-bct1OuH5.mjs";import{e as Ur}from"./packem_shared/server-DlEPJi5i.mjs";import{e as Hr}from"./packem_shared/shard-ByB2lGh0.mjs";import{G as Br}from"./packem_shared/shared-8vTRkL2-.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-ClPr_MXM.mjs";import{s as Yr,t as Xr,u as Zr}from"./packem_shared/shard-runtime-ByYXjCKY.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-zynTVppI.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-DF9vt_z_.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-CuFqq97x.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-D7mopPiT.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,g 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,ve 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,vr 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 M,readFileSync as Ge,mkdirSync as Bt,writeFileSync as gr,rmSync as ye,readdirSync as Cn}from"node:fs";import{dirname as Vt,join as E,relative as Tn}from"node:path";import{performance as ht}from"node:perf_hooks";import{runAdvisor as pr}from"@lunora/advisor";import{LunoraError as _}from"@lunora/errors";import{serializeSchemaSnapshot as mr}from"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{toAdvisorContext as hr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ut,ts as vr,VariableDeclarationKind as Er}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as w,bindingKeyName as ce,collectCallRows as C,findObjectProperty as V,collectSecurityCallRows as xr,propertyInitializer as R,listSecurityScanFiles as Ye,objectLiteralFromCallbackBody as On,limitNameOf as kn,optionsObjectLiteral as Rn,handlerOf as Sr,collectNodeRows as ne,chainRootOf as Qe,outermostValueWrapper as I,isWriteTarget as Xe,isSameNode as y,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as Wt,returningFunctionOf as wt,walkChain as Ar,RUN_METHODS as Fn,functionReferenceSegments as yr,isTestPath as br,isFunctionLike as re,functionKeyOf as Ln}from"./isTestPath-C3QumE88.mjs";import{b as Q,d as j,f as L,g as qt,c as x,a as jt,w as Ht,k as Nr,l as Pr,h as wr,m as Ir,j as It,i as Cr}from"./attribution-CG8-kUcl.mjs";import{a as Fs,r as vt,i as G,b as Tr,m as Dn,c as Je,e as Gt,E as Mn,C as _n,d as Or,f as kr,g as Rr}from"./context-root-CNR6TAsP.mjs";import{a as P,i as Fr,c as ee,d as Kn,e as Lr,f as Dr,g as zn}from"./classify-procedure-call-BkaeM9Ej.mjs";import{a as S,s as Mr}from"./property-name-7cBlgK_O.mjs";import{b as _r,a as Ze}from"./module-specifiers-BctA0m_p.mjs";import{r as et,s as Kr}from"./parse-validator-iVTounLK.mjs";import zr from"./discoverAuthApiCalls-CScPrUD-.mjs";import{i as z,r as $n}from"./database-calls-UPlhi3Ks.mjs";import $r from"./discoverHyperdriveCalls-CL-d0IVo.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Yt,a as Be,s as Bn,d as Br}from"./index-CN8FVvr-.mjs";import{MUTATORS_FILENAME as Vr,isDefineMutatorCallee as Ur,mutatorServerImplOf as Wr,discoverMutators as qr}from"./MUTATORS_FILENAME-Cy9h3EVW.mjs";import jr from"./discoverNondeterministicCalls-mFJNU8qY.mjs";import{discoverNotifyConfig as Hr,discoverNotifyCalls as Gr}from"./NOTIFY_FILENAME-9to_l_Kh.mjs";import Yr from"./discoverR2sqlCalls-B4oeTYEM.mjs";import Qr from"./discoverRlsProcedures-Cl6UKT7L.mjs";import{s as Qt,n as Xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Jr,redact as Zr,isHeuristicSecretKind as eo,isSecretishName as to}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Vn,readMergeDurableObjects as so}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Le,d as no,r as io}from"./modules-l-Db0C4S.mjs";import{WORKFLOWS_FILENAME as ro,discoverWorkflows as oo}from"./WORKFLOWS_FILENAME-kXq07aGl.mjs";import{r as ao}from"./json-data-Chfs2Cz5.mjs";import{a as co,I as lo,g as uo,G as Un,d as fo,i as go}from"./shared-8vTRkL2-.mjs";import{createCodegenProject as po}from"./createCodegenProject-ClPr_MXM.mjs";import{findTsconfig as wE,refreshCodegenProject as IE,tsconfigFingerprint as CE}from"./createCodegenProject-ClPr_MXM.mjs";import{CAPABILITIES as mo,usedCapabilities as ho}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Wn,isHyperdriveGlobalTable as qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as vo}from"./AGENTS_FILENAME-isdHqPIt.mjs";import{discoverContainers as Eo}from"./CONTAINERS_FILENAME-mK4cZpcz.mjs";import xo from"./discoverCrons-B1_NUt19.mjs";import{contextPropertiesRead as So,fileWiresRequestSecretTool as Ao,createTargetScope as yo,discoverFeatureUsage as bo}from"./capabilitiesUsedBy-DjRHg-Zk.mjs";import jn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as No,findProjectConfigFile as Po}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as wo}from"./QUEUES_FILENAME-Civ-7SiI.mjs";import{discoverSandboxUsage as Io}from"./discoverSandboxUsage--Z1vx7GM.mjs";import{resolveServiceBindings as Co}from"./readServiceBindings-BA49C6aN.mjs";import To from"./discoverStorageRulesMetadata-CitX6ziW.mjs";import{resolveCodegenTarget as Ct,gatePlatformFeatures as Oo,readTargetDiagnostics as ko,vectorizeDimensionDiagnostics as Ro,liveStreamsDeliveryAuthorizationDiagnostic as Fo,socketRoutesDeliveryAuthorizationDiagnostic as Lo,studioPlatformFor as Do,platformFeatureAvailable as Mo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as _o}from"./schema-BgM8A3XV.mjs";import{b as Hn,e as Ko}from"./shard-B5e5ovr_.mjs";import{e as zo,a as $o}from"./server-DlEPJi5i.mjs";import{emitDataModel as Bo}from"./emitDataModel-CuFqq97x.mjs";import{i as Vo,a as Uo,e as Wo,b as qo,d as jo,c as Ho}from"./unwrap-handler-return-CGdJGvGh.mjs";import Go from"./discoverFunctions-CJG4S6CK.mjs";import Yo from"./discoverHttpRoutes-DCDgDIYv.mjs";import Qo from"./discoverInserts-BcoTjXqI.mjs";import{e as Gn}from"./exported-procedure-chains-D1WlRfqJ.mjs";import Xo from"./discoverMigrations-BWxx8Wv9.mjs";import Jo from"./discoverQueries-CxQRVuIV.mjs";import Zo from"./discoverRlsMetadata-D0B4nCmG.mjs";import ea from"./discoverSchema-Cwt-DQgh.mjs";import{discoverShapes as ta}from"./SHAPES_FILENAME-DVJbfDZ8.mjs";import{i as sa}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as na}from"./emitApp-UV2Ugx7C.mjs";import{readJsonSync as ia}from"@visulima/fs";import{buildSchemaSnapshot as ra}from"./SchemaSnapshotParseError-H9eQX4ui.mjs";import{buildOpenApiDocument as oa,emitOpenApiModule as aa}from"./buildOpenApiDocument-DWdj2jvW.mjs";import{buildOpenRpcDocument as ca,emitOpenRpcModule as la}from"./OPENRPC_VERSION-DfSmacMR.mjs";import{v as da,t as ua,u as fa,s as ga,w as pa}from"./shard-runtime-ByYXjCKY.mjs";import{emitCollections as ma,emitSeed as ha,emitApi as va,emitInternalApi as Ea}from"./emitApi-zynTVppI.mjs";import{emitCrons as xa,emitScheduler as Sa,emitShardRegistry as Aa,emitDurableObjects as ya,emitVectors as ba,emitWranglerCronTriggers as Na}from"./emitCrons-lc-hnJYn.mjs";import Pa from"./emitDrizzleSchema-bct1OuH5.mjs";import{LAZY_FUNCTION_DIRECTORY as Yn,emitFunctions as wa,emitLazyFunctionModules as Ia}from"./emitFunctions-D7mopPiT.mjs";const Ca=(e,t=!1)=>{if(e.length===0)return"";const s=fo(t),n=e.map(c=>{if(co(c.exportName,"live stream export name"),!lo.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=>{uo(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($=>`\${encodeURIComponent(key.${$})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as M,readFileSync as Ge,mkdirSync as Bt,writeFileSync as gr,rmSync as ye,readdirSync as Cn}from"node:fs";import{dirname as Vt,join as E,relative as Tn}from"node:path";import{performance as ht}from"node:perf_hooks";import{runAdvisor as pr}from"@lunora/advisor";import{LunoraError as _}from"@lunora/errors";import{serializeSchemaSnapshot as mr}from"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{toAdvisorContext as hr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ut,ts as vr,VariableDeclarationKind as Er}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as w,bindingKeyName as ce,collectCallRows as C,findObjectProperty as V,collectSecurityCallRows as xr,propertyInitializer as R,listSecurityScanFiles as Ye,objectLiteralFromCallbackBody as On,limitNameOf as kn,optionsObjectLiteral as Rn,handlerOf as Sr,collectNodeRows as ne,chainRootOf as Qe,outermostValueWrapper as I,isWriteTarget as Xe,isSameNode as y,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as Wt,returningFunctionOf as wt,walkChain as Ar,RUN_METHODS as Fn,functionReferenceSegments as yr,isTestPath as br,isFunctionLike as re,functionKeyOf as Ln}from"./isTestPath-C3QumE88.mjs";import{b as Q,d as j,f as L,g as qt,c as x,a as jt,w as Ht,k as Nr,l as Pr,h as wr,m as Ir,j as It,i as Cr}from"./attribution-CG8-kUcl.mjs";import{a as Fs,r as vt,i as G,b as Tr,m as Dn,c as Je,e as Gt,E as Mn,C as _n,d as Or,f as kr,g as Rr}from"./context-root-CNR6TAsP.mjs";import{a as P,i as Fr,c as ee,d as Kn,e as Lr,f as Dr,g as zn}from"./classify-procedure-call-BkaeM9Ej.mjs";import{a as S,s as Mr}from"./property-name-7cBlgK_O.mjs";import{b as _r,a as Ze}from"./module-specifiers-BctA0m_p.mjs";import{r as et,s as Kr}from"./parse-validator-iVTounLK.mjs";import zr from"./discoverAuthApiCalls-CScPrUD-.mjs";import{i as z,r as $n}from"./database-calls-UPlhi3Ks.mjs";import $r from"./discoverHyperdriveCalls-CL-d0IVo.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Yt,a as Be,s as Bn,d as Br}from"./index-CN8FVvr-.mjs";import{MUTATORS_FILENAME as Vr,isDefineMutatorCallee as Ur,mutatorServerImplOf as Wr,discoverMutators as qr}from"./MUTATORS_FILENAME-Cy9h3EVW.mjs";import jr from"./discoverNondeterministicCalls-mFJNU8qY.mjs";import{discoverNotifyConfig as Hr,discoverNotifyCalls as Gr}from"./NOTIFY_FILENAME-9to_l_Kh.mjs";import Yr from"./discoverR2sqlCalls-B4oeTYEM.mjs";import Qr from"./discoverRlsProcedures-Cl6UKT7L.mjs";import{s as Qt,n as Xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Jr,redact as Zr,isHeuristicSecretKind as eo,isSecretishName as to}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Vn,readMergeDurableObjects as so}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Le,d as no,r as io}from"./modules-l-Db0C4S.mjs";import{WORKFLOWS_FILENAME as ro,discoverWorkflows as oo}from"./WORKFLOWS_FILENAME-kXq07aGl.mjs";import{r as ao}from"./json-data-Chfs2Cz5.mjs";import{a as co,I as lo,g as uo,G as Un,d as fo,i as go}from"./shared-8vTRkL2-.mjs";import{createCodegenProject as po}from"./createCodegenProject-ClPr_MXM.mjs";import{findTsconfig as wE,refreshCodegenProject as IE,tsconfigFingerprint as CE}from"./createCodegenProject-ClPr_MXM.mjs";import{CAPABILITIES as mo,usedCapabilities as ho}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Wn,isHyperdriveGlobalTable as qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as vo}from"./AGENTS_FILENAME-isdHqPIt.mjs";import{discoverContainers as Eo}from"./CONTAINERS_FILENAME-mK4cZpcz.mjs";import xo from"./discoverCrons-B1_NUt19.mjs";import{contextPropertiesRead as So,fileWiresRequestSecretTool as Ao,createTargetScope as yo,discoverFeatureUsage as bo}from"./capabilitiesUsedBy-DjRHg-Zk.mjs";import jn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as No,findProjectConfigFile as Po}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as wo}from"./QUEUES_FILENAME-Civ-7SiI.mjs";import{discoverSandboxUsage as Io}from"./discoverSandboxUsage--Z1vx7GM.mjs";import{resolveServiceBindings as Co}from"./readServiceBindings-BA49C6aN.mjs";import To from"./discoverStorageRulesMetadata-CitX6ziW.mjs";import{resolveCodegenTarget as Ct,gatePlatformFeatures as Oo,readTargetDiagnostics as ko,vectorizeDimensionDiagnostics as Ro,liveStreamsDeliveryAuthorizationDiagnostic as Fo,socketRoutesDeliveryAuthorizationDiagnostic as Lo,studioPlatformFor as Do,platformFeatureAvailable as Mo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as _o}from"./schema-BgM8A3XV.mjs";import{b as Hn,e as Ko}from"./shard-ByB2lGh0.mjs";import{e as zo,a as $o}from"./server-DlEPJi5i.mjs";import{emitDataModel as Bo}from"./emitDataModel-CuFqq97x.mjs";import{i as Vo,a as Uo,e as Wo,b as qo,d as jo,c as Ho}from"./unwrap-handler-return-CGdJGvGh.mjs";import Go from"./discoverFunctions-CJG4S6CK.mjs";import Yo from"./discoverHttpRoutes-DCDgDIYv.mjs";import Qo from"./discoverInserts-BcoTjXqI.mjs";import{e as Gn}from"./exported-procedure-chains-D1WlRfqJ.mjs";import Xo from"./discoverMigrations-BWxx8Wv9.mjs";import Jo from"./discoverQueries-CxQRVuIV.mjs";import Zo from"./discoverRlsMetadata-D0B4nCmG.mjs";import ea from"./discoverSchema-Cwt-DQgh.mjs";import{discoverShapes as ta}from"./SHAPES_FILENAME-DVJbfDZ8.mjs";import{i as sa}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as na}from"./emitApp-C0shqv7S.mjs";import{readJsonSync as ia}from"@visulima/fs";import{buildSchemaSnapshot as ra}from"./SchemaSnapshotParseError-H9eQX4ui.mjs";import{buildOpenApiDocument as oa,emitOpenApiModule as aa}from"./buildOpenApiDocument-DWdj2jvW.mjs";import{buildOpenRpcDocument as ca,emitOpenRpcModule as la}from"./OPENRPC_VERSION-DfSmacMR.mjs";import{v as da,t as ua,u as fa,s as ga,w as pa}from"./shard-runtime-ByYXjCKY.mjs";import{emitCollections as ma,emitSeed as ha,emitApi as va,emitInternalApi as Ea}from"./emitApi-zynTVppI.mjs";import{emitCrons as xa,emitScheduler as Sa,emitShardRegistry as Aa,emitDurableObjects as ya,emitVectors as ba,emitWranglerCronTriggers as Na}from"./emitCrons-DF9vt_z_.mjs";import Pa from"./emitDrizzleSchema-bct1OuH5.mjs";import{LAZY_FUNCTION_DIRECTORY as Yn,emitFunctions as wa,emitLazyFunctionModules as Ia}from"./emitFunctions-D7mopPiT.mjs";const Ca=(e,t=!1)=>{if(e.length===0)return"";const s=fo(t),n=e.map(c=>{if(co(c.exportName,"live stream export name"),!lo.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=>{uo(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($=>`\${encodeURIComponent(key.${$})}`).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.`)},Mp="env.ts",_p=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ze(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Kp=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&&Ze(n.getModuleSpecifierValue())}return!1},zp=e=>{if(r.isIdentifier(e))return _p(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Kp(t)}return!1},$p=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!zp(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=jt(s,"member");a!==void 0&&t.push({exportName:a})}return t},Bp=(e,t)=>{const s=E(t,Mp);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=$p(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Vp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Up=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Wp=(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())},qp=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(S(s));if(!r.isPropertyAssignment(s)||!t.has(S(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),jp=new Set(["durable"]),Hp=new Set(["rollback"]),Li=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Gp="defineApp",Ae="app",hn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>S(s)===Ae&&s.getInitializer()?.getText()===t)||t===Ae&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>S(s)===Ae),Yp=e=>{if(e===void 0||!No.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&S(e)===Ae;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return S(t)===Ae;if(r.isVariableDeclaration(t))return hn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&hn(e.getSourceFile(),s)},Qp="AppBuilder",Di=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Xp=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Qp&&s.getDeclarations().some(n=>Di(n))},Jp=e=>e.getText()===Gp&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Di(t)),Mi=(e,t,s=new Set)=>{const n=Qe(t);if(n===void 0||!r.isIdentifier(n))return!1;if(Jp(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 Yp(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 Mi(e,a.getInitializer(),s)}}return!1},_i=(e,t)=>{const s=Wt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Mi(e,s.object)||Xp(s.object))},Zp=new Map([["defineContainer",{keys:Up,signal:"containerEgressPolicy"}],["defineStep",{keys:Hp,signal:"workflowRollback"}],["stream",{keys:jp,signal:"durableStreams"}]]),em=(e,t)=>{const s=Zp.get(Li(t));if(s!==void 0)return t.getArguments().some(n=>qp(Wp(e,n),s.keys))?s.signal:void 0},tm=(e,t)=>Vp[Li(t)]??(_i(e,t)?"deliveryAuthorization":void 0),sm=(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 A(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=So(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=o.getDescendantsOfKind(d.CallExpression);for(const c of a){const l=em(o,c)??tm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>zn(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 Ut({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Ge(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>_i(i,o))}return n},nm=(e,t)=>{const s=yo();for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Ao(i,s))return!0}return!1},im="createWorker",rm="extend",vn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,En=e=>{const t=[],s=vn(R(e,"backupCron"));s!==void 0&&t.push(s);const n=R(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=vn(i.getNameNode());o!==void 0&&t.push(o)}return t},om=e=>{const t=P(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===im)return r.isObjectLiteralExpression(s)?En(s):[];if(t!==rm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=On(s.getBody());return n===void 0?[]:En(n)},am=(e,t)=>{const s=[];for(const{filePath:n}of Ye(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...om(o))}return[...new Set(s)]},Ki=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Ki(e.inner)},cm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Ki(n);return i!==void 0&&t.has(i)}))},lm=(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 _("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 _("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})}},dm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Jl(s,t),a=Bp(s,t),c=oo(s,t),{queues:l,topics:u}=wo(s,t),f=Co(n),g=vo(s,t);lm(c,g);const m=Eo(s,t),v=To(s,t),$=xo(s,t,c,g),ue=am(s,t),b=sm(s,t,Po(n)),B=Io(s,t),H=nm(s,t),F=bo(s,t);F.browser=F.browser||B.usesSandboxBrowser;const k=Ct(n,e.target),T=Oo(F,k,{agents:g.length>0,commitOrderedTables:i.tables.some(D=>D.commitOrdered===!0),cronTriggers:$.length>0,crossShardFanout:i.tables.some(D=>_o(D)),containerEgressPolicy:b.containerEgressPolicy,containerRuntimeScheduling:m.some(D=>D.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(D=>D.sandbox===!0),deliveryAuthorization:b.deliveryAuthorization,durableStreams:b.durableStreams,globalTables:i.tables.some(D=>D.shardMode==="global"),liveContext:b.liveContext,liveStreams:b.liveStreams,typedWebSockets:b.typedWebSockets,queues:l.length>0,relationGraph:cm(i),secretValues:H,secrets:b.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:B.usesSandboxLoader,workflowRollback:b.workflowRollback,workflowSchedules:c.some(D=>D.schedules!==void 0)}),U=T.usage,X=ho(U),te=T.signals.vectorStore!==!1,se=T.signals.services===!1?[]:f,oe=jn(n),K=oe??new Set,N=K.has("lunorash");Dp(i,oe,{hasVectors:te,scheduler:U.scheduler||$.length>0,storage:U.storage||v.rules.length>0||Object.keys(Hn(i)).length>0,usage:U});const O=M(E(t,"flags.ts")),Ie=M(E(t,"notify.ts"));return{agents:g,capabilities:X,containers:m,crons:$,dataModelContent:Bo(i),declaredDependencies:oe,dependencies:K,entryCronTriggers:ue,env:a,featureUsage:U,hasFlags:O,hasNotify:Ie,identity:o,platformGate:{...T,diagnostics:[...ko(n,e.target),...T.diagnostics,...Ro(k,i.vectorIndexes),...b.liveStreams&&b.deliveryAuthorization?[Fo(k)]:[],...b.socketRoutes&&b.deliveryAuthorization?[Lo(k)]:[]]},queues:l,serverContent:zo({agents:g,capabilities:X,containers:m,env:a,hasVectors:te,hasFlags:O,hasNotify:Ie,identity:o,queues:l,schema:i,services:se,storageRuleBuckets:v.rules.map(D=>D.bucket),topics:u,useUmbrella:N,workflows:c}),services:se,storageRulesMetadata:v,topics:u,usesSandbox:B.usesSandboxBrowser||B.usesSandboxContainer||B.usesSandboxFs,useUmbrella:N,workflows:c}},zi=(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},um=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},fm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),gm=/^[\w$]+:[\w$]+$/u,pm=(e,t)=>{const s=Ln(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},xn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},mm=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return xn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Er.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?xn(s):void 0}}},hm=(e,t,s)=>({schedule:{argKeys:mm(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Fn.has(s))return pm(s,n);if((s==="runAfter"||s==="runAt")&&um(t)){const l=Ln(i)??(r.isStringLiteral(i)&&gm.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,...hm(s,n,o)}}const a=fm.get(s),c=a===void 0?void 0:zi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Em=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),$i=e=>vr.isOptionalChain(e.compilerNode),xm=(e,t)=>r.isIfStatement(t)?!y(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?y(e,t.getStatement()):r.isForStatement(t)?y(e,t.getStatement())||y(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:re(t)?t.getFirstAncestor(re)!==void 0:r.isConditionalExpression(t)?!y(e,t.getCondition()):r.isBinaryExpression(t)?!y(e,t.getLeft())&&Em.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&$i(t)?!y(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&kg(s)),Sm=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)&&y(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(re);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&y(o.getFirstAncestor(re),i))===!0},Am=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&y(e,t.getStatement())||r.isForStatement(t)&&(y(e,t.getStatement())||y(t.getIncrementor(),e)),ym=(e,t)=>{if($i(e)||t==="schedule"&&Sm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(xm(s,i)){if(!Am(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Sn=(e,t,s)=>{if(s===void 0)return;const n=ym(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:x(e)}},bm=(e,t)=>[...C(e,t,(s,n)=>Sn(s,n,vm(s))),...ne(e,t,d.PropertyAccessExpression,(s,n)=>{const i=zi(s,"services");return Sn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Nm=new Set(["boolean","number","object","string"]),Pm=e=>{const t=e.getName();if(!Nm.has(t))return;const s=e.getExpression();return G(s,["flags"])||G(s,["flags","details"])?t:void 0},wm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Pm(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},Im=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=wm(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))},Cm=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"||Vo(o))return;const a=e.getSourceFile().getFilePath();if(Uo(i,e,a)){const c=Wo(i,e,a,0,new Set);return c===void 0&&qo(o),c}return o},Tm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Mr(t.getNameNode());return s===void 0||s==="namespace"}),Om=(e,t)=>{for(const{filePath:s}of Ye(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Tm(a)))return i}}},km="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Rm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw de(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 (${km}). 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})},Fm="room:",Lm="__lunora_socket__:",Dm=/^[A-Za-z]\w*$/u,An=e=>Dm.test(e),Mm=e=>`${e}:`.startsWith(Fm)||`${e}:`.startsWith(Lm),Bi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Vi=e=>Bi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),yn=e=>S(e),rs=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&S(s)===t),ae=(e,t)=>{const s=de(e,`defineLiveStream ${t}`);return new _("LIVE_STREAM_NOT_LITERAL",s.message)},Ui=(e,t,s)=>{const n=rs(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ae(n??e,`needs ${s} so codegen can read its topics`);if(Vi(i))throw ae(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},_m=(e,t)=>{const s=yn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ae(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Vi(n))throw ae(n,`cannot spread into or compute the keys of topic "${s}"`);if(!An(s)||Mm(s))throw new _("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(rs(n,"key")===void 0)return{fields:[],name:s};const a=Ui(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>yn(l)),c=a.find(l=>!An(l));if(c!==void 0)throw new _("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}},Km=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ae(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Bi(n))throw ae(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=rs(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ae(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Ui(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:w(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>_m(a,l))}},zm=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 _("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)}},$m=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Bm=(e,t)=>e.getDescendantsOfKind(d.CallExpression).filter(s=>zn(s,"defineLiveStream")).map(s=>{const n=$m(s),i=r.isVariableDeclaration(n)?jt(n,"binding"):void 0;if(i===void 0)throw new _("LIVE_STREAM_NOT_EXPORTED",de(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 Km(s,i,t)}),Vm=(e,t)=>{const s=A(t).flatMap(n=>Bm(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return zm(s),s},Um=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Wm=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Um(e):!0,Wi=(e,t=!1)=>{for(const s of e.getProperties()){if(Wm(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Wi(n,!0))return!0}return!1},qm=(e,t)=>{for(const s of A(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Gn(n))for(const o of Yt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Wi(a)))return!0}}return!1},jm=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Be(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=Be(a);c!==void 0&&s.push({column:c,strategy:Bn(a),table:i})}}return s},Hm=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Gn(i))for(const a of Yt(o))for(const c of jm(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Gm=["providerSubscriptionId","state"],Ym=["providerEventId","processedAt"],bn=(e,t)=>t.every(s=>s in e.shape),Qm=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&&bn(t,Gm)&&bn(s,Ym)},Xm=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Jm=(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},Zm=(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},eh="@lunora/privacy",qi="userId",th=e=>e.replaceAll("\\","/"),sh="privacy",nh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),st=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,nt=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",os=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),ih=(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},it=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},rh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=ih(s,"tables"),i=st(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:os(n).map(a=>nt(a)))t.datasets.set(o,i)},oh=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?os(s):[],i=new Set(n.map(o=>nt(o)));for(const o of Xm)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?st(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},Nn=(e,t,s)=>{t.datasets.set(st(e.getArguments()[0])??s,s)},as=8,Pe=(e,t=0)=>{if(t>as)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Pe(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:Pe(i,t+1)},ah=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[nt(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()]}},ji=(e,t=0)=>{const s=Pe(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>as)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?ji(i.getExpression(),t+1):[ah(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},ch=e=>{const t=e.getArguments()[0];return t===void 0?void 0:ji(t)},lh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Pe(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?os(n):[])t.excluded.set(nt(i),r.isPropertyAssignment(i)?st(i.getInitializer())??"":"")},dh=(e,t)=>{switch(it(e)){case"actionCacheDataset":{Nn(e,t,"actionCache");break}case"authDataset":{oh(e,t);break}case"defineDataset":{rh(e,t);break}case"documentHistoryDataset":{Nn(e,t,"documentHistory");break}}},cs=e=>e!==void 0&&r.isCallExpression(e)&&it(e)==="defineDataset",Hi=e=>e!==void 0&&r.isCallExpression(e)&&nh.has(it(e)??""),uh=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)&&(cs(i)||Hi(i))?n:void 0},Gi=(e,t,s=0)=>{const n=Pe(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>as)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Gi(i.getExpression(),t,s+1))return!1}else if(!cs(i)&&!Hi(i)){const o=r.isIdentifier(i)?uh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},fh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Gi(t,s)?s:void 0},gh=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(dh(i,t),it(i)==="definePrivacy"){const o=ch(i);lh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:fh(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>cs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},ph=(e,t)=>{const s=E(t,"schema.ts"),n=[...A(t),...M(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>th(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},mh=(e,t,s)=>{if(s?.has(eh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of ph(e,t)){const g=gh(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:Jm(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},hh=e=>e.extensionKey!==sh&&qi in e.shape,vh=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 (it has a "${qi}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Eh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>hh(o)).map(o=>o.name),[n]=Zm(s,t.classifications);if(n!==void 0)throw new _("PRIVACY_COVERAGE",vh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new _("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},xh=(e,t)=>{const s=Do(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")}},Sh=new Set(["delete","hardDelete","patch","replace","restore"]),Ah=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),yh=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Pn=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},bh=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:Pn(i,e)}return Pn(s,e)},wn="",Nh=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},Ph=(e,t)=>{if(Ah.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():wn]};if(Sh.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:bh(t,e);return{method:e,tables:s.length===0?[wn]:s}}},In=(e,t)=>e===void 0?void 0:{...e,fields:Nh(t,e.method)},wh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(z(n))return In(Ph(s,e.getArguments()[0]),e);if(yh.has(s)&&r.isPropertyAccessExpression(n)&&z(n.getExpression()))return In({method:s,tables:[n.getName()]},e)},Ih=(e,t)=>C(e,t,(s,n)=>{const i=wh(s);if(i===void 0)return;const o=x(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}))}),Ch=(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"}),Th=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||V(s,"args")===void 0)return!1}return Jt(e,t).opaque},Oh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ee(a);c!==void 0&&Th(a,c.receiver)&&s.push(Ch(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},kh=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Oh(i,w(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Rh=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"}]]),He=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Yi=e=>!e.isAny(),Qi=e=>{const t=e.getType();if(!Yi(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Rh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Fh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},Xi={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."},Lh=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.`}),Dh={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)."},Mh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),_h={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)."},Kh=(e,t,s)=>{if(!t.some(i=>Cr(i)))return Dh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Mh.has(s.typeName)&&!n&&!t.some(i=>sa(i))?_h:Xi},Ji=(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:Lh(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"}},zh=(e,t,s)=>{const n=[];for(const i of Q(e)){const o=r.isIdentifier(i.getNameNode())?It(i):[i.getName()],c=o.some(u=>He(s,t,u))||!Fh(i)?void 0:Qi(i),[l=i.getName()]=o;c!==void 0&&n.push(Ji(t,l,c,i.getStartLineNumber(),Kh(i,o,c)))}return n},$h=(e,t,s)=>{if(He(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=Qi(i.getExpression());o!==void 0&&n.push(Ji(t,"default",o,i.getStartLineNumber(),Xi))}return n},Bh=(e,t,s)=>[...zh(e,t,s),...$h(e,t,s)],Vh=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>It(n).some(i=>He(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=It(n).find(o=>He(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Uh=({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"}),Wh=(e,t,s)=>{const n=[],i=[];for(const a of A(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Bh(c,l,s)),i.push(...Vh(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Yi(a.getType()))&&n.push(Uh(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},qh=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"},jh=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Hh=(e,t)=>C(e,t,(s,n)=>qh(s)?{file:n,line:s.getStartLineNumber(),scope:x(s),workflow:jh(s)}:void 0),we=(e,t)=>{M(e)&&Ge(e,"utf8")===t||gr(e,t,"utf8")},Gh=(e,t)=>{if(t===""){ye(e,{force:!0});return}we(e,t)},Yh=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){ye(s,{force:!0,recursive:!0});return}if(M(s))for(const n of Cn(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[Tn(e,i)]===void 0&&ye(i)}for(const[n,i]of Object.entries(t))Bt(Vt(E(e,n)),{recursive:!0}),we(E(e,n),i)},Qh=(e,t,s)=>{const n=E(e,t);if(Object.keys(s).length===0){ye(n,{force:!0,recursive:!0});return}if(M(n))for(const i of Cn(n,{recursive:!0,withFileTypes:!0})){const o=E(i.parentPath,i.name);i.isFile()&&s[Tn(n,o)]===void 0&&ye(o)}for(const[i,o]of Object.entries(s)){const a=E(n,i);Bt(Vt(a),{recursive:!0}),we(a,o)}},Xh=e=>{try{const t=ia(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},$e=(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)},Jh=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Zh=(e,t)=>{M(e)||Bt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{we(E(e,n.name),n.content),s.push(n.name);break}case"directory":{Qh(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{Yh(e,n.files),s.push(...Object.keys(n.files));break}default:Gh(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},ev=e=>{const t=Xh(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=oa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ca({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
29
  `,openApiModuleContent:aa(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
- `,openRpcModuleContent:la(i)}},tv=".lunora-schema.json",sv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},nv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new _("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 _("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 _("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})}},iv=8,rv=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,$=()=>Ho(()=>{const F=Go(l,a,{lazyFunctions:o}),k=qr(l,a);return{functions:F,httpRoutes:Yo(l,a),mutators:k}});let{erased:ue,value:{functions:b,httpRoutes:B,mutators:H}}=$();mn([...b,...H].map(F=>F.filePath)),mn(B.filter(F=>F.stream).map(F=>F.filePath),"http-stream");for(let F=1;;F+=1){const k=u?b:b.filter(N=>N.channel?.kind!=="room"&&N.lifecycle!=="socket"),T=va({agents:t,functions:k,httpRoutes:B,mutators:H,useUmbrella:m,workflows:v}),U={agents:t,functions:k,lazyFunctions:o,migrations:c,mutators:H,shapes:f,useUmbrella:m,usesSandbox:g},X=wa(U),te=Ia(U),se=Ea({functions:b,useUmbrella:m}),oe=E(a,"_generated",Yn),K=[[s,T],[i,se],[n,X],...Object.entries(te).map(([N,O])=>[E(oe,N),O])];if(F>=iv||K.every(([N,O])=>Jh(l,N,O)))return{apiContent:T,erased:ue,functions:b,functionModulesContent:te,functionsContent:X,httpRoutes:B,internalContent:se,mutators:H};for(const[N,O]of K)$e(l,N,O);({erased:ue,value:{functions:b,httpRoutes:B,mutators:H}}=$())}},bE=e=>{const t=sv(),s=t?ht.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!M(o))throw new _("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??po(n);Kr(Cm);const c=ea(a,o,e.projectRoot);Eh(c.tables,mh(a,n,jn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:$,env:ue,featureUsage:b,hasFlags:B,hasNotify:H,identity:F,platformGate:k,queues:T,serverContent:U,services:X,storageRulesMetadata:te,topics:se,usesSandbox:oe,useUmbrella:K,workflows:N}=dm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Rm(c,c.jurisdiction===void 0?void 0:Om(a,n));const O=E(n,"_generated"),Ie=E(O,"dataModel.ts"),D=E(O,"server.ts"),Zi=E(O,"api.ts"),er=E(O,"internal.ts"),tr=E(O,"functions.ts");$e(a,Ie,m),$e(a,D,U);const ls=Object.fromEntries(X.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries($o(p,O))));for(const[p,mt]of Object.entries(ls))$e(a,E(O,p),mt);const Ce=Xo(a,n),fe=ta(a,n),rt=k.signals.typedWebSockets!==!1,{apiContent:ds,erased:sr,functions:J,functionModulesContent:us,functionsContent:fs,httpRoutes:ot,internalContent:gs,mutators:at}=rv({agents:l,apiPath:Zi,generatedFunctionsPath:tr,internalPath:er,lazyFunctions:i,roomsSupported:rt,lunoraDirectory:n,migrations:Ce,project:a,shapes:fe,useUmbrella:K,usesSandbox:oe,workflows:N}),ps=no(a,n),ct=io(ps,c,[...J,...ot].map(p=>p.filePath)),Te=ps.length>0,Oe=e.lint===!1&&!Te?void 0:{callEdges:bm(a,n),inserts:Qo(a,n),queries:Jo(a,n,J),tableWrites:Ih(a,n),workflowCalls:Hh(a,n)},ke=e.lint===!1||Oe===void 0?void 0:dp(a,n,{callSites:Oe,containers:f,crons:g,functions:J,modules:ct,mutators:at,queues:T,schema:c,shapes:fe,workflows:N,wranglerVariables:e.wranglerVariables}),ms=ke===void 0?[]:vp(e.projectRoot,[...pr(ke,{source:"static"}),...Wh(a,n,{byName:new Set([...N,...T,...l,...f].map(p=>p.exportName)),byPath:new Set([...J,...at,...fe,...Ce].map(p=>`${p.filePath}:${p.exportName}`))}),...kh(a,n),...jo(sr,n),...da(T,e.wranglerQueueProducers)]),nr=Zo(a,n),hs=Hm(a,n);nv(fe,hs,qm(a,n));const ir=B?Im(a,n):[],lt=k.signals.vectorStore!==!1,rr=Mo(Ct(e.projectRoot,e.target),"deliveryAuthorization"),me=xh(b,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:Qm(c.tables),queueCount:T.length,storageColumnCount:Object.keys(Hn(c)).length,storageRuleCount:te.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Ct(e.projectRoot,e.target),vectorStoreSupported:lt,workflowCount:N.length}),vs=t?ht.now():0,dt=ra(c,Ce.map(p=>p.id)),ut=Vm(a,n),Es=Ko({advisories:ms.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:ke?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:ue,flagKeys:ir,hasFlags:B,hasNotify:H,hasRooms:rt&&J.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||J.some(p=>go(p)),hasSecretValues:k.signals.secretValues===!0,hasSockets:rt&&J.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:lt,liveStreamDeclarations:ut,liveStreams:k.signals.liveStreams===!0,maskMetadata:hs,mutators:at,queues:T,rlsMetadata:nr,schema:c,schemaSnapshot:dt,shapes:fe,services:X,storageRules:te,studioFeatures:me,topics:se,useUmbrella:K,workflows:N}),xs=ma(fe,v.has("@lunora/db"),K),Ss=ua(f,c.jurisdiction),As=fa(N),ys=ga(l),bs=pa(T,e.wranglerQueueProducers),Ns=Ca(ut,K),Ps=xa(g),or=Sa(me.scheduler),ar=Aa(c.tables,K),cr=so(e.projectRoot)?ya(K):"",ws=ba(c.vectorIndexes),Re=Pa(c,K),Is=ha(v.has("@lunora/seed")),Fe=e.apiSpec??"openapi",ft=Fe==="openapi"||Fe==="both",gt=Fe==="openrpc"||Fe==="both",Cs=na({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")||M(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Wn(p)),hasHyperdriveGlobal:c.tables.some(p=>qn(p)),hasKvIntrospector:me.kv,hasNotify:H,hasQueue:T.some(p=>p.mode==="push"),liveStreams:k.signals.liveStreams===!0,liveStreamsWithheld:k.liveStreamsWithheld,liveStreamDeclarations:ut,hasScheduler:me.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:me.storage,hasDeliveryAuthorization:rr,hasVectors:lt,hasWorkflow:N.length>0,identity:F,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:K,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:Te,wantsOpenApi:ft,wantsOpenRpc:gt}),{openApiContent:Ts,openApiModuleContent:Os,openRpcContent:ks,openRpcModuleContent:Rs}=ev({functions:J,httpRoutes:ot,modules:ct,projectRoot:e.projectRoot,wantsArchitecture:Te}),he=Te&&Oe!==void 0?Rp({...Oe,crons:g,functions:J,httpRoutes:ot,modules:ct,queues:T,schema:c,services:X,topics:se,workflows:N}):void 0,pt=E(n,tv),lr=M(pt),dr=e.dryRun?[]:Zh(O,[{content:Cs,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ds,kind:"always",name:"api.ts"},{content:gs,kind:"always",name:"internal.ts"},{content:U,kind:"always",name:"server.ts"},{content:fs,kind:"always",name:"functions.ts"},{files:us,kind:"directory",name:Yn},{content:Es,kind:"always",name:"shard.ts"},{content:Ps,kind:"always",name:"crons.ts"},{content:ws,kind:"always",name:"vectors.ts"},{content:Re.global,kind:"always",name:"drizzle.global.ts"},{content:Re.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ss,kind:"optional",name:"containers.ts"},{content:As,kind:"optional",name:"workflows.ts"},{content:ys,kind:"optional",name:"agents.ts"},{content:bs,kind:"optional",name:"queues.ts"},{content:Ns,kind:"optional",name:"live.ts"},{content:or,kind:"optional",name:"scheduler.ts"},{content:ar,kind:"optional",name:"shardRegistry.ts"},{content:cr,kind:"optional",name:"durableObjects.ts"},{content:Is,kind:"optional",name:"seed.ts"},{content:xs,kind:"optional",name:"collections.ts"},{files:ls,kind:"services"},{content:ft?Ts:"",kind:"optional",name:"openapi.json"},{content:ft?Os:"",kind:"optional",name:"openapi.ts"},{content:gt?ks:"",kind:"optional",name:"openrpc.json"},{content:gt?Rs:"",kind:"optional",name:"openrpc.ts"},{content:he===void 0?"":`${JSON.stringify(he,void 0,2)}
30
+ `,openRpcModuleContent:la(i)}},tv=".lunora-schema.json",sv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},nv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new _("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 _("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 _("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})}},iv=8,rv=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,$=()=>Ho(()=>{const F=Go(l,a,{lazyFunctions:o}),k=qr(l,a);return{functions:F,httpRoutes:Yo(l,a),mutators:k}});let{erased:ue,value:{functions:b,httpRoutes:B,mutators:H}}=$();mn([...b,...H].map(F=>F.filePath)),mn(B.filter(F=>F.stream).map(F=>F.filePath),"http-stream");for(let F=1;;F+=1){const k=u?b:b.filter(N=>N.channel?.kind!=="room"&&N.lifecycle!=="socket"),T=va({agents:t,functions:k,httpRoutes:B,mutators:H,useUmbrella:m,workflows:v}),U={agents:t,functions:k,lazyFunctions:o,migrations:c,mutators:H,shapes:f,useUmbrella:m,usesSandbox:g},X=wa(U),te=Ia(U),se=Ea({functions:b,useUmbrella:m}),oe=E(a,"_generated",Yn),K=[[s,T],[i,se],[n,X],...Object.entries(te).map(([N,O])=>[E(oe,N),O])];if(F>=iv||K.every(([N,O])=>Jh(l,N,O)))return{apiContent:T,erased:ue,functions:b,functionModulesContent:te,functionsContent:X,httpRoutes:B,internalContent:se,mutators:H};for(const[N,O]of K)$e(l,N,O);({erased:ue,value:{functions:b,httpRoutes:B,mutators:H}}=$())}},bE=e=>{const t=sv(),s=t?ht.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!M(o))throw new _("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??po(n);Kr(Cm);const c=ea(a,o,e.projectRoot);Eh(c.tables,mh(a,n,jn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:$,env:ue,featureUsage:b,hasFlags:B,hasNotify:H,identity:F,platformGate:k,queues:T,serverContent:U,services:X,storageRulesMetadata:te,topics:se,usesSandbox:oe,useUmbrella:K,workflows:N}=dm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Rm(c,c.jurisdiction===void 0?void 0:Om(a,n));const O=E(n,"_generated"),Ie=E(O,"dataModel.ts"),D=E(O,"server.ts"),Zi=E(O,"api.ts"),er=E(O,"internal.ts"),tr=E(O,"functions.ts");$e(a,Ie,m),$e(a,D,U);const ls=Object.fromEntries(X.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries($o(p,O))));for(const[p,mt]of Object.entries(ls))$e(a,E(O,p),mt);const Ce=Xo(a,n),fe=ta(a,n),rt=k.signals.typedWebSockets!==!1,{apiContent:ds,erased:sr,functions:J,functionModulesContent:us,functionsContent:fs,httpRoutes:ot,internalContent:gs,mutators:at}=rv({agents:l,apiPath:Zi,generatedFunctionsPath:tr,internalPath:er,lazyFunctions:i,roomsSupported:rt,lunoraDirectory:n,migrations:Ce,project:a,shapes:fe,useUmbrella:K,usesSandbox:oe,workflows:N}),ps=no(a,n),ct=io(ps,c,[...J,...ot].map(p=>p.filePath)),Te=ps.length>0,Oe=e.lint===!1&&!Te?void 0:{callEdges:bm(a,n),inserts:Qo(a,n),queries:Jo(a,n,J),tableWrites:Ih(a,n),workflowCalls:Hh(a,n)},ke=e.lint===!1||Oe===void 0?void 0:dp(a,n,{callSites:Oe,containers:f,crons:g,functions:J,modules:ct,mutators:at,queues:T,schema:c,shapes:fe,workflows:N,wranglerVariables:e.wranglerVariables}),ms=ke===void 0?[]:vp(e.projectRoot,[...pr(ke,{source:"static"}),...Wh(a,n,{byName:new Set([...N,...T,...l,...f].map(p=>p.exportName)),byPath:new Set([...J,...at,...fe,...Ce].map(p=>`${p.filePath}:${p.exportName}`))}),...kh(a,n),...jo(sr,n),...da(T,e.wranglerQueueProducers)]),nr=Zo(a,n),hs=Hm(a,n);nv(fe,hs,qm(a,n));const ir=B?Im(a,n):[],lt=k.signals.vectorStore!==!1,rr=Mo(Ct(e.projectRoot,e.target),"deliveryAuthorization"),me=xh(b,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:Qm(c.tables),queueCount:T.length,storageColumnCount:Object.keys(Hn(c)).length,storageRuleCount:te.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Ct(e.projectRoot,e.target),vectorStoreSupported:lt,workflowCount:N.length}),vs=t?ht.now():0,dt=ra(c,Ce.map(p=>p.id)),ut=Vm(a,n),Es=Ko({advisories:ms.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:ke?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:ue,flagKeys:ir,hasFlags:B,hasNotify:H,hasRooms:rt&&J.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||J.some(p=>go(p)),hasSecretValues:k.signals.secretValues===!0,hasSockets:rt&&J.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:lt,liveStreamDeclarations:ut,liveStreams:k.signals.liveStreams===!0,maskMetadata:hs,mutators:at,queues:T,rlsMetadata:nr,schema:c,schemaSnapshot:dt,shapes:fe,services:X,storageRules:te,studioFeatures:me,topics:se,useUmbrella:K,workflows:N}),xs=ma(fe,v.has("@lunora/db"),K),Ss=ua(f,c.jurisdiction),As=fa(N),ys=ga(l),bs=pa(T,e.wranglerQueueProducers),Ns=Ca(ut,K),Ps=xa(g),or=Sa(me.scheduler),ar=Aa(c.tables,K,c.jurisdiction),cr=so(e.projectRoot)?ya(K):"",ws=ba(c.vectorIndexes),Re=Pa(c,K),Is=ha(v.has("@lunora/seed")),Fe=e.apiSpec??"openapi",ft=Fe==="openapi"||Fe==="both",gt=Fe==="openrpc"||Fe==="both",Cs=na({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")||M(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Wn(p)),hasHyperdriveGlobal:c.tables.some(p=>qn(p)),hasKvIntrospector:me.kv,hasNotify:H,hasQueue:T.some(p=>p.mode==="push"),liveStreams:k.signals.liveStreams===!0,liveStreamsWithheld:k.liveStreamsWithheld,liveStreamDeclarations:ut,hasScheduler:me.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:me.storage,hasDeliveryAuthorization:rr,hasVectors:lt,hasWorkflow:N.length>0,identity:F,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:K,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:Te,wantsOpenApi:ft,wantsOpenRpc:gt}),{openApiContent:Ts,openApiModuleContent:Os,openRpcContent:ks,openRpcModuleContent:Rs}=ev({functions:J,httpRoutes:ot,modules:ct,projectRoot:e.projectRoot,wantsArchitecture:Te}),he=Te&&Oe!==void 0?Rp({...Oe,crons:g,functions:J,httpRoutes:ot,modules:ct,queues:T,schema:c,services:X,topics:se,workflows:N}):void 0,pt=E(n,tv),lr=M(pt),dr=e.dryRun?[]:Zh(O,[{content:Cs,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ds,kind:"always",name:"api.ts"},{content:gs,kind:"always",name:"internal.ts"},{content:U,kind:"always",name:"server.ts"},{content:fs,kind:"always",name:"functions.ts"},{files:us,kind:"directory",name:Yn},{content:Es,kind:"always",name:"shard.ts"},{content:Ps,kind:"always",name:"crons.ts"},{content:ws,kind:"always",name:"vectors.ts"},{content:Re.global,kind:"always",name:"drizzle.global.ts"},{content:Re.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ss,kind:"optional",name:"containers.ts"},{content:As,kind:"optional",name:"workflows.ts"},{content:ys,kind:"optional",name:"agents.ts"},{content:bs,kind:"optional",name:"queues.ts"},{content:Ns,kind:"optional",name:"live.ts"},{content:or,kind:"optional",name:"scheduler.ts"},{content:ar,kind:"optional",name:"shardRegistry.ts"},{content:cr,kind:"optional",name:"durableObjects.ts"},{content:Is,kind:"optional",name:"seed.ts"},{content:xs,kind:"optional",name:"collections.ts"},{files:ls,kind:"services"},{content:ft?Ts:"",kind:"optional",name:"openapi.json"},{content:ft?Os:"",kind:"optional",name:"openapi.ts"},{content:gt?ks:"",kind:"optional",name:"openrpc.json"},{content:gt?Rs:"",kind:"optional",name:"openrpc.ts"},{content:he===void 0?"":`${JSON.stringify(he,void 0,2)}
31
31
  `,kind:"optional",name:"architecture.json"},{content:he===void 0?"":Fp(he),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!lr||e.updateSchemaBaseline===!0)&&we(pt,mr(dt)),t){const p=ht.now(),mt=Math.round(p-s),ur=Math.round(vs-s),fr=Math.round(p-vs);console.error(`@lunora/codegen: codegen took ${mt.toString()}ms (discovery ${ur.toString()}ms, emit ${fr.toString()}ms)`)}return{advisories:ms,advisorContext:ke,agents:l,architecture:he,containers:f,cronTriggers:[...new Set([...Na(g),...$])],generated:{agents:ys,api:ds,app:Cs,collections:xs,containers:Ss,crons:Ps,dataModel:m,drizzleGlobal:Re.global,drizzleShard:Re.shard,functionModules:us,functions:fs,internal:gs,live:Ns,openApi:Ts,openApiModule:Os,openRpc:ks,openRpcModule:Rs,queues:bs,seed:Is,server:U,shard:Es,vectors:ws,workflows:As},migrations:Ce,outputDirectory:O,platformDiagnostics:k.diagnostics,queues:T,schemaSnapshot:dt,schemaSnapshotPath:pt,workflows:N,writtenFiles:dr}};export{tv as SCHEMA_SNAPSHOT_FILENAME,po as createCodegenProject,wE as findTsconfig,IE as refreshCodegenProject,bE as runCodegen,CE as tsconfigFingerprint};
@@ -1,4 +1,4 @@
1
- import{APP_METHOD_CAPABILITIES as E}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{i as D}from"./schema-BgM8A3XV.mjs";import{a as R,I as A,G as x}from"./shared-8vTRkL2-.mjs";const C={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},g=e=>[...E.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[C]:[]],v=e=>g(e).length>0,y=e=>(e.emailAgents?.length??0)>0,d=e=>e.tables.some(t=>D(t)),u=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,O=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as E}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{i as D}from"./schema-BgM8A3XV.mjs";import{a as R,I as A,G as x}from"./shared-8vTRkL2-.mjs";const C={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},g=e=>[...E.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[C]:[]],v=e=>g(e).length>0,y=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(t=>D(t)),u=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,O=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);
@@ -249,17 +249,18 @@ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector =
249
249
  * shard-local ones it filtered out before calling here — a single
250
250
  * \`startLine\` plus positional counting would mis-attribute every row after
251
251
  * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
252
- * falls back to the position-derived count otherwise.
252
+ * falls back to the position-derived count otherwise. A dry run is passed through and writes nothing.
253
253
  */
254
254
  const buildGlobalImporter =
255
255
  (database: D1DatabaseLike, cdc: boolean) =>
256
- (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
256
+ (request: { dryRun?: boolean; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
257
257
  const exec = buildExec(database);
258
258
  // Same reason the PITR applier carries it: a bulk import that skips the
259
259
  // changelog restores rows no downstream consumer is ever told about.
260
260
  const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
261
261
 
262
262
  return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
263
+ dryRun: request.dryRun === true,
263
264
  exec,
264
265
  rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
265
266
  ...(request.startLine === undefined ? {} : { startLine: request.startLine }),
@@ -336,7 +337,7 @@ const buildGlobalCdcApplier =
336
337
 
337
338
  return request.changes.length;
338
339
  };
339
- `:"",I=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)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\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}']:[]],q=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>;"]:[],...v(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],L=e=>g(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
340
+ `:"",I=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)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\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}']:[]],q=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>;"]:[],...v(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(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>;"]:[]],L=e=>g(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
340
341
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
341
342
  this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
342
343
 
@@ -395,7 +396,7 @@ const buildGlobalCdcApplier =
395
396
  this.shardSelector = selector;
396
397
 
397
398
  return this;
398
- }`,...d(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
399
+ }`,...l(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
399
400
  public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
400
401
  this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
401
402
 
@@ -485,10 +486,10 @@ const buildGlobalCdcApplier =
485
486
  ? {
486
487
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
487
488
  }
488
- : {}),`]:[],...d(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) } : {}),"]:[],...v(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
489
+ : {}),`]:[],...l(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) } : {}),"]:[],...v(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
489
490
  ${r.join(`
490
491
  `)}
491
- `:""},_=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],B=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],G=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],M=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],W=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],$=e=>e?['import notifyConfig from "../notify.js";']:[],H=e=>y(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],U=e=>y(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],F=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],c=[...r||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((s,h)=>s.localeCompare(h)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},Q=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:l,hasStorage:c,hasWorkflow:s,wantsOpenApi:h,wantsOpenRpc:p}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...B(t,r),...W(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...G(o),...M(e.hasVectors),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...H(e),...F(e),"",..._(e.identity),...U(e),...a||n?['import schema from "../schema.js";']:[],...$(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";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...p?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...u(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
492
+ `:""},B=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],G=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],_=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],M=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],W=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],$=e=>e?['import notifyConfig from "../notify.js";']:[],H=e=>y(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],U=e=>y(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],F=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",c=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],h=[...r||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...c].toSorted((s,d)=>s.localeCompare(d)).join(", ")} } from "${i}";`,`import { ${h} } from "${i}";`]},Q=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:c,hasStorage:h,hasWorkflow:s,wantsOpenApi:d,wantsOpenRpc:p}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...G(t,r),...W(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],..._(o),...M(e.hasVectors),...c?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...h?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...H(e),...F(e),"",...B(e.identity),...U(e),...a||n?['import schema from "../schema.js";']:[],...$(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";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...p?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...u(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
492
493
  // The schema's jurisdiction pins the auth object like every other DO.
493
494
  jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",J=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,K=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
494
495
  ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${J(t.shardMode)}],`).join(`
@@ -496,10 +497,10 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${J(t.shardMode)}],`)
496
497
  ]);
497
498
 
498
499
  options.listSchemaTables = () => [...tableSharding.keys()];
499
- options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...d(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
500
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...l(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
500
501
 
501
502
  if (shardRegistry) {
502
- options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}namespace: shardRegistry, secret: (env as { SHARD_REGISTRY_DO_SECRET?: string }).SHARD_REGISTRY_DO_SECRET }) });
503
+ options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
503
504
  }`]:[]],f=e=>(e.liveStreamDeclarations??[]).map(t=>{if(R(t.exportName,"live stream export name"),!A.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),V=e=>u(e)?[" httpRouter: liveStreamRouter([",...f(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],Y=e=>u(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],X=e=>u(e)?`liveStreamRouter([
504
505
  ${f(e).join(`
505
506
  `)}
@@ -522,6 +523,8 @@ ${f(e).join(`
522
523
  // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
523
524
  // land here, and without it they are reported, not written.
524
525
  options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
526
+ // The importer above skips the write for a dry run.
527
+ options.importGlobalsSupportsDryRun = true;
525
528
  // The read/replay half of the same admin plane. Each one is the
526
529
  // only reason its endpoint can see the global storage plane at
527
530
  // all, and every one of them fails SILENTLY when unset — export
@@ -759,7 +762,7 @@ type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
759
762
  // One memo per env for THIS assembled worker: a framework-hosted worker rebuilds its options per
760
763
  // request and must reuse it, but a second \`assemble()\` has its own auth closure and must not share.
761
764
  const identityMemos: IdentityMemoStore = new WeakMap();
762
- `:"",l=a?`
765
+ `:"",c=a?`
763
766
  const initAuth = async (env: Env): Promise<void> => {
764
767
  if (!this.authDeclaration) {
765
768
  return;
@@ -811,8 +814,8 @@ type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
811
814
  authInit = null;
812
815
  throw error;
813
816
  }));
814
- `:"",c=a?`
815
- await ensureAuth(env);`:"",s=a?"() => auth, identityMemos":"() => null",h=a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null",p=r.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
817
+ `:"",h=a?`
818
+ await ensureAuth(env);`:"",s=a?"() => auth, identityMemos":"() => null",d=a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null",p=r.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
816
819
  host ? withFrameworkWorker(${X(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,w=r.hasFramework?"host?: FrameworkHostHandler":"",b=r.emailAgents??[],k=b.length>0?` composed.email = dispatchAgentEmail([
817
820
  ${b.map(m=>` { agent: lunoraAgentDefinitions.${m.exportName}, className: ${JSON.stringify(m.className)} },`).join(`
818
821
  `)}
@@ -873,13 +876,13 @@ ${S}
873
876
  // build, so the first request constructs them and every later request on
874
877
  // the same isolate reuses them.
875
878
  let worker: LunoraWorker | null = null;
876
- ${i}${l}
879
+ ${i}${c}
877
880
  ${p}
878
881
 
879
882
  const composed: ComposedApp = {
880
883
  ShardDO,
881
884
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
882
- const env = rawEnv as Env;${c}
885
+ const env = rawEnv as Env;${h}
883
886
  worker ??= buildWorker(env);
884
887
 
885
888
  return worker.fetch(request, rawEnv, context);
@@ -923,7 +926,7 @@ ${r.hasFramework?`
923
926
  }
924
927
  ${O(r)}${T(r.hasStorage)}
925
928
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
926
- private buildWorkerOptions(env: Env, ${h}): WorkerOptions {
929
+ private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
927
930
  const options: WorkerOptions = {
928
931
  ${ee(r).join(`
929
932
  `)}
@@ -1,4 +1,4 @@
1
- import{G as i,d as c}from"./shared-8vTRkL2-.mjs";import{i as m}from"./schema-BgM8A3XV.mjs";const u=r=>r?`${i}/**
1
+ import{G as a,d as c}from"./shared-8vTRkL2-.mjs";import{i as y}from"./schema-BgM8A3XV.mjs";const f=s=>s?`${a}/**
2
2
  * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
3
3
  * forward it — wrangler binds only what the entry exports:
4
4
  *
@@ -8,7 +8,10 @@ import{G as i,d as c}from"./shared-8vTRkL2-.mjs";import{i as m}from"./schema-BgM
8
8
  * forwards this module for you whenever it exists.
9
9
  */
10
10
  export { SchedulerDO } from "@lunora/scheduler";
11
- `:"",y=(r,t)=>r.some(o=>m(o))?`${i}/**
11
+ `:"",u=(s,r,o)=>{if(!s.some(t=>y(t)))return"";const e=o?JSON.stringify(o):"undefined";return`${a}import { WorkerEntrypoint } from "cloudflare:workers";
12
+ import { hostedShardRegistry } from "${c(r).do}";
13
+
14
+ /**
12
15
  * The \`ShardRegistryDO\` Durable Object class — the live set of shard keys per
13
16
  * \`.shardBy()\` table, which cross-shard export, CDC sync and migrations fan out
14
17
  * to. Re-exported so a worker entry can forward it (wrangler binds only what the
@@ -21,8 +24,32 @@ export { SchedulerDO } from "@lunora/scheduler";
21
24
  * \`export *\`. A Vite-first (class-A) app needs neither line — its generated
22
25
  * worker entry does both whenever this module exists.
23
26
  */
24
- export { ShardRegistryDO } from "${c(t).do}";
25
- `:"",w=r=>`${i}/**
27
+ export { ShardRegistryDO } from "${c(r).do}";
28
+
29
+ /**
30
+ * The registry's RPC surface. A worker that calls a registry this worker hosts binds
31
+ * this class with a service binding (\`services: [{ binding, service, entrypoint:
32
+ * "ShardRegistryEntrypoint" }]\`), so it needs no secret: the binding is the capability.
33
+ * The host signs its own calls into the registry with its \`LUNORA_RELAY_SECRET\`.
34
+ */
35
+ export class ShardRegistryEntrypoint extends WorkerEntrypoint<{ SHARD_REGISTRY: unknown; LUNORA_RELAY_SECRET?: string }> {
36
+ public register(table: string, shardKey: string): Promise<void> {
37
+ return hostedShardRegistry(this.env, ${e}).register(table, shardKey);
38
+ }
39
+
40
+ public unregister(table: string, shardKey: string): Promise<void> {
41
+ return hostedShardRegistry(this.env, ${e}).unregister(table, shardKey);
42
+ }
43
+
44
+ public listShardKeys(table: string): Promise<string[]> {
45
+ return hostedShardRegistry(this.env, ${e}).listShardKeys(table);
46
+ }
47
+
48
+ public snapshot(): Promise<Record<string, string[]>> {
49
+ return hostedShardRegistry(this.env, ${e}).snapshot();
50
+ }
51
+ }
52
+ `},R=s=>`${a}/**
26
53
  * Host the shard, the scheduler and the shard registry in ONE Durable Object
27
54
  * class, so the app spends one of the account's classes instead of three. A
28
55
  * Vite-first (class-A) app needs nothing more: its generated worker entry builds
@@ -34,17 +61,17 @@ export { ShardRegistryDO } from "${c(t).do}";
34
61
  * to \`.scheduler()\` / \`.shardRegistry()\`. Merge before the first deploy only:
35
62
  * data already in \`ShardDO\` does not move, and a deployed merge cannot be undone.
36
63
  */
37
- export { mergeDurableObjects, roleNamespace } from "${c(r).do}";
38
- `,O=r=>{const t=new Map;for(const n of r){const d=t.get(n.cron);d?d.push(n):t.set(n.cron,[n])}const o=[...t.keys()].map(n=>` ${JSON.stringify(n)},`).join(`
64
+ export { mergeDurableObjects, roleNamespace } from "${c(s).do}";
65
+ `,S=s=>{const r=new Map;for(const n of s){const d=r.get(n.cron);d?d.push(n):r.set(n.cron,[n])}const o=[...r.keys()].map(n=>` ${JSON.stringify(n)},`).join(`
39
66
  `),e=o.length>0?`
40
67
  ${o}
41
- `:"",s=[...t.entries()].map(([n,d])=>{const l=d.map(a=>{const f=a.workflow?`workflow: ${JSON.stringify(a.workflow.className)}`:`functionPath: ${JSON.stringify(a.functionPath)}`;return` { name: ${JSON.stringify(a.name)}, ${f}, args: ${JSON.stringify(a.args)} },`}).join(`
68
+ `:"",t=[...r.entries()].map(([n,d])=>{const l=d.map(i=>{const g=i.workflow?`workflow: ${JSON.stringify(i.workflow.className)}`:`functionPath: ${JSON.stringify(i.functionPath)}`;return` { name: ${JSON.stringify(i.name)}, ${g}, args: ${JSON.stringify(i.args)} },`}).join(`
42
69
  `);return` ${JSON.stringify(n)}: [
43
70
  ${l}
44
71
  ],`}).join(`
45
- `),h=s.length>0?`
46
- ${s}
47
- `:"";return`${i}/**
72
+ `),h=t.length>0?`
73
+ ${t}
74
+ `:"";return`${a}/**
48
75
  * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
49
76
  * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
50
77
  * shard; \`workflow\` is a workflow class name (its \`ctx.exports\` key) whose durable workflow is
@@ -69,10 +96,10 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${e}];
69
96
  * looks up \`event.cron\` here and dispatches every job in the list.
70
97
  */
71
98
  export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${h}};
72
- `},S=r=>{const t=[...r].toSorted((e,s)=>e.name.localeCompare(s.name)).map(e=>{const s=[`name: ${JSON.stringify(e.name)}`,`table: ${JSON.stringify(e.table)}`];return e.field!==void 0&&s.push(`field: ${JSON.stringify(e.field)}`),e.dimensions!==void 0&&s.push(`dimensions: ${JSON.stringify(e.dimensions)}`),e.metric!==void 0&&s.push(`metric: ${JSON.stringify(e.metric)}`),e.metadata!==void 0&&s.push(`metadata: ${JSON.stringify(e.metadata)}`),` { ${s.join(", ")} },`}).join(`
73
- `),o=t.length>0?`
74
- ${t}
75
- `:"";return`${i}/**
99
+ `},b=s=>{const r=[...s].toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>{const t=[`name: ${JSON.stringify(e.name)}`,`table: ${JSON.stringify(e.table)}`];return e.field!==void 0&&t.push(`field: ${JSON.stringify(e.field)}`),e.dimensions!==void 0&&t.push(`dimensions: ${JSON.stringify(e.dimensions)}`),e.metric!==void 0&&t.push(`metric: ${JSON.stringify(e.metric)}`),e.metadata!==void 0&&t.push(`metadata: ${JSON.stringify(e.metadata)}`),` { ${t.join(", ")} },`}).join(`
100
+ `),o=r.length>0?`
101
+ ${r}
102
+ `:"";return`${a}/**
76
103
  * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
77
104
  * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
78
105
  * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
@@ -93,4 +120,4 @@ export interface LunoraVectorIndex {
93
120
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
94
121
  */
95
122
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${o}];
96
- `},b=r=>[...new Set(r.map(t=>t.cron))];export{O as emitCrons,w as emitDurableObjects,u as emitScheduler,y as emitShardRegistry,S as emitVectors,b as emitWranglerCronTriggers};
123
+ `},w=s=>[...new Set(s.map(r=>r.cron))];export{S as emitCrons,R as emitDurableObjects,f as emitScheduler,u as emitShardRegistry,b as emitVectors,w as emitWranglerCronTriggers};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-B5e5ovr_.mjs";import"./shard-runtime-ByYXjCKY.mjs";import"./shared-8vTRkL2-.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-ByB2lGh0.mjs";import"./shard-runtime-ByYXjCKY.mjs";import"./shared-8vTRkL2-.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -1,4 +1,4 @@
1
- import{LunoraError as he}from"@lunora/errors";import{serializeSchemaSnapshot as Jt,hashSchemaSnapshot as Yt}from"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{isHyperdriveGlobalTable as zt,isD1GlobalTable as Xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Zt}from"./json-data-Chfs2Cz5.mjs";import{r as $,e as er,a as tr,b as rr,c as nr,d as ar,f as sr,g as or,h as ir,i as dr,j as cr,k as lr,l as ur,m as hr,n as pr,o as mr,p as fr,q as gr}from"./shard-runtime-ByYXjCKY.mjs";import{u as re,h as br,s as yr,a as wr,I as vr,c as kr,G as Sr,d as Rr}from"./shared-8vTRkL2-.mjs";import{p as xr}from"./platform-8oj7iXQy.mjs";import{i as Ar}from"./schema-BgM8A3XV.mjs";const u=(n,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${t}); })()`,pe=["categories","description","facing","level","remediation","title"],Or=n=>{const t={};return{advisoryRows:n.map(a=>{let r=t[a.name];return r||(r=Object.fromEntries(pe.filter(o=>o in a).map(o=>[o,a[o]])),t[a.name]=r),Object.fromEntries(Object.entries(a).filter(([o,d])=>!pe.includes(o)||JSON.stringify(d)!==JSON.stringify(r[o])))}),advisoryRules:t}},Dr=` /**
1
+ import{LunoraError as he}from"@lunora/errors";import{serializeSchemaSnapshot as Jt,hashSchemaSnapshot as Yt}from"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{isHyperdriveGlobalTable as zt,isD1GlobalTable as Xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Zt}from"./json-data-Chfs2Cz5.mjs";import{r as $,e as er,a as tr,b as rr,c as nr,d as ar,f as sr,g as or,h as ir,i as dr,j as cr,k as lr,l as ur,m as hr,n as pr,o as mr,p as fr,q as gr}from"./shard-runtime-ByYXjCKY.mjs";import{u as M,h as br,s as yr,a as wr,I as vr,c as kr,G as Sr,d as Rr}from"./shared-8vTRkL2-.mjs";import{p as xr}from"./platform-8oj7iXQy.mjs";import{i as Ar}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,pe=["categories","description","facing","level","remediation","title"],Or=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(pe.filter(s=>s in o).map(s=>[s,o[s]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([s,i])=>!pe.includes(s)||JSON.stringify(i)!==JSON.stringify(n[s])))}),advisoryRules:t}},Dr=` /**
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
@@ -30,7 +30,7 @@ import{LunoraError as he}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,y=(n="")=>` const writer = this.adminWriter(${n});`,Tr=`${Dr}
33
+ }`,y=(r="")=>` const writer = this.adminWriter(${r});`,Tr=`${Dr}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -156,7 +156,10 @@ ${y()}
156
156
  }
157
157
 
158
158
  protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
159
- this.ensureMigrated();
159
+ // A dry run checks row shapes and never writes. Migrating first would write the schema ledger and create tables on a cold shard.
160
+ if (args.dryRun !== true) {
161
+ this.ensureMigrated();
162
+ }
160
163
 
161
164
  ${y()}
162
165
 
@@ -231,13 +234,13 @@ ${y()}
231
234
  await applyCdcChanges(writer, args.changes);
232
235
 
233
236
  return { applied: args.changes.length };
234
- }`,_r=({actionOnlyBuild:n,actionOnlyFields:t,agentsBuild:e,agentsContextField:a,containersBuild:r,containersContextField:o,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:h,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:g=!1,notifyBuild:c,ormContextField:w,paymentsBuild:M,paymentsContextField:A,queuesBuild:q,queuesContextField:F,topicsBuild:R,topicsContextField:U,vectorsBuild:i,vectorsContextField:v,workflowsBuild:E,workflowsContextField:B})=>{const I=t.length>0,C=w===""?"{ db }":"{ db, orm: bindOrm(facade) }",j=w===""?"":`
235
- orm: databaseContext.orm,`,W=w===""?"":`
237
+ }`,_r=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,containersBuild:n,containersContextField:s,databaseOptions:i,everyContextBuild:l,everyContextField:u,facadeBlock:m,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:g=!1,notifyBuild:c,ormContextField:w,paymentsBuild:q,paymentsContextField:A,queuesBuild:F,queuesContextField:U,topicsBuild:R,topicsContextField:B,vectorsBuild:d,vectorsContextField:v,workflowsBuild:E,workflowsContextField:j})=>{const I=t.length>0,C=w===""?"{ db }":"{ db, orm: bindOrm(facade) }",W=w===""?"":`
238
+ orm: databaseContext.orm,`,K=w===""?"":`
236
239
  orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,O=I?`
237
240
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
238
241
  // and attached only for an \`action\` so query/mutation ctx never carry them.
239
242
  if (isAction) {
240
- ${n.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`).join(`
243
+ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(f=>` ctx.${f} = ${f};`).join(`
241
244
  `)}
242
245
  }
243
246
  `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; replayKey?: boolean | undefined; scope?: QueryReadScope | undefined; sensitive?: SensitiveScope | undefined; trusted?: boolean | undefined } = {}): unknown {
@@ -267,7 +270,7 @@ ${n.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`
267
270
  };
268
271
  })();
269
272
  const { identity, ip, userId } = caller;
270
- ${i}${m}${r}${E}${q}${R}${e}
273
+ ${d}${l}${n}${E}${F}${R}${e}
271
274
  // Which dispatch this ctx belongs to. Drives the two deferral facades
272
275
  // below and the \`ctx.run*\` caller guard; a ctx built for an
273
276
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -381,12 +384,12 @@ ${x} // \`ctx.db\`, wrapped in automatic instrumentation: by default
381
384
  // Schema triggers close over this DB's scheduler, so a composed
382
385
  // mutation must rebuild its DB and table/ORM views with its own queue.
383
386
  const makeDatabaseContext = (scheduler: SchedulerLike) => {
384
- const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability, options.sensitive);
385
- ${h} return ${C};
387
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${i}), logFunctionPath, traceAnchor, observability, options.sensitive);
388
+ ${m} return ${C};
386
389
  };
387
390
  const databaseContext = makeDatabaseContext(scheduler);
388
391
  const db = databaseContext.db;
389
- ${M}
392
+ ${q}
390
393
 
391
394
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
392
395
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -463,11 +466,11 @@ ${c}
463
466
  // to the handler so code that signs its own URLs (a copy-in
464
467
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
465
468
  // query and for a deferred dispatch, for the reasons given there.
466
- origin: requestOrigin,${j}
469
+ origin: requestOrigin,${W}
467
470
  scheduler,
468
471
  span,
469
472
  storage: contextStorage,
470
- trace,${v}${f}${A}${o}${B}${F}${U}${a}${S?`
473
+ trace,${v}${u}${A}${s}${j}${U}${B}${o}${S?`
471
474
  [Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
472
475
  };
473
476
  ${I?` const isAction = contextKind === "action";
@@ -502,7 +505,7 @@ ${g?` const captureScope = (): (() => void) => {
502
505
  // refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
503
506
  return Object.defineProperties({}, {
504
507
  ...Object.getOwnPropertyDescriptors(target),
505
- db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${W}
508
+ db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${K}
506
509
  fetch: { configurable: true, enumerable: true, value: refuseFetch, writable: true },
507
510
  // The composed mutation's ids come from the action's replay key and counter, so its draws do too; a
508
511
  // fresh factory per call would repeat the same draws across sibling mutations.
@@ -567,7 +570,7 @@ ${g?` const captureScope = (): (() => void) => {
567
570
 
568
571
  if (queryView === undefined) {
569
572
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
570
- ${t.map(p=>` delete descriptors.${p};
573
+ ${t.map(f=>` delete descriptors.${f};
571
574
  `).join("")} // Writable and configurable, like the plain fields they replace.
572
575
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
573
576
 
@@ -655,7 +658,7 @@ const dispatchRun = async (
655
658
  } finally {
656
659
  runDepth -= 1;
657
660
  }
658
- };`,Er=n=>n?me.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
661
+ };`,Er=r=>r?me.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
659
662
  captureScope?: () => () => void,`).replace(` try {
660
663
  // A mutation composed from an action`,` try {
661
664
  let loaded = getLoadedFunction(functionPath);
@@ -929,13 +932,13 @@ __PREPARE_FUNCTION__ this.ensureServable();
929
932
  }
930
933
 
931
934
  throw error;
932
- `,Pr=(n,t=!1)=>{const e=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
935
+ `,Pr=(r,t=!1)=>{const e=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
933
936
 
934
937
  if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
935
938
  throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
936
939
  }
937
940
 
938
- `:"",a=t?` const requestScope = this.captureRequestScope();
941
+ `:"",o=t?` const requestScope = this.captureRequestScope();
939
942
  const preparation = this.prepareFunction(functionPath, "rpc");
940
943
 
941
944
  if (preparation !== undefined) {
@@ -946,7 +949,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
946
949
  }
947
950
  }
948
951
 
949
- `:"";return Ir.replace("__COMMITTED_CATCH__",n?Lr:"").replace("__PREPARE_FUNCTION__",`${e}${a}`)},Nr=n=>{const t={};for(const e of n.tables){const a={};for(const[r,o]of Object.entries(e.shape)){const d=re(o);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(t[e.name]=a)}return t},$r=n=>{const t={};for(const e of n.tables){const a=[];for(const[r,o]of Object.entries(e.shape))re(o).kind==="storage"&&a.push(r);a.length>0&&(t[e.name]=a)}return t},Mr=n=>{const t={};for(const e of n.tables){const a=[...e.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(e.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...e.rankIndexes.map(r=>({fields:r.sortBy.map(o=>o.field),name:r.name,type:"rank"})),...e.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(t[e.name]=a)}return t},qr=n=>{const t=[];for(const e of n.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Fr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const t=[];for(const e of n.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const a=JSON.parse(e.literalValue);if(typeof a!="string")return;t.push(a)}catch{return}}return t},Ur=(n,t,e)=>{const a=re(t),r={name:n,optional:br(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=e.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const o=Fr(a);return o!==void 0&&(r.enumValues=o),a.column?.notNull===!1&&(r.nullable=!0),r},Br=n=>{const t={};for(const e of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(e.relations.flatMap(o=>o.kind==="one"?[[o.field,o.onDelete]]:[]));for(const[o,d]of Object.entries(e.shape))a.push(Ur(o,d,r));t[e.name]=a}return t},jr=({hasMutators:n,hasSensitiveShapes:t,hasShapes:e,rlsData:a})=>{const r="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",o=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${r} {
952
+ `:"";return Ir.replace("__COMMITTED_CATCH__",r?Lr:"").replace("__PREPARE_FUNCTION__",`${e}${o}`)},Nr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,s]of Object.entries(e.shape)){const i=M(s);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},$r=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,s]of Object.entries(e.shape))M(s).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Mr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(s=>s.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},qr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Fr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Ur=new Set(["bigint","boolean","date","number","timestamp"]),Br=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=s=>s.kind==="null"||s.kind==="literal"&&s.literalValue==="null",n=M(o(e)?t:e);return o(t)!==o(e)&&Ur.has(n.kind)?n:void 0},jr=(r,t,e)=>{const o=M(t),n=Br(o),s=n??o,i={name:r,optional:br(t),type:s.kind};if(s.kind==="id"&&s.tableName!==void 0){i.ref=s.tableName;const u=e.get(r);u!==void 0&&(i.onDelete=u)}s.kind==="storage"&&(i.isStorage=!0,s.bucket!==void 0&&(i.bucket=s.bucket));const l=Fr(s);return l!==void 0&&(i.enumValues=l),(s.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Wr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,i]of Object.entries(e.shape))o.push(jr(s,i,n));t[e.name]=o}return t},Kr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",s=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
950
953
  const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
951
954
 
952
955
  try {
@@ -958,8 +961,8 @@ __PREPARE_FUNCTION__ this.ensureServable();
958
961
  }
959
962
  }
960
963
 
961
- private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${r} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${r} {`,m=e?`
962
- ${o}
964
+ private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${n} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {`,l=e?`
965
+ ${s}
963
966
  const shape = LUNORA_SHAPES[name];
964
967
 
965
968
  if (!shape) {
@@ -1021,14 +1024,14 @@ ${o}
1021
1024
 
1022
1025
  return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
1023
1026
  }
1024
- `:"",f=e?[...new Set(a.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],h=f.length>0?`
1027
+ `:"",u=e?[...new Set(o.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],m=u.length>0?`
1025
1028
  /** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
1026
- assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(f)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1027
- `:"";return{customMutatorOverride:n?`
1029
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(u)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1030
+ `:"";return{customMutatorOverride:r?`
1028
1031
  protected override isCustomMutator(functionPath: string): boolean {
1029
1032
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1030
1033
  }
1031
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:h,shapeReadPolicyImport:h===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:m}},Wr=(n,t)=>n?`
1034
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:l}},Hr=(r,t)=>r?`
1032
1035
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1033
1036
  const env = this.env as Record<string, unknown>;
1034
1037
  // A shape read performs no writes, so the widened request only needs
@@ -1094,7 +1097,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(f)}, (schema as
1094
1097
 
1095
1098
  return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1096
1099
  }
1097
- `:"",Kr=n=>({externalSourceOverride:n?`
1100
+ `:"",Vr=r=>({externalSourceOverride:r?`
1098
1101
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1099
1102
  const env = (this.env ?? {}) as Record<string, unknown>;
1100
1103
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1234,7 +1237,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(f)}, (schema as
1234
1237
 
1235
1238
  return nextDueAt;
1236
1239
  }
1237
- `:"",sourceBootstrap:n?`
1240
+ `:"",sourceBootstrap:r?`
1238
1241
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1239
1242
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1240
1243
 
@@ -1244,11 +1247,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(f)}, (schema as
1244
1247
  if (autoSourced) {
1245
1248
  void this.scheduleSourcePoll();
1246
1249
  }
1247
- `:"",sourceClientCacheConst:n?`
1250
+ `:"",sourceClientCacheConst:r?`
1248
1251
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1249
1252
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1250
- `:""}),Hr=(n,t)=>{const e=t.length>0,r=n?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1251
- `:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,h=n?`
1253
+ `:""}),Gr=(r,t)=>{const e=t.length>0,n=r?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=e?` const vectorShardKey = this.currentShardKey();
1254
+ `:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",u=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,m=r?`
1252
1255
  const vectorSync = this.vectorSync(env);
1253
1256
  // Vectorize lives outside this shard's SQLite, so a query whose result
1254
1257
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1258,18 +1261,18 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1258
1261
  const bareVectors = vectorSync?.vectors ?? vectorsStub;
1259
1262
  const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1260
1263
  const onWrite = vectorSync?.onWrite;
1261
- `:"";return{vectorSyncMethod:n?`
1264
+ `:"";return{vectorSyncMethod:r?`
1262
1265
  private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1263
1266
  if (!config.vectors) {
1264
1267
  return undefined;
1265
1268
  }
1266
1269
 
1267
1270
  const lunora = createVectors({ indexes: config.vectors(env) });
1268
- ${o} const vectors = createContextVectors(lunora${f});
1271
+ ${s} const vectors = createContextVectors(lunora${u});
1269
1272
 
1270
1273
  return {
1271
- backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
1272
- onWrite: createVectorSyncHook({ ${d}schema: schema as unknown as VectorSchemaLike, vectors }),
1274
+ backfill: createVectorBackfillSync({ ${i}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
1275
+ onWrite: createVectorSyncHook({ ${i}schema: schema as unknown as VectorSchemaLike, vectors }),
1273
1276
  vectors,
1274
1277
  };
1275
1278
  }
@@ -1291,14 +1294,14 @@ ${o} const vectors = createContextVectors(lunora${f});
1291
1294
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1292
1295
  });
1293
1296
  }
1294
- `:"",vectorsBuild:h,vectorsStub:r}},on=({advisories:n=[],advisorProcedures:t=[],agents:e=[],capabilities:a=new Set,containers:r=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasRooms:h=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:M=[],liveStreams:A=!1,maskMetadata:q,mutators:F=[],queues:R=[],rlsMetadata:U,schema:i,schemaSnapshot:v,shapes:E=[],storageRules:B,studioFeatures:I,services:C=[],topics:j=[],useUmbrella:W=!1,workflows:O=[]})=>{const l=Rr(W),K=F.length>0,p=E.length>0,D=E.some(s=>yr(s.args).length>0),H=S||D,fe=v===void 0?"":Jt(v),ge=v===void 0?"":`
1297
+ `:"",vectorsBuild:m,vectorsStub:n}},cn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:s,flagKeys:i=[],hasFlags:l=!1,hasNotify:u=!1,hasRooms:m=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:q=[],liveStreams:A=!1,maskMetadata:F,mutators:U=[],queues:R=[],rlsMetadata:B,schema:d,schemaSnapshot:v,shapes:E=[],storageRules:j,studioFeatures:I,services:C=[],topics:W=[],useUmbrella:K=!1,workflows:O=[]})=>{const h=Rr(K),H=U.length>0,f=E.length>0,D=E.some(a=>yr(a.args).length>0),V=S||D,fe=v===void 0?"":Jt(v),ge=v===void 0?"":`
1295
1298
  /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1296
1299
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Yt(v))}, json: ${JSON.stringify(fe)} };
1297
- `,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(a),L=tr(m,l.flags),V=rr(d,m,l.flags),G=gr(f),Q=nr(o),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(j,R),J=or(C,l.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(r,i.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(a.has("payments")),We=n,{advisoryRules:Ke,advisoryRows:He}=Or(We),Ve=t,ne=U??{policies:[],roles:[]},Ge=q??{columns:[]},Qe=B??{rules:[]},Je=I??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ye,override:ze}=ur(O),{constant:Xe,override:Ze}=hr(R),b=w&&i.vectorIndexes.length>0,Y=new Set(i.tables.filter(s=>Ar(s)).map(s=>s.name)),ae=b&&i.vectorIndexes.some(s=>Y.has(s.table)),T=i.tables.some(s=>s.shardMode==="global"),z=pr(Y),X=i.tables.some(s=>zt(s)),se=i.tables.some(s=>Xt(s)),P=i.tables.some(s=>s.externalSource!==void 0),oe=i.tables.some(s=>s.memory===!0),Z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&X)throw new he("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ee=i.tables.length>0,et=Nr(i),tt=Mr(i),rt=Br(i),nt=$r(i),ie=qr(i),te=mr(b,O.length>0,R.length>0,m,Z);p&&te.push("WhereInput"),D&&te.push("SensitiveScope");const de=fr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=jr({hasMutators:K,hasSensitiveShapes:D,hasShapes:p,rlsData:ne}),_=A?M:[];for(const s of _)if(wr(s.exportName,"live stream export name"),!vr.test(s.filePath))throw new he("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ct=c?[]:_.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),lt=` protected override liveStreams() {
1298
- return { ${_.map(s=>`${kr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1300
+ `,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(o),L=tr(l,h.flags),G=rr(i,l,h.flags),Q=gr(u),J=nr(s),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(W,R),Y=or(C,h.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(n,d.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(o.has("payments")),We=r,{advisoryRules:Ke,advisoryRows:He}=Or(We),Ve=t,ne=B??{policies:[],roles:[]},Ge=F??{columns:[]},Qe=j??{rules:[]},Je=I??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ye,override:ze}=ur(O),{constant:Xe,override:Ze}=hr(R),b=w&&d.vectorIndexes.length>0,z=new Set(d.tables.filter(a=>Ar(a)).map(a=>a.name)),ae=b&&d.vectorIndexes.some(a=>z.has(a.table)),T=d.tables.some(a=>a.shardMode==="global"),X=pr(z),Z=d.tables.some(a=>zt(a)),se=d.tables.some(a=>Xt(a)),P=d.tables.some(a=>a.externalSource!==void 0),oe=d.tables.some(a=>a.memory===!0),ee=d.tables.some(a=>a.shardMode!=="global"&&a.searchIndexes.length>0);if(se&&Z)throw new he("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const te=d.tables.length>0,et=Nr(d),tt=Mr(d),rt=Wr(d),nt=$r(d),ie=qr(d),re=mr(b,O.length>0,R.length>0,l,ee);f&&re.push("WhereInput"),D&&re.push("SensitiveScope");const de=fr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=Kr({hasMutators:H,hasSensitiveShapes:D,hasShapes:f,rlsData:ne}),_=A?q:[];for(const a of _)if(wr(a.exportName,"live stream export name"),!vr.test(a.filePath))throw new he("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(a.filePath)}`);const ct=c?[]:_.map(a=>`import { ${a.exportName} as liveStream_${a.exportName} } from "../${a.filePath}.js";`),lt=` protected override liveStreams() {
1301
+ return { ${_.map(a=>`${kr(a.id)}: liveStream_${a.exportName}`).join(", ")} };
1299
1302
  }
1300
1303
  `,ut=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1301
- ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1304
+ ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}.js").then((module) => module.${a.exportName})],`).join(`
1302
1305
  `)}
1303
1306
  ]);
1304
1307
 
@@ -1319,11 +1322,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1319
1322
  protected override liveStreams() {
1320
1323
  return Object.fromEntries(this.loadedLiveStreams);
1321
1324
  }
1322
- `;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${te.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${Z?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],p?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];ee&&N.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...G.importLines,...Q.importLines,...Te,...Ce,...ve,...xe,...J.importLines,...$e,...Be,...H?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ct,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...K?["LUNORA_MUTATOR_PATHS"]:[],...h?["LUNORA_ROOMS"]:[],...g?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
1325
+ `;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${re.join(", ")} } from "${h.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${ee?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${h.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${h.do}";`]:[],f?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`];te&&N.push(`import { bindOrm, bindTableFacade } from "${h.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...Q.importLines,...J.importLines,...Te,...Ce,...ve,...xe,...Y.importLines,...$e,...Be,...V?[`import { sensitiveArgumentNames } from "${h.values}";`]:[],"",'import schema from "../schema.js";',...ct,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...H?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...g?["LUNORA_SOCKETS"]:[],...f?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
1323
1326
  vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",pt=se?`
1324
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",mt=X?`
1327
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",mt=Z?`
1325
1328
  hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ft=P?`
1326
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=Hr(b,ae?i.vectorIndexes.filter(s=>Y.has(s.table)).map(s=>s.name):[]),Rt=`{
1329
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=Gr(b,ae?d.vectorIndexes.filter(a=>z.has(a.table)).map(a=>a.name):[]),Rt=`{
1327
1330
  ...this.ctxDbTuning(),
1328
1331
  auth: { identity: identity ?? null, userId: userId ?? null },
1329
1332
  broadcast: (delta) => {
@@ -1378,8 +1381,8 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1378
1381
  storage,${T?`
1379
1382
  globalDb,`:""}
1380
1383
  }`,xt=b?`
1381
- vectors,`:"",At=ee?`
1382
- orm: bindOrm(facade),`:"",le=X?"config.hyperdriveGlobal":"config.d1",Ot=T?` const bookmark = this.getInboundBookmark();
1384
+ vectors,`:"",At=te?`
1385
+ orm: bindOrm(facade),`:"",le=Z?"config.hyperdriveGlobal":"config.d1",Ot=T?` const bookmark = this.getInboundBookmark();
1383
1386
  const globalRequest = {
1384
1387
  ...this.globalCdcOptions(config.cdc ?? false),
1385
1388
  ...(bookmark === undefined ? {} : { bookmark }),
@@ -1388,14 +1391,14 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1388
1391
  ...(userId === undefined ? {} : { userId }),
1389
1392
  };
1390
1393
  const globalDb: DatabaseWriterLike = ${le}?.(env, globalRequest) ?? globalDbStub;
1391
- `:"",Dt=Wr(p&&T,le),Tt=h?` protected override roomHandlerPath(topic: string): string | undefined {
1394
+ `:"",Dt=Hr(f&&T,le),Tt=m?` protected override roomHandlerPath(topic: string): string | undefined {
1392
1395
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1393
1396
  return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1394
1397
  }
1395
1398
  `:"",_t=g?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1396
1399
  return LUNORA_SOCKETS[path];
1397
1400
  }
1398
- `:"",{externalSourceOverride:Et,sourceBootstrap:It,sourceClientCacheConst:Ct}=Kr(P),Lt=`
1401
+ `:"",{externalSourceOverride:Et,sourceBootstrap:It,sourceClientCacheConst:Ct}=Vr(P),Lt=`
1399
1402
  private shardInitDeferred = false;
1400
1403
  private deferredShardInit?: Promise<void>;
1401
1404
 
@@ -1504,7 +1507,7 @@ ${It}${Pt} }
1504
1507
  `:"",$t=ue===""?`
1505
1508
 
1506
1509
  `:`${ue}
1507
- `,Mt=H?`
1510
+ `,Mt=V?`
1508
1511
  protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
1509
1512
  const registered = LUNORA_FUNCTIONS[functionPath];${D?`
1510
1513
  const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
@@ -1519,20 +1522,20 @@ ${It}${Pt} }
1519
1522
 
1520
1523
  `:"",qt=Er(c),Ft=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1521
1524
  if (preparation !== undefined) await preparation;
1522
- `:"",Ut=Cr.replace("__PREPARE_FUNCTION__",Ft),Bt=Pr(h,c),jt=ee?`
1525
+ `:"",Ut=Cr.replace("__PREPARE_FUNCTION__",Ft),Bt=Pr(m,c),jt=te?`
1523
1526
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1524
- ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
1527
+ ${d.tables.map(a=>` facade[${JSON.stringify(a.name)}] = bindTableFacade(db, ${JSON.stringify(a.name)});`).join(`
1525
1528
  `)}
1526
- `:"",Wt=`${k.everyBuild}${L.build}${Q.build}
1529
+ `:"",Wt=`${k.everyBuild}${L.build}${J.build}
1527
1530
  const secrets = createSecrets(env);
1528
- `,Kt=`${k.everyFields}${L.contextField}${G.contextField}${Q.contextField}
1529
- secrets,`,Ht=G.build,Vt=A?`
1531
+ `,Kt=`${k.everyFields}${L.contextField}${Q.contextField}${J.contextField}
1532
+ secrets,`,Ht=Q.build,Vt=A?`
1530
1533
  const live = {
1531
1534
  publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
1532
1535
  await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1533
1536
  },
1534
1537
  };
1535
- `:"",Gt=[...k.actionFields,...C.length>0?["services"]:[],...A?["live"]:[]],Qt=`${k.actionBuild}${J.build}${Vt}`;return`${Sr}${N.join(`
1538
+ `:"",Gt=[...k.actionFields,...C.length>0?["services"]:[],...A?["live"]:[]],Qt=`${k.actionBuild}${Y.build}${Vt}`;return`${Sr}${N.join(`
1536
1539
  `)}
1537
1540
 
1538
1541
  type FunctionKind = "action" | "mutation" | "query";
@@ -1542,13 +1545,13 @@ interface FunctionReference {
1542
1545
  }
1543
1546
 
1544
1547
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1545
- const LUNORA_TABLE_REFS = ${u(et,"Record<string, Record<string, string>>")};
1548
+ const LUNORA_TABLE_REFS = ${p(et,"Record<string, Record<string, string>>")};
1546
1549
 
1547
1550
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1548
- const LUNORA_TABLE_INDEXES = ${u(tt,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1551
+ const LUNORA_TABLE_INDEXES = ${p(tt,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1549
1552
 
1550
1553
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1551
- const LUNORA_TABLE_COLUMNS = ${u(rt,`Record<
1554
+ const LUNORA_TABLE_COLUMNS = ${p(rt,`Record<
1552
1555
  string,
1553
1556
  Array<{
1554
1557
  bucket?: string;
@@ -1565,16 +1568,16 @@ const LUNORA_TABLE_COLUMNS = ${u(rt,`Record<
1565
1568
  >`)};
1566
1569
 
1567
1570
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1568
- const LUNORA_STORAGE_COLUMNS = ${u(nt,"Record<string, string[]>")};
1571
+ const LUNORA_STORAGE_COLUMNS = ${p(nt,"Record<string, string[]>")};
1569
1572
 
1570
1573
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1571
1574
  const LUNORA_TTL_SWEEPS = ${Zt(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1572
1575
 
1573
1576
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1574
- const LUNORA_ADVISORY_RULES = ${u(Ke,"Record<string, Partial<AdvisoryFinding>>")};
1577
+ const LUNORA_ADVISORY_RULES = ${p(Ke,"Record<string, Partial<AdvisoryFinding>>")};
1575
1578
 
1576
1579
  /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1577
- const LUNORA_ADVISORY_ROWS = ${u(He,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1580
+ const LUNORA_ADVISORY_ROWS = ${p(He,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1578
1581
 
1579
1582
  const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1580
1583
  let cached: AdvisoryFinding[] | undefined;
@@ -1582,23 +1585,23 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1582
1585
  })();
1583
1586
 
1584
1587
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1585
- const LUNORA_ADVISOR_PROCEDURES = ${u(Ve,"AdvisorProcedure[]")};
1588
+ const LUNORA_ADVISOR_PROCEDURES = ${p(Ve,"AdvisorProcedure[]")};
1586
1589
 
1587
1590
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1588
- const LUNORA_RLS_METADATA = ${u(ne,"RlsPoliciesResult")};
1591
+ const LUNORA_RLS_METADATA = ${p(ne,"RlsPoliciesResult")};
1589
1592
  ${ot}
1590
1593
  /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1591
- const LUNORA_MASK_METADATA = ${u(Ge,"MaskPoliciesResult")};
1594
+ const LUNORA_MASK_METADATA = ${p(Ge,"MaskPoliciesResult")};
1592
1595
 
1593
1596
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1594
- const LUNORA_STORAGE_RULES = ${u(Qe,"StorageRulesResult")};
1597
+ const LUNORA_STORAGE_RULES = ${p(Qe,"StorageRulesResult")};
1595
1598
 
1596
1599
  /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1597
- const LUNORA_STUDIO_FEATURES = ${u(Je,"StudioFeaturesResult")};
1600
+ const LUNORA_STUDIO_FEATURES = ${p(Je,"StudioFeaturesResult")};
1598
1601
 
1599
1602
  /** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
1600
1603
  const BLOCKED_MIGRATION_RETRY_MS = 5000;
1601
- ${ge}${z.constant}${V.constant}${Ye}${Xe}${_e}${Le}${ke}${Ae}${J.specs}${Me}
1604
+ ${ge}${X.constant}${G.constant}${Ye}${Xe}${_e}${Le}${ke}${Ae}${Y.specs}${Me}
1602
1605
  export interface ShardDOConfig {
1603
1606
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1604
1607
  cdc?: boolean;
@@ -1615,7 +1618,7 @@ export interface ShardDOConfig {
1615
1618
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1616
1619
  scheduler?: (env: Record<string, unknown>) => unknown;
1617
1620
  /** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
1618
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ht}${k.configFields}${L.configField}${Fe}${pt}${mt}${ft}${z.configField}
1621
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ht}${k.configFields}${L.configField}${Fe}${pt}${mt}${ft}${X.configField}
1619
1622
  }
1620
1623
  ${$("schedulerStub",bt,["cancel","runAfter","runAt"])}${$("storageStub",yt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${wt}${Ct}${St}${k.stubs}${je}
1621
1624
  ${qt}
@@ -1635,7 +1638,7 @@ ${at}${dt}${Dt}${Et}
1635
1638
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1636
1639
  return LUNORA_LIFECYCLE_HOOKS[event];
1637
1640
  }
1638
- ${Tt}${_t}${ce}${z.override}${Lt}
1641
+ ${Tt}${_t}${ce}${X.override}${Lt}
1639
1642
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1640
1643
  // socket-terminated half of the same reactivity — and differs only in who
1641
1644
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1734,7 +1737,7 @@ ${c?` const requestScope = this.captureRequestScope();
1734
1737
  protected override studioFeatures(): StudioFeaturesResult {
1735
1738
  return LUNORA_STUDIO_FEATURES();
1736
1739
  }
1737
- ${V.evaluateOverride}${V.subscriptionOverride}${ze}${Ze}
1740
+ ${G.evaluateOverride}${G.subscriptionOverride}${ze}${Ze}
1738
1741
  protected override advisories(): AdvisoryFinding[] {
1739
1742
  return LUNORA_ADVISORIES();
1740
1743
  }
@@ -1781,7 +1784,7 @@ ${Tr}
1781
1784
  throw new LunoraError("INTERNAL", this.blockedUniqueIndexes.join("; "));
1782
1785
  }
1783
1786
  }
1784
- ${Z?`
1787
+ ${ee?`
1785
1788
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1786
1789
  // Migrations create the fts5 companions; without them every backfill
1787
1790
  // statement would raise "no such table" on a shard that has never
@@ -1791,6 +1794,6 @@ ${Z?`
1791
1794
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1792
1795
  }
1793
1796
  `:""}${vt}
1794
- ${_r({hasSensitiveArgs:H,lazyFunctions:c,actionOnlyFields:Gt,agentsBuild:Pe,agentsContextField:Ne,containersBuild:Oe,containersContextField:De,databaseOptions:Rt,everyContextBuild:Wt,everyContextField:Kt,facadeBlock:jt,globalDatabaseLine:Ot,notifyBuild:Ht,ormContextField:At,paymentsBuild:qe,paymentsContextField:Ue,queuesBuild:ye,queuesContextField:we,topicsBuild:Se,topicsContextField:Re,vectorsBuild:kt,vectorsContextField:xt,workflowsBuild:Ee,workflowsContextField:Ie,actionOnlyBuild:Qt})}
1797
+ ${_r({hasSensitiveArgs:V,lazyFunctions:c,actionOnlyFields:Gt,agentsBuild:Pe,agentsContextField:Ne,containersBuild:Oe,containersContextField:De,databaseOptions:Rt,everyContextBuild:Wt,everyContextField:Kt,facadeBlock:jt,globalDatabaseLine:Ot,notifyBuild:Ht,ormContextField:At,paymentsBuild:qe,paymentsContextField:Ue,queuesBuild:ye,queuesContextField:we,topicsBuild:Se,topicsContextField:Re,vectorsBuild:kt,vectorsContextField:xt,workflowsBuild:Ee,workflowsContextField:Ie,actionOnlyBuild:Qt})}
1795
1798
  };
1796
- `};export{$r as b,on as e};
1799
+ `};export{$r as b,cn as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.351",
3
+ "version": "1.0.0-alpha.353",
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.255",
54
- "@lunora/agent": "1.0.0-alpha.245",
55
- "@lunora/container": "1.0.0-alpha.91",
53
+ "@lunora/advisor": "1.0.0-alpha.257",
54
+ "@lunora/agent": "1.0.0-alpha.247",
55
+ "@lunora/container": "1.0.0-alpha.92",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
- "@lunora/platform": "1.0.0-alpha.74",
58
- "@lunora/queue": "1.0.0-alpha.126",
59
- "@lunora/scheduler": "1.0.0-alpha.149",
60
- "@lunora/values": "1.0.0-alpha.80",
61
- "@lunora/workflow": "1.0.0-alpha.94",
57
+ "@lunora/platform": "1.0.0-alpha.75",
58
+ "@lunora/queue": "1.0.0-alpha.128",
59
+ "@lunora/scheduler": "1.0.0-alpha.151",
60
+ "@lunora/values": "1.0.0-alpha.81",
61
+ "@lunora/workflow": "1.0.0-alpha.95",
62
62
  "@visulima/fs": "6.0.29",
63
63
  "jiti": "^2.7.0",
64
64
  "quicktype-core": "^26.0.0",