@lunora/codegen 1.0.0-alpha.370 → 1.0.0-alpha.372

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-SplX7j_9.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DKYJ2K4t.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CN8HACEL.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-BdEY3nbv.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-Hy2UrcrN.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-Cn3087D8.mjs";import{default as J}from"./packem_shared/discoverInserts-DIzIGlyG.mjs";import{d as X}from"./packem_shared/index-Cm7HdvL5.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-PNPCtUl2.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-HXIKioYv.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-KjOdhrk6.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4N8iXlU.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-DhOEyJLg.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-CzDMr_iP.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-Cju685VK.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CTR_g_IE.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-DDRbBN-I.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as gr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-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-CD4hPtUP.mjs";import{e as Ur}from"./packem_shared/server-DC4PW_2M.mjs";import{e as Hr}from"./packem_shared/shard-D9_wgrV7.mjs";import{G as Br}from"./packem_shared/shared-Br_OnErI.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{t as Yr,u as Xr,v as Zr}from"./packem_shared/shard-runtime-B9K29SyO.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-CCjh0ICg.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-CY8IQfAI.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-Bba2y2yt.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-C3WOlVN0.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,gr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DKYJ2K4t.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CN8HACEL.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-BdEY3nbv.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-Hy2UrcrN.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-Cn3087D8.mjs";import{default as J}from"./packem_shared/discoverInserts-DIzIGlyG.mjs";import{d as X}from"./packem_shared/index-Cm7HdvL5.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-PNPCtUl2.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-HXIKioYv.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-KjOdhrk6.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4N8iXlU.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-DhOEyJLg.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-HgQGUETJ.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-Cju685VK.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CTR_g_IE.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-QK5plNRi.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as gr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-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-CD4hPtUP.mjs";import{e as Ur}from"./packem_shared/server-DC4PW_2M.mjs";import{e as Hr}from"./packem_shared/shard-CSK4o67d.mjs";import{G as Br}from"./packem_shared/shared-Br_OnErI.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{t as Yr,u as Xr,v as Zr}from"./packem_shared/shard-runtime-B9K29SyO.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-CCjh0ICg.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-CY8IQfAI.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-Bba2y2yt.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-C3WOlVN0.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,gr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as z,readFileSync as Xe,mkdirSync as qt,writeFileSync as Sr,rmSync as Ne,readdirSync as Rn}from"node:fs";import{dirname as jt,join as E,relative as Fn}from"node:path";import{performance as xt}from"node:perf_hooks";import{runAdvisor as Ar}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as yr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as br}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ht,ts as Nr,VariableDeclarationKind as Gt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as de,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as Pr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Ln,limitNameOf as Dn,optionsObjectLiteral as Mn,handlerOf as wr,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Yt,returningFunctionOf as Ot,walkChain as Ir,RUN_METHODS as _n,functionReferenceSegments as Tr,isTestPath as Cr,isFunctionLike as oe,functionKeyOf as zn,withSourceListMemo as Or}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as M,g as Qt,c as S,a as tt,w as Xt,k as kr,l as Rr,h as Fr,m as Lr,j as kt,i as Dr}from"./attribution-DUbGYT4N.mjs";import{a as zs,r as St,i as Y,b as Mr,m as Kn,c as st,e as Jt,E as $n,C as Bn,d as _r,f as zr,g as Kr}from"./context-root-Bd08qiVR.mjs";import{a as I,i as Vn,c as te,d as Un,e as $r,f as Br,g as Wn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Vr}from"./property-name-7cBlgK_O.mjs";import{b as Ur,a as nt}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as Wr}from"./parse-validator-CP5CL6Q7.mjs";import qr from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as qn}from"./database-calls-BSyvN1No.mjs";import jr from"./discoverHyperdriveCalls-Cn3087D8.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as jn,d as Hr}from"./index-Cm7HdvL5.mjs";import{MUTATORS_FILENAME as Gr,isDefineMutatorCallee as Yr,mutatorServerImplOf as Qr,discoverMutators as Xr}from"./MUTATORS_FILENAME-PNPCtUl2.mjs";import Jr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Zr,discoverNotifyCalls as eo}from"./NOTIFY_FILENAME-HXIKioYv.mjs";import to from"./discoverR2sqlCalls-B4N8iXlU.mjs";import so from"./discoverRlsProcedures-DhOEyJLg.mjs";import{s as es,n as no}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as io,redact as ro,isHeuristicSecretKind as oo,isSecretishName as ao}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Hn,readMergeDurableObjects as co}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as lo,r as uo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as fo,discoverWorkflows as go}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as po}from"./json-data-Chfs2Cz5.mjs";import{a as mo,I as ho,g as vo,G as Gn,d as Eo,i as xo}from"./shared-Br_OnErI.mjs";import{createCodegenProject as So}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as zE,refreshCodegenProject as KE,tsconfigFingerprint as $E}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Ao,usedCapabilities as yo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Yn,isHyperdriveGlobalTable as Qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bo}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as No}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import Po from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as wo,fileWiresRequestSecretTool as Io,createTargetScope as To,discoverFeatureUsage as Co}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Xn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Oo,findProjectConfigFile as ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ro}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as Fo}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Lo}from"./readServiceBindings-BA49C6aN.mjs";import Do from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as Mo,readTargetDiagnostics as _o,vectorizeDimensionDiagnostics as zo,liveStreamsDeliveryAuthorizationDiagnostic as Ko,socketRoutesDeliveryAuthorizationDiagnostic as $o,studioPlatformFor as Bo,platformFeatureAvailable as Vo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Uo}from"./schema-BgM8A3XV.mjs";import{b as Jn,e as Wo}from"./shard-D9_wgrV7.mjs";import{e as qo,a as jo}from"./server-DC4PW_2M.mjs";import{emitDataModel as Ho}from"./emitDataModel-Bba2y2yt.mjs";import{i as Go,a as Yo,e as Qo,b as Xo,d as Jo,c as Zo}from"./unwrap-handler-return-DTcee6Ng.mjs";import ea from"./discoverFunctions-BdEY3nbv.mjs";import ta from"./discoverHttpRoutes-Hy2UrcrN.mjs";import sa from"./discoverInserts-DIzIGlyG.mjs";import{e as Zn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import na from"./discoverMigrations-Bv8kNIgy.mjs";import ia from"./discoverQueries-KjOdhrk6.mjs";import ra from"./discoverRlsMetadata-Dq6iSXnC.mjs";import oa from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as aa}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as la,emitApp as da}from"./emitApp-CzDMr_iP.mjs";import{readJsonSync as ua}from"@visulima/fs";import{buildSchemaSnapshot as fa}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as ga,emitOpenApiModule as pa}from"./buildOpenApiDocument-Cju685VK.mjs";import{buildOpenRpcDocument as ma,emitOpenRpcModule as ha}from"./OPENRPC_VERSION-CTR_g_IE.mjs";import{w as va,u as Ea,v as xa,t as Sa,x as Aa}from"./shard-runtime-B9K29SyO.mjs";import{emitCollections as ya,emitSeed as ba,emitApi as Na,emitInternalApi as Pa}from"./emitApi-CCjh0ICg.mjs";import{emitCrons as wa,emitScheduler as Ia,emitShardRegistry as Ta,emitDurableObjects as Ca,emitVectors as Oa,emitWranglerCronTriggers as ka}from"./emitCrons-CY8IQfAI.mjs";import Ra from"./emitDrizzleSchema-CD4hPtUP.mjs";import{LAZY_FUNCTION_DIRECTORY as ei,emitFunctions as Fa,emitLazyFunctionModules as La}from"./emitFunctions-C3WOlVN0.mjs";const Da=(e,t=!1)=>{if(e.length===0)return"";const s=Eo(t),n=e.map(c=>{if(mo(c.exportName,"live stream export name"),!ho.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{vo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as z,readFileSync as Xe,mkdirSync as qt,writeFileSync as Sr,rmSync as Ne,readdirSync as Rn}from"node:fs";import{dirname as jt,join as E,relative as Fn}from"node:path";import{performance as xt}from"node:perf_hooks";import{runAdvisor as Ar}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as yr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as br}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ht,ts as Nr,VariableDeclarationKind as Gt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as de,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as Pr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Ln,limitNameOf as Dn,optionsObjectLiteral as Mn,handlerOf as wr,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Yt,returningFunctionOf as Ot,walkChain as Ir,RUN_METHODS as _n,functionReferenceSegments as Tr,isTestPath as Cr,isFunctionLike as oe,functionKeyOf as zn,withSourceListMemo as Or}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as M,g as Qt,c as S,a as tt,w as Xt,k as kr,l as Rr,h as Fr,m as Lr,j as kt,i as Dr}from"./attribution-DUbGYT4N.mjs";import{a as zs,r as St,i as Y,b as Mr,m as Kn,c as st,e as Jt,E as $n,C as Bn,d as _r,f as zr,g as Kr}from"./context-root-Bd08qiVR.mjs";import{a as I,i as Vn,c as te,d as Un,e as $r,f as Br,g as Wn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Vr}from"./property-name-7cBlgK_O.mjs";import{b as Ur,a as nt}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as Wr}from"./parse-validator-CP5CL6Q7.mjs";import qr from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as qn}from"./database-calls-BSyvN1No.mjs";import jr from"./discoverHyperdriveCalls-Cn3087D8.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as jn,d as Hr}from"./index-Cm7HdvL5.mjs";import{MUTATORS_FILENAME as Gr,isDefineMutatorCallee as Yr,mutatorServerImplOf as Qr,discoverMutators as Xr}from"./MUTATORS_FILENAME-PNPCtUl2.mjs";import Jr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Zr,discoverNotifyCalls as eo}from"./NOTIFY_FILENAME-HXIKioYv.mjs";import to from"./discoverR2sqlCalls-B4N8iXlU.mjs";import so from"./discoverRlsProcedures-DhOEyJLg.mjs";import{s as es,n as no}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as io,redact as ro,isHeuristicSecretKind as oo,isSecretishName as ao}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Hn,readMergeDurableObjects as co}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as lo,r as uo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as fo,discoverWorkflows as go}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as po}from"./json-data-Chfs2Cz5.mjs";import{a as mo,I as ho,g as vo,G as Gn,d as Eo,i as xo}from"./shared-Br_OnErI.mjs";import{createCodegenProject as So}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as zE,refreshCodegenProject as KE,tsconfigFingerprint as $E}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Ao,usedCapabilities as yo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Yn,isHyperdriveGlobalTable as Qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bo}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as No}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import Po from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as wo,fileWiresRequestSecretTool as Io,createTargetScope as To,discoverFeatureUsage as Co}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Xn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Oo,findProjectConfigFile as ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ro}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as Fo}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Lo}from"./readServiceBindings-BA49C6aN.mjs";import Do from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as Mo,readTargetDiagnostics as _o,vectorizeDimensionDiagnostics as zo,liveStreamsDeliveryAuthorizationDiagnostic as Ko,socketRoutesDeliveryAuthorizationDiagnostic as $o,studioPlatformFor as Bo,platformFeatureAvailable as Vo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Uo}from"./schema-BgM8A3XV.mjs";import{b as Jn,e as Wo}from"./shard-CSK4o67d.mjs";import{e as qo,a as jo}from"./server-DC4PW_2M.mjs";import{emitDataModel as Ho}from"./emitDataModel-Bba2y2yt.mjs";import{i as Go,a as Yo,e as Qo,b as Xo,d as Jo,c as Zo}from"./unwrap-handler-return-DTcee6Ng.mjs";import ea from"./discoverFunctions-BdEY3nbv.mjs";import ta from"./discoverHttpRoutes-Hy2UrcrN.mjs";import sa from"./discoverInserts-DIzIGlyG.mjs";import{e as Zn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import na from"./discoverMigrations-Bv8kNIgy.mjs";import ia from"./discoverQueries-KjOdhrk6.mjs";import ra from"./discoverRlsMetadata-Dq6iSXnC.mjs";import oa from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as aa}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as la,emitApp as da}from"./emitApp-HgQGUETJ.mjs";import{readJsonSync as ua}from"@visulima/fs";import{buildSchemaSnapshot as fa}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as ga,emitOpenApiModule as pa}from"./buildOpenApiDocument-Cju685VK.mjs";import{buildOpenRpcDocument as ma,emitOpenRpcModule as ha}from"./OPENRPC_VERSION-CTR_g_IE.mjs";import{w as va,u as Ea,v as xa,t as Sa,x as Aa}from"./shard-runtime-B9K29SyO.mjs";import{emitCollections as ya,emitSeed as ba,emitApi as Na,emitInternalApi as Pa}from"./emitApi-CCjh0ICg.mjs";import{emitCrons as wa,emitScheduler as Ia,emitShardRegistry as Ta,emitDurableObjects as Ca,emitVectors as Oa,emitWranglerCronTriggers as ka}from"./emitCrons-CY8IQfAI.mjs";import Ra from"./emitDrizzleSchema-CD4hPtUP.mjs";import{LAZY_FUNCTION_DIRECTORY as ei,emitFunctions as Fa,emitLazyFunctionModules as La}from"./emitFunctions-C3WOlVN0.mjs";const Da=(e,t=!1)=>{if(e.length===0)return"";const s=Eo(t),n=e.map(c=>{if(mo(c.exportName,"live stream export name"),!ho.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{vo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${v}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -1,4 +1,4 @@
1
- import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as q}from"./schema-BgM8A3XV.mjs";import{a as N,I,G as y}from"./shared-Br_OnErI.mjs";const L={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...T.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[L]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>q(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,j=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as T}from"./schema-BgM8A3XV.mjs";import{a as N,I,G as y}from"./shared-Br_OnErI.mjs";const L={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...q.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[L]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(t=>T(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,j=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);
@@ -339,7 +339,7 @@ const buildGlobalCdcApplier =
339
339
 
340
340
  return request.changes.length;
341
341
  };
342
- `:"",$=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],M=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...c(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],B=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
342
+ `:"",$=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],M=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...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>;"]:[]],B=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
343
343
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
344
344
  this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
345
345
 
@@ -398,7 +398,7 @@ const buildGlobalCdcApplier =
398
398
  this.shardSelector = selector;
399
399
 
400
400
  return this;
401
- }`,...c(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. */
401
+ }`,...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. */
402
402
  public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
403
403
  this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
404
404
 
@@ -408,7 +408,7 @@ const buildGlobalCdcApplier =
408
408
  this.storageDeclaration = declaration;
409
409
 
410
410
  return this;
411
- }`]:[],...B(e)],W=e=>{const t=a=>e.hasScheduler?`
411
+ }`]:[],...B(e)],H=e=>{const t=a=>e.hasScheduler?`
412
412
  ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
413
413
  ? {
414
414
  d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
@@ -488,10 +488,10 @@ const buildGlobalCdcApplier =
488
488
  ? {
489
489
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
490
490
  }
491
- : {}),`]:[],...c(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
491
+ : {}),`]:[],...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) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
492
492
  ${r.join(`
493
493
  `)}
