@lunora/codegen 1.0.0-alpha.352 → 1.0.0-alpha.354
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 +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-DkUvvpG8.mjs → SCHEMA_SNAPSHOT_FILENAME-BQwNonnN.mjs} +1 -1
- package/dist/packem_shared/{discoverSchema-Cwt-DQgh.mjs → discoverSchema-CGAFQxFU.mjs} +1 -1
- package/dist/packem_shared/{emitApp-C7eHrv9C.mjs → emitApp-C0shqv7S.mjs} +5 -2
- package/dist/packem_shared/{emitShard-DEZcDjgF.mjs → emitShard-CYjlTMmT.mjs} +1 -1
- package/dist/packem_shared/{schemaFromIr-BWFnvCVg.mjs → schemaFromIr-CByOxuZb.mjs} +1 -1
- package/dist/packem_shared/{shard-B5e5ovr_.mjs → shard-ByB2lGh0.mjs} +72 -69
- package/package.json +8 -8
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-
|
|
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-CGAFQxFU.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-BQwNonnN.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-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-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-
|
|
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-CGAFQxFU.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}: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as V}from"node:module";import{join as _}from"node:path";import{fileURLToPath as q}from"node:url";import{createJiti as J}from"jiti";import{findObjectProperty as u}from"./isTestPath-C3QumE88.mjs";import{r as U,p as K}from"./parse-validator-iVTounLK.mjs";import{R as W}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./property-name-7cBlgK_O.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},X=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:X(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},H=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Q=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},Y=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Q(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:H(e.shardMode),vectorIndexes:[]}},ee=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>Y(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},te=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ne=e=>{const t=te(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},re=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},se=(e,t)=>{const n=ne(e);if(n)try{const s=J(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=V(_(t,"noop.cjs"))(s.startsWith("file:")?q(s):s),o=re(r,n);return typeof o!="object"||o===null?void 0:ee(o)}catch{return}},ie=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&ie.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",oe=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},ae=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,le=/^(?:sqlite_|_cf_|__)/u,ce=/__(?:agg|rank|geo|fts)_/u,de=e=>le.test(e)||ce.test(e),fe=new Set(["cascade","restrict","set null"]),ue=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(ue.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(W.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(de(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},pe=e=>e&&fe.has(e)?e:void 0,ge=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},me=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},he=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?me(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?pe(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},be=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return he(s,w(e),a,o)},xe=e=>{const t=ge(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=be(s);r&&n.push(r)}return n},ye=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ve=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ee=e=>{const[t,n,s]=e,r=ve(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ye(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},Ie=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},we=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},ke=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Se=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Te=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Se(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},_e=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},A=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:oe(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Le=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(we(n));break}case"global":{e.shardMode="global",e.globalBackend=_e(n);break}case"index":{e.indexes.push(Ee(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Te(n));break}case"relations":{const r=n[0];r&&e.relations.push(...xe(r));break}case"searchIndex":{e.searchIndexes.push(Ie(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:A(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(A(n[0],"updatedAt"));break}case"ttl":{e.ttl=ke(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Ne=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Pe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,ae(t))},je=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Le(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=K(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=je(e,s,n),Ne(e,t,n.searchIndexes),Pe(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=U(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},$e=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},De=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:$e(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=De(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,ze=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Fe=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Me=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Re=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Ce=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Be=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Ve=(e,t)=>{const n=Me(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Be(n);return s?b(s,t.getName()):void 0}return n}},qe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Re(t))return t;const s=Ce(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Ve(a,t)}},Je=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ue=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},Ke=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{ze(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Fe(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},We=(e,t,n)=>M(e,Ue(n),Ke(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=qe(n);if(!s){if(t!==void 0){const o=se(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Je(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return We(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Xe=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},He=new Set(["eu","fedramp","us"]),Qe=e=>j(e,"jurisdiction","jurisdiction",He,'"eu", "us", or "fedramp"'),Ye=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},et=new Set(["required"]),tt=e=>j(e,"rls","rls mode",et,'"required"'),nt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},rt=(e,t)=>{if(t===void 0)return;const n=nt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},mt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(B.CallExpression).find(p=>{const O=p.getExpression();return i.isIdentifier(O)&&O.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=Xe(r,a,n);rt(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Qe(r),...Ye(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:tt(r),tables:a,vectorIndexes:T}};export{mt as default};
|
|
1
|
+
import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as V}from"node:module";import{join as _}from"node:path";import{fileURLToPath as q}from"node:url";import{createJiti as J}from"jiti";import{findObjectProperty as u}from"./isTestPath-C3QumE88.mjs";import{r as U,p as K}from"./parse-validator-iVTounLK.mjs";import{R as W}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./property-name-7cBlgK_O.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},X=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:X(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},H=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Q=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},Y=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Q(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:H(e.shardMode),vectorIndexes:[]}},ee=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>Y(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},te=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ne=e=>{const t=te(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},re=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},se=(e,t)=>{const n=ne(e);if(n)try{const s=J(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=V(_(t,"noop.cjs"))(s.startsWith("file:")?q(s):s),o=re(r,n);return typeof o!="object"||o===null?void 0:ee(o)}catch{return}},ie=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&ie.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",oe=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},ae=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,le=/^(?:sqlite_|_cf_|__)/u,ce=/__(?:agg|rank|geo|fts)_/u,de=e=>le.test(e)||ce.test(e),fe=new Set(["cascade","restrict","set null"]),ue=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(ue.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(W.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(de(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},pe=e=>e&&fe.has(e)?e:void 0,ge=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},me=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},he=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?me(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?pe(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},be=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return he(s,w(e),a,o)},xe=e=>{const t=ge(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=be(s);r&&n.push(r)}return n},ye=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ve=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ee=e=>{const[t,n,s]=e,r=ve(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ye(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},Ie=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},we=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},ke=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Se=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Te=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Se(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},_e=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},A=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:oe(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Le=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(we(n));break}case"global":{e.shardMode="global",e.globalBackend=_e(n);break}case"index":{e.indexes.unshift(Ee(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Te(n));break}case"relations":{const r=n[0];r&&e.relations.push(...xe(r));break}case"searchIndex":{e.searchIndexes.push(Ie(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:A(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(A(n[0],"updatedAt"));break}case"ttl":{e.ttl=ke(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Ne=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Pe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,ae(t))},je=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Le(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=K(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=je(e,s,n),Ne(e,t,n.searchIndexes),Pe(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=U(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},$e=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},De=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:$e(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=De(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,ze=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Fe=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Me=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Re=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Ce=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Be=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Ve=(e,t)=>{const n=Me(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Be(n);return s?b(s,t.getName()):void 0}return n}},qe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Re(t))return t;const s=Ce(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Ve(a,t)}},Je=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ue=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},Ke=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{ze(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Fe(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},We=(e,t,n)=>M(e,Ue(n),Ke(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=qe(n);if(!s){if(t!==void 0){const o=se(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Je(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return We(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Xe=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},He=new Set(["eu","fedramp","us"]),Qe=e=>j(e,"jurisdiction","jurisdiction",He,'"eu", "us", or "fedramp"'),Ye=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},et=new Set(["required"]),tt=e=>j(e,"rls","rls mode",et,'"required"'),nt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},rt=(e,t)=>{if(t===void 0)return;const n=nt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},mt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(B.CallExpression).find(p=>{const O=p.getExpression();return i.isIdentifier(O)&&O.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=Xe(r,a,n);rt(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Qe(r),...Ye(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:tt(r),tables:a,vectorIndexes:T}};export{mt as default};
|
|
@@ -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 }),
|
|
@@ -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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-
|
|
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 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const o=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=o(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{indexes:a.indexes,shape:Object.fromEntries(Object.entries(a.shape).map(([l,s])=>[l,n(s)]))}]))});export{m as schemaFromIr};
|
|
@@ -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
|
|
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=(
|
|
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
|
-
|
|
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:
|
|
235
|
-
orm: databaseContext.orm,`,
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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(${
|
|
385
|
-
${
|
|
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
|
-
${
|
|
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,${
|
|
469
|
+
origin: requestOrigin,${W}
|
|
467
470
|
scheduler,
|
|
468
471
|
span,
|
|
469
472
|
storage: contextStorage,
|
|
470
|
-
trace,${v}${
|
|
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 },${
|
|
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(
|
|
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=
|
|
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=(
|
|
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
|
-
`:"",
|
|
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__",
|
|
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): ${
|
|
962
|
-
${
|
|
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
|
-
`:"",
|
|
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(
|
|
1027
|
-
`:"";return{customMutatorOverride:
|
|
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:
|
|
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
|
-
`:"",
|
|
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:
|
|
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:
|
|
1250
|
+
`:"",sourceClientCacheConst:r?`
|
|
1248
1251
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1249
1252
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1250
|
-
`:""}),
|
|
1251
|
-
`:"",
|
|
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:
|
|
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
|
-
${
|
|
1271
|
+
${s} const vectors = createContextVectors(lunora${u});
|
|
1269
1272
|
|
|
1270
1273
|
return {
|
|
1271
|
-
backfill: createVectorBackfillSync({ ${
|
|
1272
|
-
onWrite: createVectorSyncHook({ ${
|
|
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:
|
|
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(
|
|
1298
|
-
return { ${_.map(
|
|
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(
|
|
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 { ${
|
|
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=
|
|
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}=
|
|
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=
|
|
1382
|
-
orm: bindOrm(facade),`:"",le=
|
|
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=
|
|
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}=
|
|
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=
|
|
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(
|
|
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
|
-
${
|
|
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}${
|
|
1529
|
+
`:"",Wt=`${k.everyBuild}${L.build}${J.build}
|
|
1527
1530
|
const secrets = createSecrets(env);
|
|
1528
|
-
`,Kt=`${k.everyFields}${L.contextField}${
|
|
1529
|
-
secrets,`,Ht=
|
|
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}${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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 = ${
|
|
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}${
|
|
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}${
|
|
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}${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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:
|
|
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,
|
|
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.
|
|
3
|
+
"version": "1.0.0-alpha.354",
|
|
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.
|
|
54
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
55
|
-
"@lunora/container": "1.0.0-alpha.
|
|
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
57
|
"@lunora/platform": "1.0.0-alpha.75",
|
|
58
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
59
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
60
|
-
"@lunora/values": "1.0.0-alpha.
|
|
61
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
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",
|