494
- `:""},H=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],U=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],F=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],z=e=>e?['import notifyConfig from "../notify.js";']:[],K=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],V=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Y=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((n,u)=>n.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},X=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:o,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:n}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...U(t,r),...J(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...F(o),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...n?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...K(e),...Y(e),"",...H(e.identity),...V(e),...a||s?['import schema from "../schema.js";']:[],...z(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},Z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
494
+ `:""},W=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],U=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],F=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],z=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],J=e=>e?['import notifyConfig from "../notify.js";']:[],K=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],V=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Y=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],c=[...r||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((s,u)=>s.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},X=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:s}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...U(t,r),...z(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...F(o),...Q(e.hasVectors),...d?['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";']:[],...K(e),...Y(e),"",...W(e.identity),...V(e),...a||n?['import schema from "../schema.js";']:[],...J(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},Z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
495
495
  // The schema's jurisdiction pins the auth object like every other DO.
496
496
  jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",ee=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,te=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
497
497
  ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${ee(t.shardMode)}],`).join(`
@@ -499,14 +499,14 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${ee(t.shardMode)}],`
499
499
  ]);
500
500
 
501
501
  options.listSchemaTables = () => [...tableSharding.keys()];
502
- options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...c(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
502
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...l(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
503
503
 
504
504
  if (shardRegistry) {
505
505
  options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
506
- }`]:[]],S=e=>(e.liveStreamDeclarations??[]).map(t=>{if(N(t.exportName,"live stream export name"),!I.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}) },`}),re=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ae=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],se=e=>p(e)?`liveStreamRouter([
506
+ }`]:[]],S=e=>(e.liveStreamDeclarations??[]).map(t=>{if(N(t.exportName,"live stream export name"),!I.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}) },`}),re=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ae=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ne=e=>p(e)?`liveStreamRouter([
507
507
  ${S(e).join(`
508
508
  `)}
509
- ], host)`:"host",ne=e=>[...te(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
509
+ ], host)`:"host",se=e=>[...te(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
510
510
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
511
511
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
512
512
  const source = workflowEnv as Record<string, unknown>;
@@ -609,7 +609,7 @@ ${S(e).join(`
609
609
  }`,...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
610
610
  // \`this.authDeclaration.namespace\` again below would be optional all over again.
611
611
  const authDeclaration = this.authDeclaration;
612
- const { authDiscoveryPathsFor, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest } = deferred.auth;
612
+ const { authDiscoveryPathsFor, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, resolveSessionIdentity } = deferred.auth;
613
613
  const authNamespace = authDeclaration?.namespace;
614
614
  const authD1 = authDeclaration?.d1;
615
615
 
@@ -668,39 +668,11 @@ ${S(e).join(`
668
668
  return null;
669
669
  }
670
670
 
671
- const session = await auth.api.getSession({ headers: (request as Request).headers });
672
-
673
- if (!session?.user?.id) {
674
- return null;
675
- }
676
-
677
- // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
678
- // work on this wiring without a hand-written resolver. better-auth's
679
- // \`admin()\` plugin owns that column (comma-joined for multiple roles)
680
- // and only an administrator can write it; it is absent when the plugin
681
- // is off, which reads as no roles.
682
- //
683
- // \`expiresAtMs\` is the socket credential expiry the runtime forwards
684
- // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
685
- // fires, so a signed-out, banned or lapsed user keeps streaming their
686
- // RLS-scoped rows over an already-open WebSocket while every HTTP call
687
- // is anonymous. better-auth hands back a \`Date\`; anything else means
688
- // the adapter did not hydrate it, and omitting beats guessing.
689
- const expiresAt = session.session.expiresAt;
690
- // \`email\` and \`name\` are the claims \`ctx.auth.getIdentity()\` is
691
- // documented to carry ("email, name, roles, custom claims"). Without
692
- // them the documented \`me\` query — \`identity?.email\` — resolves
693
- // \`undefined\` on the built-in wiring. Empty strings are dropped so an
694
- // absent claim reads as absent rather than as "".
695
- const user = session.user as { email?: unknown; name?: unknown; role?: unknown };
696
-
697
- return {
698
- ...(typeof user.email === "string" && user.email.length > 0 ? { email: user.email } : {}),
699
- ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
700
- ...(typeof user.name === "string" && user.name.length > 0 ? { name: user.name } : {}),
701
- role: user.role,
702
- userId: session.user.id,
703
- };
671
+ // \`resolveSessionIdentity\` is shared with the DO wiring, so both modes put
672
+ // the same claims (role, expiry, profile, and the active organization and
673
+ // team checked against membership) on the identity, and it is unit-tested
674
+ // where this template cannot be.
675
+ return resolveSessionIdentity(auth, (request as Request).headers);
704
676
  };
705
677
  const authInstance = getAuth();
706
678
 
@@ -803,10 +775,10 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
803
775
  };`]:[]],oe=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...e.hasQueue?[` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],...re(e),...ae(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],ie=e=>e?`
804
776
  /** The identity memo per \`env\` object, owned by one assembled worker. */
805
777
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
806
- `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,le=e=>{if(!E(e))return"";const r=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,s,o])=>[a,s,o]);return`
778
+ `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ce=e=>{if(!E(e))return"";const r=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n,o])=>[a,n,o]);return`
807
779
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
808
780
  interface DeferredModules {
809
- ${r.map(([a,s])=>` ${a}: ${s};`).join(`
781
+ ${r.map(([a,n])=>` ${a}: ${n};`).join(`
810
782
  `)}
811
783
  }
812
784
 
@@ -816,13 +788,13 @@ let deferredModules: Promise<DeferredModules> | undefined;
816
788
  const loadDeferredModules = (): Promise<DeferredModules> =>
817
789
  (deferredModules ??= (async (): Promise<DeferredModules> => {
818
790
  return {
819
- ${r.map(([a,,s])=>` ${a}: ${s},`).join(`
791
+ ${r.map(([a,,n])=>` ${a}: ${n},`).join(`
820
792
  `)}
821
793
  };
822
794
  })());
823
- `},ce=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
824
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},be=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth/worker";
825
- `:"",de=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),me=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=$(r),o=ne(r),i=a?` let auth: LunoraAuth | null = null;
795
+ `},le=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
796
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},be=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
797
+ `:"",de=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),me=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,n=$(r),o=se(r),i=a?` let auth: LunoraAuth | null = null;
826
798
  let authInit: Promise<void> | null = null;
827
799
  // One memo per env for THIS assembled worker: a framework-hosted worker rebuilds its options per
828
800
  // request and must reuse it, but a second \`assemble()\` has its own auth closure and must not share.
@@ -880,9 +852,9 @@ ${r.map(([a,,s])=>` ${a}: ${s},`).join(`
880
852
  authInit = null;
881
853
  throw error;
882
854
  }));
883
- `:"",{asyncIfDeferred:l,deferredArgument:n,deferredParameter:u,loadDeferredLine:h}=ce(r),D=a?`
884
- await ensureAuth(env);`:"",b=`${a?"() => auth, identityMemos":"() => null"}${n}`,R=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,m=`env: Env${u}`,A=r.hasFramework?` const buildWorker = (${m}): LunoraWorker =>
885
- host ? withFrameworkWorker(${se(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${b})) : createWorker(this.buildWorkerOptions(env, ${b}));`:` const buildWorker = (${m}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${b}));`,x=r.hasFramework?"host?: FrameworkHostHandler":"",g=r.emailAgents??[],C=g.length>0?` composed.email = dispatchAgentEmail([
855
+ `:"",{asyncIfDeferred:c,deferredArgument:s,deferredParameter:u,loadDeferredLine:h}=le(r),D=a?`
856
+ await ensureAuth(env);`:"",b=`${a?"() => auth, identityMemos":"() => null"}${s}`,R=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,m=`env: Env${u}`,A=r.hasFramework?` const buildWorker = (${m}): LunoraWorker =>
857
+ host ? withFrameworkWorker(${ne(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${b})) : createWorker(this.buildWorkerOptions(env, ${b}));`:` const buildWorker = (${m}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${b}));`,x=r.hasFramework?"host?: FrameworkHostHandler":"",g=r.emailAgents??[],C=g.length>0?` composed.email = dispatchAgentEmail([
886
858
  ${g.map(v=>` { agent: lunoraAgentDefinitions.${v.exportName}, className: ${JSON.stringify(v.className)} },`).join(`
887
859
  `)}
888
860
  ]);
@@ -898,15 +870,15 @@ type Selector<Env, T> = (env: Env) => T | undefined;
898
870
 
899
871
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
900
872
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
901
- ${ie(a)}${le(r)}${r.jurisdiction?`
873
+ ${ie(a)}${ce(r)}${r.jurisdiction?`
902
874
  // Module scope, so every isolate loading this script (the worker and each Durable
903
875
  // Object class it exports) knows the schema's jurisdiction before a request runs.
904
876
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
905
877
  declareAppJurisdiction(${JSON.stringify(r.jurisdiction)});
906
878
  `:""}
907
- ${s.join(`
879
+ ${n.join(`
908
880
 
909
- `)}${s.length>0?`
881
+ `)}${n.length>0?`
910
882
 
911
883
  `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
912
884
  interface ComposedApp extends LunoraWorker {
@@ -936,7 +908,7 @@ ${O}
936
908
 
937
909
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
938
910
  private assemble(${x}): ComposedApp {
939
- const ShardDO = createShardDO({${W(r)}});
911
+ const ShardDO = createShardDO({${H(r)}});
940
912
 
941
913
  // Per-isolate singletons: the worker (and auth instance) are expensive to
942
914
  // build, so the first request constructs them and every later request on
@@ -949,22 +921,22 @@ ${A}
949
921
  ShardDO,
950
922
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
951
923
  const env = rawEnv as Env;${h}${D}
952
- worker ??= buildWorker(env${n});
924
+ worker ??= buildWorker(env${s});
953
925
 
954
926
  return worker.fetch(request, rawEnv, context);
955
927
  },
956
928
  scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}
957
- worker ??= buildWorker(rawEnv as Env${n});
929
+ worker ??= buildWorker(rawEnv as Env${s});
958
930
 
959
931
  return worker.scheduled(controller, rawEnv, context);
960
932
  },
961
- serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}
962
- worker ??= buildWorker(rawEnv as Env${n});
933
+ serverQuery: ${c}(request, rawEnv, reference, args, options) => {${h}
934
+ worker ??= buildWorker(rawEnv as Env${s});
963
935
 
964
936
  return worker.serverQuery(request, rawEnv, reference, args, options);
965
937
  },${r.hasQueue||r.hasFramework?`
966
938
  queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}
967
- worker ??= buildWorker(rawEnv as Env${n});
939
+ worker ??= buildWorker(rawEnv as Env${s});
968
940
 
969
941
  return worker.queue?.(batch, rawEnv, context);
970
942
  },`:""}
@@ -981,8 +953,8 @@ ${r.hasFramework?`
981
953
  // of its own the host's is the only one there is — forward to it rather than
982
954
  // dropping the entry.
983
955
  if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
984
- composed.email = ${l}(message, rawEnv, context) => {${h}
985
- worker ??= buildWorker(rawEnv as Env${n});
956
+ composed.email = ${c}(message, rawEnv, context) => {${h}
957
+ worker ??= buildWorker(rawEnv as Env${s});
986
958
 
987
959
  return worker.email?.(message, rawEnv, context) ?? Promise.resolve();
988
960
  };
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-D9_wgrV7.mjs";import"./shard-runtime-B9K29SyO.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CSK4o67d.mjs";import"./shard-runtime-B9K29SyO.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -432,6 +432,7 @@ ${c}
432
432
  newId: createStableIdFactory(stableKey, stableScope),
433
433
  // Only a mutation is a replay the key reproduces; a query or action carrying the header draws Math.random.
434
434
  random: createStableRandomFactory(contextKind === "mutation" ? stableKey : undefined, stableScope),
435
+ shardKey: this.currentShardKey(),
435
436
  // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
436
437
  // \`traceparent\` propagation, so time spent in a downstream service
437
438
  // is visible and its spans join this trace. Degrades to the bare
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.370",
3
+ "version": "1.0.0-alpha.372",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,13 +50,13 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "1.0.0-alpha.269",
54
- "@lunora/agent": "1.0.0-alpha.260",
53
+ "@lunora/advisor": "1.0.0-alpha.270",
54
+ "@lunora/agent": "1.0.0-alpha.261",
55
55
  "@lunora/container": "1.0.0-alpha.97",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
- "@lunora/platform": "1.0.0-alpha.75",
58
- "@lunora/queue": "1.0.0-alpha.131",
59
- "@lunora/scheduler": "1.0.0-alpha.155",
57
+ "@lunora/platform": "1.0.0-alpha.76",
58
+ "@lunora/queue": "1.0.0-alpha.132",
59
+ "@lunora/scheduler": "1.0.0-alpha.156",
60
60
  "@lunora/values": "1.0.0-alpha.85",
61
61
  "@lunora/workflow": "1.0.0-alpha.99",
62
62
  "@visulima/fs": "7.0.0",