@lunora/codegen 1.0.0-alpha.429 → 1.0.0-alpha.430
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-CoXEvSNg.mjs → SCHEMA_SNAPSHOT_FILENAME-C0ZU8cQz.mjs} +1 -1
- package/dist/packem_shared/{emitApp-BJxszWDO.mjs → emitApp-_YbbmtTw.mjs} +10 -6
- package/dist/packem_shared/{emitShard-CPaRxNYn.mjs → emitShard-DhgRjlEf.mjs} +1 -1
- package/dist/packem_shared/{shard-BbYT2omp.mjs → shard-WWiw5i1B.mjs} +94 -71
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-Bue5tbp6.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-BSW65Q9R.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-DJeZ18i9.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-DcvsgL5u.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-Dy3qWGfI.mjs";import{default as b}from"./packem_shared/discoverCrons-MpIC14pg.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-DFx_jlpa.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BcDkRoOu.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-CDaIBL6L.mjs";import{d as q}from"./packem_shared/index-BwLaIVqA.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-BtMgsfzG.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-B--Nvx36.mjs";import{default as ee}from"./packem_shared/discoverInserts-Dx7Lxey3.mjs";import{d as oe}from"./packem_shared/index-CQuAXbal.mjs";import{default as ie}from"./packem_shared/discoverMigrations-DaBdK1Bv.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-SLAN2VXq.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-MeKjo_UX.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-BlhMsXuk.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-CVkpGqoY.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-DHvclvkv.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-CUfhUqfY.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-CO-pRHOx.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-CdrJNRFd.mjs";import{default as Pe}from"./packem_shared/discoverSchema-CL9PLdOu.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-Cf4sum4C.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-D_pYyr1i.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{emitApp as qe}from"./packem_shared/emitApp-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-Bue5tbp6.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-BSW65Q9R.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-DJeZ18i9.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-DcvsgL5u.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-Dy3qWGfI.mjs";import{default as b}from"./packem_shared/discoverCrons-MpIC14pg.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-DFx_jlpa.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BcDkRoOu.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-CDaIBL6L.mjs";import{d as q}from"./packem_shared/index-BwLaIVqA.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-BtMgsfzG.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-B--Nvx36.mjs";import{default as ee}from"./packem_shared/discoverInserts-Dx7Lxey3.mjs";import{d as oe}from"./packem_shared/index-CQuAXbal.mjs";import{default as ie}from"./packem_shared/discoverMigrations-DaBdK1Bv.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-SLAN2VXq.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-MeKjo_UX.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-BlhMsXuk.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-CVkpGqoY.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-DHvclvkv.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-CUfhUqfY.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-CO-pRHOx.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-CdrJNRFd.mjs";import{default as Pe}from"./packem_shared/discoverSchema-CL9PLdOu.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-Cf4sum4C.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-D_pYyr1i.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{emitApp as qe}from"./packem_shared/emitApp-_YbbmtTw.mjs";import{isD1GlobalTable as Je,isHyperdriveGlobalTable as Xe}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as $e,emitOpenApi as er,emitOpenApiModule as rr}from"./packem_shared/buildOpenApiDocument-C3zlve6K.mjs";import{OPENRPC_VERSION as tr,buildOpenRpcDocument as ir,emitOpenRpc as ar,emitOpenRpcModule as sr}from"./packem_shared/OPENRPC_VERSION-DkWde9eh.mjs";import{DEFAULT_TARGET as fr,platformMatrixIds as mr,readProjectTarget as pr,resolveCodegenTarget as nr}from"./packem_shared/DEFAULT_TARGET-CnglMKg_.mjs";import{b as lr,r as Sr,c as xr,d as Er}from"./packem_shared/project-config-file-DR7xrrNB.mjs";import{PROJECT_CONFIG_FILENAMES as ur,findCodegenConfigFile as Nr,findProjectConfigFile as vr,projectConfigCandidatePaths as gr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Or,runCodegen as Ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-C0ZU8cQz.mjs";import{SchemaSnapshotParseError as Rr,buildSchemaSnapshot as Lr,evaluateSchemaDrift as Mr,indexReferencesOf as Tr,parseSchemaSnapshot as Fr}from"./packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs";import{default as Pr}from"./packem_shared/fingerprintSchemaSources-BqPD3mw0.mjs";import{schemaFromIr as yr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Gr,validatorIrToJsonSchema as Ur}from"./packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{SDK_LANGUAGES as Hr,SDK_TARGETS as jr,generateSdk as Vr}from"./sdk/index.mjs";import{redact as Wr,secretKindOf as zr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Qr}from"./packem_shared/emitDrizzleSchema-lRoq3OJs.mjs";import{e as qr}from"./packem_shared/server-Dfxmm5Zw.mjs";import{e as Jr}from"./packem_shared/shard-WWiw5i1B.mjs";import{G as Zr}from"./packem_shared/shared-Cn7dMQ_u.mjs";import{MESSAGE_SOLUTIONS as eo,findSolutionByMessage as ro}from"@lunora/errors";import{createCodegenProject as to,findTsconfig as io,refreshCodegenProject as ao,tsconfigFingerprint as so}from"./packem_shared/createCodegenProject-C4XuJSap.mjs";import{t as mo,u as po,v as no}from"./packem_shared/shard-runtime-G5mZQjY0.mjs";import{emitApi as lo,emitCollections as So,emitInternalApi as xo}from"./packem_shared/emitApi-lwadq5G7.mjs";import{emitCrons as Ao,emitScheduler as uo,emitVectors as No,emitWranglerCronTriggers as vo}from"./packem_shared/emitCrons-CCRKs482.mjs";import{emitDataModel as Co}from"./packem_shared/emitDataModel-Cen7mAmM.mjs";import{emitFunctions as Io}from"./packem_shared/emitFunctions-ppMX7E3X.mjs";import{isTypedSchema as Ro}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{I as AGENTS_FILENAME,ne as ALL_NOTIFY_CHANNELS,E as CAPABILITY_PROBES,u as COMPANION_BINDING,N as COMPANION_SERVICE_NAME,P as CONTAINERS_FILENAME,g as CodegenDiagnosticError,fr as DEFAULT_TARGET,U as ENV_FILENAME,K as FLAGS_FILENAME,Zr as GENERATED_HEADER,Gr as LUNORA_ERROR_CODES,eo as LUNORA_SOLUTION_RULES,se as MUTATORS_FILENAME,ce as NOTIFY_FILENAME,tr as OPENRPC_VERSION,ur as PROJECT_CONFIG_FILENAMES,ge as QUEUES_FILENAME,Or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Hr as SDK_LANGUAGES,jr as SDK_TARGETS,je as SHAPES_FILENAME,Rr as SchemaSnapshotParseError,e as VERSION,Ke as WORKFLOWS_FILENAME,$e as buildOpenApiDocument,ir as buildOpenRpcDocument,Lr as buildSchemaSnapshot,H as capabilitiesUsedBy,ye as companionServiceBinding,to as createCodegenProject,j as createTargetScope,n as describeErrorLevelFindings,C as diagnosticAt,i as diffSchemaSnapshots,_ as discoverAgents,F as discoverAuthApiCalls,D as discoverContainers,b as discoverCrons,Q as discoverFlags,q as discoverFunctions,J as discoverHttpRoutes,Z as discoverHyperdriveCalls,ee as discoverInserts,oe as discoverMaskProcedures,ie as discoverMigrations,de as discoverMutators,me as discoverNondeterministicCalls,le as discoverNotifyCalls,Se as discoverNotifyChannels,xe as discoverNotifyConfig,Ne as discoverQueries,Ce as discoverQueues,Ie as discoverR2sqlCalls,Me as discoverRlsMetadata,Re as discoverRlsProcedures,Fe as discoverSandboxUsage,Pe as discoverSchema,Ve as discoverShapes,We as discoverStorageRulesMetadata,Qe as discoverWorkflows,mo as emitAgents,lo as emitApi,qe as emitApp,So as emitCollections,po as emitContainers,Ao as emitCrons,Co as emitDataModel,Qr as emitDrizzleSchema,Io as emitFunctions,xo as emitInternalApi,er as emitOpenApi,rr as emitOpenApiModule,ar as emitOpenRpc,sr as emitOpenRpcModule,uo as emitScheduler,qr as emitServer,Jr as emitShard,No as emitVectors,no as emitWorkflows,vo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Mr as evaluateSchemaDrift,Nr as findCodegenConfigFile,ro as findLunoraSolution,vr as findProjectConfigFile,io as findTsconfig,Pr as fingerprintSchemaSources,V as foldCapabilitySignals,d as formatAdvisories,Vr as generateSdk,Tr as indexReferencesOf,Je as isD1GlobalTable,Xe as isHyperdriveGlobalTable,L as isTestPath,Ro as isTypedSchema,f as lintSchema,M as listLunoraSourceFiles,lr as loadProjectConfig,k as mayReadCapabilityContext,Fr as parseSchemaSnapshot,mr as platformMatrixIds,gr as projectConfigCandidatePaths,be as readBoundServiceBindings,Ge as readDevServiceBindings,Ae as readPackageDependencies,Sr as readProjectConfigLiterals,xr as readProjectLazyFunctions,Er as readProjectSecurityHeaders,pr as readProjectTarget,Ue as readServiceBindings,Wr as redact,ao as refreshCodegenProject,nr as resolveCodegenTarget,Be as resolveServiceBindings,Ir as runCodegen,yr as schemaFromIr,zr as secretKindOf,a as serializeSchemaSnapshot,S as sortedUniqueNames,W as sourceCapabilitySignals,m as toAdvisorContext,so as tsconfigFingerprint,Ur as validatorIrToJsonSchema};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as K,readFileSync as Ie,statSync as fi,realpathSync as To,mkdirSync as vt,writeFileSync as Co,rmSync as Ee,readdirSync as vs}from"node:fs";import{dirname as Se,join as E,relative as xe,sep as Es,basename as Ss,resolve as pi}from"node:path";import{performance as Vt}from"node:perf_hooks";import{RUNTIME_LINTS as Oo,STATIC_LINTS as ko,runAdvisor as Ro}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{serializeSchemaSnapshot as Lo}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Fo}from"./formatAdvisories-Bue5tbp6.mjs";import{Node as r,SyntaxKind as u,Project as Et,VariableDeclarationKind as xs,ts as T}from"ts-morph";import{listLunoraSourceFiles as b,lunoraRelativePath as C,declarationLineOf as gi,collectCallRows as R,descendantsOfKind as S,bindingKeyName as fe,findObjectProperty as V,collectSecurityCallRows as Do,propertyInitializer as M,listSecurityScanFiles as Ue,objectLiteralFromCallbackBody as mi,limitNameOf as hi,optionsObjectLiteral as vi,handlerOf as _o,memberAccessOf as ys,chainRootOf as St,unwrapExpression as v,collectNodeRows as ce,isConstDeclaration as J,outermostValueWrapper as O,isWriteTarget as Te,isSameNode as P,returningFunctionOf as Xt,walkChain as Mo,staticNumberValue as Ei,RUN_METHODS as As,functionReferenceSegments as Ko,isTestPath as $o,isFunctionLike as pe,functionKeyOf as Si,withSourceListMemo as zo}from"./isTestPath-DJeZ18i9.mjs";import{j as se,h as ee,c as N,a as bs,w as Ns,k as Bo,d as $,l as Vo,b as xi,f as Wo,m as Uo,g as Jt,i as jo}from"./attribution-B8xa6AeK.mjs";import{i as Y,a as Ne,r as qo,b as Ho,c as yi,d as Go,s as je,e as Yo,f as Qo,g as Xo}from"./ip-reads-D8rPYtZ6.mjs";import{e as Z,f as Jo,m as Ai,b as xt,g as yt,E as bi,C as Ni,d as wi,h as Zo,j as ea,a as ta}from"./context-root-CO8PbZi5.mjs";import{a as k,i as Pi,c as le,d as Ii,e as Ti,f as sa,b as na,g as ia,h as ra}from"./classify-procedure-call-BK_MMoue.mjs";import{a as y,s as ws}from"./property-name-7cBlgK_O.mjs";import{b as oa,a as Ci}from"./module-specifiers-BctA0m_p.mjs";import{r as At,s as aa}from"./parse-validator-BisfC8bR.mjs";import ca from"./discoverAuthApiCalls-DcvsgL5u.mjs";import{i as z,r as Oi}from"./database-calls-Cug60vT9.mjs";import{i as Zt,p as ki,w as la,d as da}from"./index-BwLaIVqA.mjs";import ua from"./discoverHyperdriveCalls-B--Nvx36.mjs";import{PROJECT_CONFIG_FILENAMES as fa,findProjectConfigFile as Ri,findCodegenConfigFile as pa}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as ga,createTargetScope as ma,fileWiresRequestSecretTool as ha,discoverFeatureUsage as va}from"./capabilitiesUsedBy-BcDkRoOu.mjs";import{diagnosticAt as Ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Ps,a as lt,s as Li,d as Ea}from"./index-CQuAXbal.mjs";import{MUTATORS_FILENAME as Sa,isDefineMutatorCallee as xa,mutatorServerImplOf as ya,discoverMutators as Aa}from"./MUTATORS_FILENAME-SLAN2VXq.mjs";import ba from"./discoverNondeterministicCalls-MeKjo_UX.mjs";import{discoverNotifyConfig as Na,discoverNotifyCalls as wa}from"./ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import Pa from"./discoverR2sqlCalls-DHvclvkv.mjs";import Ia from"./discoverRlsProcedures-CUfhUqfY.mjs";import{s as Is,n as Ta}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Ca,redact as Oa,isHeuristicSecretKind as ka,isSecretishName as Ra}from"./redact-Cy14LEnc.mjs";import{r as Fi,p as La,c as Fa,a as Da,e as _a,d as Ma}from"./project-config-file-DR7xrrNB.mjs";import{a as tt,d as Ka,r as $a}from"./modules-isOWiSYI.mjs";import{WORKFLOWS_FILENAME as za,discoverWorkflows as Ba}from"./WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{r as Va}from"./json-data-Chfs2Cz5.mjs";import{a as Wa,I as Ua,g as ja,G as Di,d as qa,i as Ha}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Ga}from"./createCodegenProject-C4XuJSap.mjs";import{findTsconfig as p0,refreshCodegenProject as g0,tsconfigFingerprint as m0}from"./createCodegenProject-C4XuJSap.mjs";import{wranglerString as Ya,wranglerValue as Qa,companionName as Xa,COMPANION_FILES as Ja}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Za,usedCapabilities as ec}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{isD1GlobalTable as _i,isHyperdriveGlobalTable as Mi}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as tc}from"./AGENTS_FILENAME-BSW65Q9R.mjs";import{discoverContainers as sc}from"./CONTAINERS_FILENAME-Dy3qWGfI.mjs";import nc from"./discoverCrons-MpIC14pg.mjs";import{discoverEnv as ic}from"./ENV_FILENAME-DFx_jlpa.mjs";import Ki from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as rc}from"./QUEUES_FILENAME-CVkpGqoY.mjs";import{discoverSandboxUsage as oc}from"./discoverSandboxUsage-CdrJNRFd.mjs";import{resolveServiceBindings as ac}from"./companionServiceBinding-BZjm486n.mjs";import cc from"./discoverStorageRulesMetadata-D_pYyr1i.mjs";import{resolveCodegenTarget as Fe,gatePlatformFeatures as lc,needsCloudflareModuleWalk as dc,readTargetDiagnostics as uc,vectorizeDimensionDiagnostics as fc,liveStreamsDeliveryAuthorizationDiagnostic as pc,socketRoutesDeliveryAuthorizationDiagnostic as gc,studioPlatformFor as mc,platformFeatureAvailable as hc,gateAdminTokenRevocation as vc}from"./DEFAULT_TARGET-CnglMKg_.mjs";import{i as Ec}from"./schema-BgM8A3XV.mjs";import{b as $i,e as Sc}from"./shard-
|
|
1
|
+
import{existsSync as K,readFileSync as Ie,statSync as fi,realpathSync as To,mkdirSync as vt,writeFileSync as Co,rmSync as Ee,readdirSync as vs}from"node:fs";import{dirname as Se,join as E,relative as xe,sep as Es,basename as Ss,resolve as pi}from"node:path";import{performance as Vt}from"node:perf_hooks";import{RUNTIME_LINTS as Oo,STATIC_LINTS as ko,runAdvisor as Ro}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{serializeSchemaSnapshot as Lo}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Fo}from"./formatAdvisories-Bue5tbp6.mjs";import{Node as r,SyntaxKind as u,Project as Et,VariableDeclarationKind as xs,ts as T}from"ts-morph";import{listLunoraSourceFiles as b,lunoraRelativePath as C,declarationLineOf as gi,collectCallRows as R,descendantsOfKind as S,bindingKeyName as fe,findObjectProperty as V,collectSecurityCallRows as Do,propertyInitializer as M,listSecurityScanFiles as Ue,objectLiteralFromCallbackBody as mi,limitNameOf as hi,optionsObjectLiteral as vi,handlerOf as _o,memberAccessOf as ys,chainRootOf as St,unwrapExpression as v,collectNodeRows as ce,isConstDeclaration as J,outermostValueWrapper as O,isWriteTarget as Te,isSameNode as P,returningFunctionOf as Xt,walkChain as Mo,staticNumberValue as Ei,RUN_METHODS as As,functionReferenceSegments as Ko,isTestPath as $o,isFunctionLike as pe,functionKeyOf as Si,withSourceListMemo as zo}from"./isTestPath-DJeZ18i9.mjs";import{j as se,h as ee,c as N,a as bs,w as Ns,k as Bo,d as $,l as Vo,b as xi,f as Wo,m as Uo,g as Jt,i as jo}from"./attribution-B8xa6AeK.mjs";import{i as Y,a as Ne,r as qo,b as Ho,c as yi,d as Go,s as je,e as Yo,f as Qo,g as Xo}from"./ip-reads-D8rPYtZ6.mjs";import{e as Z,f as Jo,m as Ai,b as xt,g as yt,E as bi,C as Ni,d as wi,h as Zo,j as ea,a as ta}from"./context-root-CO8PbZi5.mjs";import{a as k,i as Pi,c as le,d as Ii,e as Ti,f as sa,b as na,g as ia,h as ra}from"./classify-procedure-call-BK_MMoue.mjs";import{a as y,s as ws}from"./property-name-7cBlgK_O.mjs";import{b as oa,a as Ci}from"./module-specifiers-BctA0m_p.mjs";import{r as At,s as aa}from"./parse-validator-BisfC8bR.mjs";import ca from"./discoverAuthApiCalls-DcvsgL5u.mjs";import{i as z,r as Oi}from"./database-calls-Cug60vT9.mjs";import{i as Zt,p as ki,w as la,d as da}from"./index-BwLaIVqA.mjs";import ua from"./discoverHyperdriveCalls-B--Nvx36.mjs";import{PROJECT_CONFIG_FILENAMES as fa,findProjectConfigFile as Ri,findCodegenConfigFile as pa}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as ga,createTargetScope as ma,fileWiresRequestSecretTool as ha,discoverFeatureUsage as va}from"./capabilitiesUsedBy-BcDkRoOu.mjs";import{diagnosticAt as Ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Ps,a as lt,s as Li,d as Ea}from"./index-CQuAXbal.mjs";import{MUTATORS_FILENAME as Sa,isDefineMutatorCallee as xa,mutatorServerImplOf as ya,discoverMutators as Aa}from"./MUTATORS_FILENAME-SLAN2VXq.mjs";import ba from"./discoverNondeterministicCalls-MeKjo_UX.mjs";import{discoverNotifyConfig as Na,discoverNotifyCalls as wa}from"./ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import Pa from"./discoverR2sqlCalls-DHvclvkv.mjs";import Ia from"./discoverRlsProcedures-CUfhUqfY.mjs";import{s as Is,n as Ta}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Ca,redact as Oa,isHeuristicSecretKind as ka,isSecretishName as Ra}from"./redact-Cy14LEnc.mjs";import{r as Fi,p as La,c as Fa,a as Da,e as _a,d as Ma}from"./project-config-file-DR7xrrNB.mjs";import{a as tt,d as Ka,r as $a}from"./modules-isOWiSYI.mjs";import{WORKFLOWS_FILENAME as za,discoverWorkflows as Ba}from"./WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{r as Va}from"./json-data-Chfs2Cz5.mjs";import{a as Wa,I as Ua,g as ja,G as Di,d as qa,i as Ha}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Ga}from"./createCodegenProject-C4XuJSap.mjs";import{findTsconfig as p0,refreshCodegenProject as g0,tsconfigFingerprint as m0}from"./createCodegenProject-C4XuJSap.mjs";import{wranglerString as Ya,wranglerValue as Qa,companionName as Xa,COMPANION_FILES as Ja}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Za,usedCapabilities as ec}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{isD1GlobalTable as _i,isHyperdriveGlobalTable as Mi}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as tc}from"./AGENTS_FILENAME-BSW65Q9R.mjs";import{discoverContainers as sc}from"./CONTAINERS_FILENAME-Dy3qWGfI.mjs";import nc from"./discoverCrons-MpIC14pg.mjs";import{discoverEnv as ic}from"./ENV_FILENAME-DFx_jlpa.mjs";import Ki from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as rc}from"./QUEUES_FILENAME-CVkpGqoY.mjs";import{discoverSandboxUsage as oc}from"./discoverSandboxUsage-CdrJNRFd.mjs";import{resolveServiceBindings as ac}from"./companionServiceBinding-BZjm486n.mjs";import cc from"./discoverStorageRulesMetadata-D_pYyr1i.mjs";import{resolveCodegenTarget as Fe,gatePlatformFeatures as lc,needsCloudflareModuleWalk as dc,readTargetDiagnostics as uc,vectorizeDimensionDiagnostics as fc,liveStreamsDeliveryAuthorizationDiagnostic as pc,socketRoutesDeliveryAuthorizationDiagnostic as gc,studioPlatformFor as mc,platformFeatureAvailable as hc,gateAdminTokenRevocation as vc}from"./DEFAULT_TARGET-CnglMKg_.mjs";import{i as Ec}from"./schema-BgM8A3XV.mjs";import{b as $i,e as Sc}from"./shard-WWiw5i1B.mjs";import{e as xc,a as yc}from"./server-Dfxmm5Zw.mjs";import{emitDataModel as Ac}from"./emitDataModel-Cen7mAmM.mjs";import{i as bc,b as Nc,e as wc,d as Pc,f as Ic,c as Tc}from"./unwrap-handler-return-BnsKyz9W.mjs";import Cc from"./discoverHttpRoutes-BtMgsfzG.mjs";import Oc from"./discoverInserts-Dx7Lxey3.mjs";import{e as zi}from"./exported-procedure-chains-ej9ozyZB.mjs";import kc from"./discoverMigrations-DaBdK1Bv.mjs";import gn from"./discoverQueries-BlhMsXuk.mjs";import Rc from"./discoverRlsMetadata-CO-pRHOx.mjs";import Lc from"./discoverSchema-CL9PLdOu.mjs";import{discoverShapes as Fc}from"./SHAPES_FILENAME-Cf4sum4C.mjs";import{i as Dc}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as _c,emitApp as Mc}from"./emitApp-_YbbmtTw.mjs";import{readJsonSync as Kc}from"@visulima/fs";import{indexReferencesOf as $c,buildSchemaSnapshot as zc}from"./SchemaSnapshotParseError-CV7mmuPi.mjs";import{buildOpenApiDocument as Bc,emitOpenApiModule as Vc}from"./buildOpenApiDocument-C3zlve6K.mjs";import{buildOpenRpcDocument as Wc,emitOpenRpcModule as Uc}from"./OPENRPC_VERSION-DkWde9eh.mjs";import{w as jc,u as qc,v as Hc,t as Gc,x as Yc}from"./shard-runtime-G5mZQjY0.mjs";import{emitCollections as Qc,emitSeed as Xc,emitApi as Jc,emitInternalApi as Zc}from"./emitApi-lwadq5G7.mjs";import{emitCrons as el,emitScheduler as tl,emitAdminRevocations as sl,emitShardRegistry as nl,emitDurableObjects as il,emitVectors as rl,emitWranglerCronTriggers as ol}from"./emitCrons-CCRKs482.mjs";import al from"./emitDrizzleSchema-lRoq3OJs.mjs";import{LAZY_FUNCTION_DIRECTORY as Bi,emitFunctions as cl,emitLazyFunctionModules as ll}from"./emitFunctions-ppMX7E3X.mjs";const dl=(e,t=!1)=>{if(e.length===0)return"";const s=qa(t),n=e.map(c=>{if(Wa(c.exportName,"live stream export name"),!Ua.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(d=>{ja(d.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${d.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,g=JSON.stringify(c.id);if(d.fields.length===0)return` ${d.name}: (): ${p} => ({ __lunoraLive: ${g}, topic: ${JSON.stringify(d.name)} }),`;const h=d.fields.map(x=>`\${encodeURIComponent(key.${x})}`).join(":");return` ${d.name}: (key: LiveTopicKey<${f}>): ${p} => ({
|
|
2
2
|
__lunoraLive: ${g},
|
|
3
3
|
topic: \`${d.name}:${h}\`,
|
|
4
4
|
}),`});return` ${c.exportName}: {
|
|
@@ -115,7 +115,7 @@ import{APP_METHOD_CAPABILITIES as L}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";impor
|
|
|
115
115
|
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; customMetadata?: Record<string, string>; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
116
116
|
};
|
|
117
117
|
}
|
|
118
|
-
`:"",
|
|
118
|
+
`:"",W=e=>e?`
|
|
119
119
|
/**
|
|
120
120
|
* Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
|
|
121
121
|
*
|
|
@@ -409,7 +409,7 @@ const buildGlobalCdcApplier =
|
|
|
409
409
|
|
|
410
410
|
return request.changes.length;
|
|
411
411
|
};
|
|
412
|
-
`:"",
|
|
412
|
+
`:"",B=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],H=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...S(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...c(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],U=e=>k(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
|
|
413
413
|
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
|
|
414
414
|
this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
|
|
415
415
|
|
|
@@ -486,7 +486,7 @@ const buildGlobalCdcApplier =
|
|
|
486
486
|
}`]:[],...U(e)],Q=e=>{const t=a=>e.hasScheduler?`
|
|
487
487
|
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
488
488
|
? {
|
|
489
|
-
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null | undefined }) => {
|
|
489
|
+
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; onWrite?: (table: string) => void; userId?: string | null | undefined }) => {
|
|
490
490
|
const env = rawEnv as Env;
|
|
491
491
|
const database = this.globalDeclaration?.d1(env);
|
|
492
492
|
|
|
@@ -527,6 +527,9 @@ const buildGlobalCdcApplier =
|
|
|
527
527
|
// poll's changed-tables fast path is unreachable.
|
|
528
528
|
cdc: request?.cdc ?? false,
|
|
529
529
|
exec: buildExec(database, request?.bookmark, request?.onBookmark),
|
|
530
|
+
// Announces a trigger's write to another global table, which the shard's
|
|
531
|
+
// own broadcast cannot see. See \`SqlCtxDbOptions.onWrite\`.
|
|
532
|
+
...(request?.onWrite === undefined ? {} : { onWrite: request.onWrite }),
|
|
530
533
|
// The binding outlives this per-request writer, so the
|
|
531
534
|
// provisioning sweep runs once per isolate rather than
|
|
532
535
|
// once per request. See \`SqlCtxDbOptions.provisionScope\`.
|
|
@@ -537,7 +540,7 @@ const buildGlobalCdcApplier =
|
|
|
537
540
|
}
|
|
538
541
|
: {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
|
|
539
542
|
? {
|
|
540
|
-
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | null | undefined }) => {
|
|
543
|
+
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onWrite?: (table: string) => void; userId?: string | null | undefined }) => {
|
|
541
544
|
const env = rawEnv as Env;
|
|
542
545
|
const declaration = this.hyperdriveGlobalDeclaration;
|
|
543
546
|
const exec = declaration?.exec(env) as SqlExec | undefined;
|
|
@@ -577,6 +580,7 @@ const buildGlobalCdcApplier =
|
|
|
577
580
|
cdc: request?.cdc ?? false,
|
|
578
581
|
engine: declaration.engine as HyperdriveEngine,
|
|
579
582
|
exec,
|
|
583
|
+
...(request?.onWrite === undefined ? {} : { onWrite: request.onWrite }),
|
|
580
584
|
// The DECLARATION, not \`exec\` — \`exec(env)\` is a user
|
|
581
585
|
// callback that builds a fresh client per call, so scoping
|
|
582
586
|
// to its result would key the memo on a new object every
|
|
@@ -959,7 +963,7 @@ ${r(" ")}
|
|
|
959
963
|
* \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
|
|
960
964
|
*/
|
|
961
965
|
const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
|
|
962
|
-
`,Ee=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),Ce=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=
|
|
966
|
+
`,Ee=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),Ce=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=B(r),n=pe(r),o=a?` let auth: LunoraAuth | null = null;
|
|
963
967
|
let authInit: Promise<void> | null = null;
|
|
964
968
|
// One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
|
|
965
969
|
// \`assemble()\` has its own auth closure and must not share.
|
|
@@ -1156,7 +1160,7 @@ ${r.securityHeaders===void 0?"":"\n // `security.headers` from lunora.con
|
|
|
1156
1160
|
return options;
|
|
1157
1161
|
}
|
|
1158
1162
|
}
|
|
1159
|
-
${
|
|
1163
|
+
${W(r.hasGlobal)}
|
|
1160
1164
|
/**
|
|
1161
1165
|
* Shape of the project's root \`lunora.config.*\`.
|
|
1162
1166
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-WWiw5i1B.mjs";import"./shard-runtime-G5mZQjY0.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as tr,isD1GlobalTable as rr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as nr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as ar,a as sr,b as or,c as ir,d as dr,f as cr,g as lr,h as ur,i as hr,j as pr,k as mr,l as
|
|
1
|
+
import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as tr,isD1GlobalTable as rr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as nr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as ar,a as sr,b as or,c as ir,d as dr,f as cr,g as lr,h as ur,i as hr,j as pr,k as mr,l as gr,m as fr,n as br,o as yr,p as wr,q as vr,s as kr}from"./shard-runtime-G5mZQjY0.mjs";import{u as U,h as Sr,s as Rr,a as xr,I as Ar,c as Or,G as Tr,d as _r}from"./shared-Cn7dMQ_u.mjs";import{p as Dr}from"./platform-8oj7iXQy.mjs";import{i as Ir}from"./schema-BgM8A3XV.mjs";const m=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(s=>s in o).map(s=>[s,o[s]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([s,i])=>!me.includes(s)||JSON.stringify(i)!==JSON.stringify(n[s])))}),advisoryRules:t}},Cr=` /**
|
|
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
|
|
@@ -236,16 +236,16 @@ ${y()}
|
|
|
236
236
|
await applyCdcChanges(writer, args.changes);
|
|
237
237
|
|
|
238
238
|
return { applied: args.changes.length };
|
|
239
|
-
}`,Pr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:
|
|
239
|
+
}`,Pr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:s,containersContextField:i,databaseOptions:g,everyContextBuild:c,everyContextField:f,facadeBlock:O,globalDatabaseLine:w,hasSensitiveArgs:u=!1,lazyFunctions:l=!1,notifyBuild:T,ormContextField:v,paymentsBuild:F,paymentsContextField:B,queuesBuild:R,queuesContextField:j,topicsBuild:d,topicsContextField:k,vectorsBuild:I,vectorsContextField:W,workflowsBuild:K,workflowsContextField:E})=>{const _=t.length>0,H=v===""?"{ db }":"{ db, orm: bindOrm(facade) }",V=v===""?"":`
|
|
240
240
|
orm: databaseContext.orm,`,C=v===""?"":`
|
|
241
|
-
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,x=
|
|
241
|
+
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,x=_?`
|
|
242
242
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
243
243
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
244
244
|
if (isAction) {
|
|
245
245
|
${r.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`).join(`
|
|
246
246
|
`)}
|
|
247
247
|
}
|
|
248
|
-
`:"";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 {
|
|
248
|
+
`:"";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; readBookmark?: string | undefined; replayKey?: boolean | undefined; scope?: QueryReadScope | undefined; sensitive?: SensitiveScope | undefined; trusted?: boolean | undefined } = {}): unknown {
|
|
249
249
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
250
250
|
// The caller context this ctx runs under, resolved ONCE on one
|
|
251
251
|
// discriminant. When the caller threads an explicit identity
|
|
@@ -302,7 +302,7 @@ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`
|
|
|
302
302
|
|
|
303
303
|
return caller.ip;
|
|
304
304
|
};
|
|
305
|
-
${I}${c}${
|
|
305
|
+
${I}${c}${s}${K}${R}${d}${e}
|
|
306
306
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
307
307
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
308
308
|
// admin/lifecycle path has no registered function, and so no kind. An
|
|
@@ -416,8 +416,8 @@ ${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
416
416
|
// Schema triggers close over this DB's scheduler, so a composed
|
|
417
417
|
// mutation must rebuild its DB and table/ORM views with its own queue.
|
|
418
418
|
const makeDatabaseContext = (scheduler: SchedulerLike) => {
|
|
419
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
420
|
-
${
|
|
419
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${g}), logFunctionPath, traceAnchor, observability, options.sensitive);
|
|
420
|
+
${O} return ${H};
|
|
421
421
|
};
|
|
422
422
|
const databaseContext = makeDatabaseContext(scheduler);
|
|
423
423
|
const db = databaseContext.db;
|
|
@@ -429,7 +429,7 @@ ${F}
|
|
|
429
429
|
// writing mutation's trace from the shared per-request field.
|
|
430
430
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor, options.sensitive);
|
|
431
431
|
const metrics = this.makeMetrics(logFunctionPath, observability, options.sensitive);
|
|
432
|
-
${
|
|
432
|
+
${T}
|
|
433
433
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
434
434
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
435
435
|
// A \`query\` handler is re-run by every live subscription that reads it,
|
|
@@ -511,10 +511,10 @@ ${O}
|
|
|
511
511
|
scheduler,
|
|
512
512
|
span,
|
|
513
513
|
storage: contextStorage,
|
|
514
|
-
trace,${W}${
|
|
514
|
+
trace,${W}${f}${B}${i}${E}${j}${k}${o}${u?`
|
|
515
515
|
[Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
|
|
516
516
|
};
|
|
517
|
-
${
|
|
517
|
+
${_?` const isAction = contextKind === "action";
|
|
518
518
|
`:""}${x}
|
|
519
519
|
${l?` const captureScope = (): (() => void) => {
|
|
520
520
|
const requestScope = this.captureRequestScope();
|
|
@@ -584,7 +584,7 @@ ${l?` const captureScope = (): (() => void) => {
|
|
|
584
584
|
reference.__lunoraRef,
|
|
585
585
|
fnArgs,
|
|
586
586
|
runOptions?.untracked === true
|
|
587
|
-
? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope, sensitive: options.sensitive })
|
|
587
|
+
? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", readBookmark: options.readBookmark, scope: options.scope, sensitive: options.sensitive })
|
|
588
588
|
: queryContext(),
|
|
589
589
|
kind,${l?`
|
|
590
590
|
undefined,
|
|
@@ -634,7 +634,7 @@ ${t.map(p=>` delete descriptors.${p};
|
|
|
634
634
|
installRun(ctx, contextKind);
|
|
635
635
|
|
|
636
636
|
return ctx;
|
|
637
|
-
}`},
|
|
637
|
+
}`},ge=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
638
638
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
639
639
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
640
640
|
// single-threaded), so the counter reflects true nesting depth.
|
|
@@ -700,7 +700,7 @@ const dispatchRun = async (
|
|
|
700
700
|
} finally {
|
|
701
701
|
runDepth -= 1;
|
|
702
702
|
}
|
|
703
|
-
};`,Nr=r=>r?
|
|
703
|
+
};`,Nr=r=>r?ge.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
|
|
704
704
|
captureScope?: () => () => void,`).replace(` try {
|
|
705
705
|
// A mutation composed from an action`,` try {
|
|
706
706
|
let loaded = getLoadedFunction(functionPath);
|
|
@@ -721,7 +721,7 @@ const dispatchRun = async (
|
|
|
721
721
|
|
|
722
722
|
const loadedFunction = loaded;
|
|
723
723
|
|
|
724
|
-
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):
|
|
724
|
+
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ge,$r=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
|
|
725
725
|
// A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
|
|
726
726
|
// a lifecycle hook, an admin run) has no scope of its own, so it opens one here
|
|
727
727
|
// and releases it when the handler settles.
|
|
@@ -934,7 +934,7 @@ __COMMITTED_CATCH__ } finally {
|
|
|
934
934
|
// parked it, and there is nothing to park — an app with no scheduler has no
|
|
935
935
|
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
936
936
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
937
|
-
__OUTBOX_SCHEDULER__ }`,Mr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
937
|
+
__OUTBOX_SCHEDULER__ }`,Mr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity, readBookmark?: string): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
938
938
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
939
939
|
|
|
940
940
|
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
@@ -1005,16 +1005,16 @@ __SUBSCRIPTION_RUN__
|
|
|
1005
1005
|
}
|
|
1006
1006
|
}
|
|
1007
1007
|
|
|
1008
|
-
`:"",
|
|
1008
|
+
`:"",s=e?` const configured = config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
1009
1009
|
return configured === undefined ? undefined : withAgentScheduleShard(configured, LUNORA_AGENTS, this.currentShardKey());
|
|
1010
1010
|
`:` return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
1011
|
-
`;return $r.replace("__COMMITTED_CATCH__",r?qr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",
|
|
1011
|
+
`;return $r.replace("__COMMITTED_CATCH__",r?qr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",s)},Fr=` const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange, readBookmark });
|
|
1012
1012
|
const result = await registered.handler(ctx, args);
|
|
1013
1013
|
`,Br=` const sensitive = this.openSensitiveScope(functionPath, args);
|
|
1014
1014
|
let result: unknown;
|
|
1015
1015
|
|
|
1016
1016
|
try {
|
|
1017
|
-
const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange, sensitive });
|
|
1017
|
+
const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange, readBookmark, sensitive });
|
|
1018
1018
|
|
|
1019
1019
|
result = await registered.handler(ctx, args);
|
|
1020
1020
|
} catch (error) {
|
|
@@ -1022,7 +1022,7 @@ __SUBSCRIPTION_RUN__
|
|
|
1022
1022
|
} finally {
|
|
1023
1023
|
sensitive.clear();
|
|
1024
1024
|
}
|
|
1025
|
-
`,jr=r=>Mr.replace("__SUBSCRIPTION_RUN__",r?Br:Fr),Wr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,
|
|
1025
|
+
`,jr=r=>Mr.replace("__SUBSCRIPTION_RUN__",r?Br:Fr),Wr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,s]of Object.entries(e.shape)){const i=U(s);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},Kr=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,s]of Object.entries(e.shape))U(s).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Hr=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},Vr=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},Gr=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},Qr=new Set(["bigint","boolean","date","number","timestamp"]),Jr=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=U(o(e)?t:e);return o(t)!==o(e)&&Qr.has(n.kind)?n:void 0},zr=(r,t,e)=>{const o=U(t),n=Jr(o),s=n??o,i={name:r,optional:Sr(t),type:s.kind};if(s.kind==="id"&&s.tableName!==void 0){i.ref=s.tableName;const c=e.get(r);c!==void 0&&(i.onDelete=c)}s.kind==="storage"&&(i.isStorage=!0,s.bucket!==void 0&&(i.bucket=s.bucket));const g=Gr(s);return g!==void 0&&(i.enumValues=g),(s.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Yr=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(zr(s,i,n));t[e.name]=o}return t},Xr=({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} {
|
|
1026
1026
|
const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
|
|
1027
1027
|
|
|
1028
1028
|
try {
|
|
@@ -1034,8 +1034,8 @@ __SUBSCRIPTION_RUN__
|
|
|
1034
1034
|
}
|
|
1035
1035
|
}
|
|
1036
1036
|
|
|
1037
|
-
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} {`,
|
|
1038
|
-
${
|
|
1037
|
+
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} {`,g=e?`
|
|
1038
|
+
${s}
|
|
1039
1039
|
const shape = LUNORA_SHAPES[name];
|
|
1040
1040
|
|
|
1041
1041
|
if (!shape) {
|
|
@@ -1097,14 +1097,14 @@ ${a}
|
|
|
1097
1097
|
|
|
1098
1098
|
return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
|
|
1099
1099
|
}
|
|
1100
|
-
`:"",c=e?[...new Set(o.policies.filter(l=>l.on==="read"&&l.table!=="").map(l=>l.table))].toSorted((l,
|
|
1100
|
+
`:"",c=e?[...new Set(o.policies.filter(l=>l.on==="read"&&l.table!=="").map(l=>l.table))].toSorted((l,T)=>l.localeCompare(T)):[],f=c.length>0?`
|
|
1101
1101
|
/** 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). */
|
|
1102
1102
|
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
|
|
1103
1103
|
`:"";return{customMutatorOverride:r?`
|
|
1104
1104
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1105
1105
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1106
1106
|
}
|
|
1107
|
-
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:
|
|
1107
|
+
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:f,shapeReadPolicyImport:f===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:g}},Zr=(r,t)=>r?`
|
|
1108
1108
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1109
1109
|
const env = this.env as Record<string, unknown>;
|
|
1110
1110
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1151,26 +1151,43 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as
|
|
|
1151
1151
|
|
|
1152
1152
|
return rows;
|
|
1153
1153
|
}
|
|
1154
|
+
`:"",en=(r,t)=>r.length===0?"":`
|
|
1155
|
+
// Without a changelog a tick cannot say which tables moved, so there is nothing to poll for.
|
|
1156
|
+
private readonly polledGlobalTableSet: ReadonlySet<string> = new Set<string>(config.cdc === true ? ${JSON.stringify(r)} : []);
|
|
1154
1157
|
|
|
1155
|
-
protected override
|
|
1158
|
+
protected override polledGlobalTables(): ReadonlySet<string> {
|
|
1159
|
+
return this.polledGlobalTableSet;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ bookmark?: string; cursor: number; floor?: number; tables: string[] } | undefined> {
|
|
1156
1163
|
const env = this.env as Record<string, unknown>;
|
|
1157
1164
|
// Metadata-only: this asks the global changelog which TABLES moved,
|
|
1158
1165
|
// never what changed in them, so it costs one small read per poll tick
|
|
1159
|
-
// for the whole shard — and a tick whose answer omits a
|
|
1160
|
-
//
|
|
1166
|
+
// for the whole shard — and a tick whose answer omits a table skips
|
|
1167
|
+
// the shapes and live queries that read only it.
|
|
1161
1168
|
// Named local, not an inline object literal — same reason as the
|
|
1162
|
-
// dispatch path and \`readGlobalShapeRows\`: \`bookmark\`
|
|
1163
|
-
// on the narrower Hyperdrive thunk's \`request\` type, and an inline
|
|
1164
|
-
// literal trips an excess-property error (TS2353)
|
|
1165
|
-
//
|
|
1166
|
-
//
|
|
1169
|
+
// dispatch path and \`readGlobalShapeRows\`: \`bookmark\` and \`onBookmark\` are not
|
|
1170
|
+
// declared on the narrower Hyperdrive thunk's \`request\` type, and an inline
|
|
1171
|
+
// literal trips an excess-property error (TS2353). The Hyperdrive factory
|
|
1172
|
+
// simply never reads them.
|
|
1173
|
+
//
|
|
1174
|
+
// The session's bookmark after the read is returned with the answer: a read
|
|
1175
|
+
// at it sees every write the answer reports, so the refresh it drives reads there.
|
|
1167
1176
|
const bookmark = this.getInboundBookmark();
|
|
1168
|
-
|
|
1177
|
+
let changelogBookmark: string | undefined;
|
|
1178
|
+
const globalRequest = {
|
|
1179
|
+
...this.globalCdcOptions(config.cdc ?? false),
|
|
1180
|
+
...(bookmark === undefined ? {} : { bookmark }),
|
|
1181
|
+
onBookmark: (value: string | undefined) => {
|
|
1182
|
+
changelogBookmark = value;
|
|
1183
|
+
},
|
|
1184
|
+
};
|
|
1169
1185
|
const globalDb: DatabaseWriterLike = ${t}?.(env, globalRequest) ?? globalDbStub;
|
|
1186
|
+
const changed = await globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
|
|
1170
1187
|
|
|
1171
|
-
return
|
|
1188
|
+
return changed === undefined || changelogBookmark === undefined ? changed : { ...changed, bookmark: changelogBookmark };
|
|
1172
1189
|
}
|
|
1173
|
-
|
|
1190
|
+
`,tn=r=>({externalSourceOverride:r?`
|
|
1174
1191
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1175
1192
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1176
1193
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1327,8 +1344,8 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as
|
|
|
1327
1344
|
`:"",sourceClientCacheConst:r?`
|
|
1328
1345
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1329
1346
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1330
|
-
`:""}),
|
|
1331
|
-
`:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",c=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(w=>JSON.stringify(w)).join(", ")}]`]:[]].join(", ")} }`,
|
|
1347
|
+
`:""}),rn=(r,t)=>{const e=t.length>0,n=r?q("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=e?` const vectorShardKey = this.currentShardKey();
|
|
1348
|
+
`:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",c=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(w=>JSON.stringify(w)).join(", ")}]`]:[]].join(", ")} }`,f=r?`
|
|
1332
1349
|
const vectorSync = this.vectorSync(env);
|
|
1333
1350
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
1334
1351
|
// depends on a similarity search cannot be proven current on reconnect —
|
|
@@ -1345,7 +1362,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1345
1362
|
}
|
|
1346
1363
|
|
|
1347
1364
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1348
|
-
${
|
|
1365
|
+
${s} const vectors = createContextVectors(lunora${c});
|
|
1349
1366
|
|
|
1350
1367
|
return {
|
|
1351
1368
|
backfill: createVectorBackfillSync({ ${i}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
|
|
@@ -1371,14 +1388,14 @@ ${a} const vectors = createContextVectors(lunora${c});
|
|
|
1371
1388
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1372
1389
|
});
|
|
1373
1390
|
}
|
|
1374
|
-
`:"",vectorsBuild:
|
|
1391
|
+
`:"",vectorsBuild:f,vectorsStub:n}},Sn=({advisories:r=[],agents:t=[],capabilities:e=new Set,containers:o=[],env:n,flagKeys:s=[],hasFlags:i=!1,hasNotify:g=!1,hasRooms:c=!1,hasSecretValues:f=!1,hasSensitiveArgs:O=!1,hasSockets:w=!1,lazyFunctions:u=!1,hasVectors:l=!0,liveStreamDeclarations:T=[],liveStreams:v=!1,maskMetadata:F,mutators:B=[],queues:R=[],rlsMetadata:j,schema:d,schemaSnapshot:k,shapes:I=[],storageRules:W,studioFeatures:K,hasIpReaders:E=!1,services:_=[],topics:H=[],useUmbrella:V=!1,workflowEvents:C=[],workflows:x=[]})=>{const h=_r(V),G=B.length>0,p=I.length>0,L=I.some(a=>Rr(a.args).length>0),P=O||L,fe=k===void 0?"":Zt(k),be=k===void 0?"":`
|
|
1375
1392
|
/** 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. */
|
|
1376
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(er(k))}, json: ${JSON.stringify(
|
|
1377
|
-
`,ye=k===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",S=ar(e),N=sr(i,h.flags),Q=or(
|
|
1378
|
-
return { ${D.map(
|
|
1393
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(er(k))}, json: ${JSON.stringify(fe)} };
|
|
1394
|
+
`,ye=k===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",S=ar(e),N=sr(i,h.flags),Q=or(s,i,h.flags),J=kr(g),z=ir(n),{build:we,contextField:ve,importLines:ke,specs:Se}=dr(Dr(R)),{build:Re,contextField:xe,importLines:Ae,specs:Oe}=cr(H,R),Y=lr(_,h.server),{build:Te,contextField:_e,importLines:De,specs:Ie}=ur(o,d.jurisdiction),{build:Ee,contextField:Ce,importLines:Le,specs:Pe}=hr(x),{build:Ne,contextField:$e,importLines:Me,schedulerSource:qe,specs:Ue,stampsOutbox:Fe}=pr(t,f&&t.length>0),{build:Be,configField:je,contextField:We,imports:Ke,stub:He}=mr(e.has("payments")),Ve=r,{advisoryRules:Ge,advisoryRows:Qe}=Er(Ve),ae=j??{policies:[],roles:[]},Je=F??{columns:[]},ze=W??{rules:[]},Ye=K??{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:Xe,override:Ze}=gr(x,C),{constant:et,override:tt}=fr(x,C),{constant:rt,override:nt}=br(R),b=l&&d.vectorIndexes.length>0,X=new Set(d.tables.filter(a=>Ir(a)).map(a=>a.name)),se=b&&d.vectorIndexes.some(a=>X.has(a.table)),A=d.tables.some(a=>a.shardMode==="global"),Z=yr(X),ee=d.tables.some(a=>tr(a)),oe=d.tables.some(a=>rr(a)),$=d.tables.some(a=>a.externalSource!==void 0),ie=d.tables.some(a=>a.memory===!0),te=d.tables.some(a=>a.shardMode!=="global"&&a.searchIndexes.length>0);if(oe&&ee)throw new pe("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const re=d.tables.length>0,at=Wr(d),st=Hr(d),ot=Yr(d),it=Kr(d),de=Vr(d),ce=wr(b,x.length>0,R.length>0,i,te);p&&ce.push("WhereInput");const le=vr(A),{customMutatorOverride:dt,shapeGuardImport:ct,shapeReadPolicyAssertion:lt,shapeReadPolicyImport:ut,shapeResolveOverride:ht}=Xr({hasMutators:G,hasSensitiveShapes:L,hasShapes:p,rlsData:ae}),D=v?T:[];for(const a of D)if(xr(a.exportName,"live stream export name"),!Ar.test(a.filePath))throw new pe("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(a.filePath)}`);const pt=u?[]:D.map(a=>`import { ${a.exportName} as liveStream_${a.exportName} } from "../${a.filePath}.js";`),mt=` protected override liveStreams() {
|
|
1395
|
+
return { ${D.map(a=>`${Or(a.id)}: liveStream_${a.exportName}`).join(", ")} };
|
|
1379
1396
|
}
|
|
1380
|
-
`,
|
|
1381
|
-
${D.map(
|
|
1397
|
+
`,gt=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
|
|
1398
|
+
${D.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}.js").then((module) => module.${a.exportName})],`).join(`
|
|
1382
1399
|
`)}
|
|
1383
1400
|
]);
|
|
1384
1401
|
|
|
@@ -1399,11 +1416,11 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1399
1416
|
protected override liveStreams() {
|
|
1400
1417
|
return Object.fromEntries(this.loadedLiveStreams);
|
|
1401
1418
|
}
|
|
1402
|
-
`;let
|
|
1403
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",bt=
|
|
1404
|
-
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",yt=ee?`
|
|
1405
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",wt=$?`
|
|
1406
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",vt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",kt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",St="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Rt=
|
|
1419
|
+
`;let ue="";D.length>0&&(ue=u?gt:mt);const M=[`import type { ${ce.join(", ")} } from "${h.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${te?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ie?"clearMemoryTables, ":""}${ct}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${$?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${le.importFragment}ShardDO as ShardDOBase } from "${h.do}";`,...$?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${h.do}";`]:[],p?`import { asBucketStorage, ${ut}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`];re&&M.push(`import type { FacadeEntry } from "${h.server}";`,`import { bindOrm, defineLazyFacade } from "${h.server}";`),b&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...S.importLines,...N.importLines,...J.importLines,...z.importLines,...De,...Le,...ke,...Ae,...Y.importLines,...Me,...Ke,...P?[`import { sensitiveArgumentNames } from "${h.values}";`]:[],"",'import schema from "../schema.js";',...pt,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...u?["getLoadedFunction","loadFunction"]:[],...G?["LUNORA_MUTATOR_PATHS"]:[],...E?["LUNORA_IP_READER_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...w?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ft=b?`
|
|
1420
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",bt=oe?`
|
|
1421
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; onWrite?: (table: string) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",yt=ee?`
|
|
1422
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onWrite?: (table: string) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",wt=$?`
|
|
1423
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",vt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",kt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",St="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Rt=A?q("globalDbStub: DatabaseWriterLike",vt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:xt,vectorsBuild:At,vectorsStub:Ot}=rn(b,se?d.vectorIndexes.filter(a=>X.has(a.table)).map(a=>a.name):[]),Tt=`{
|
|
1407
1424
|
...this.ctxDbTuning(),
|
|
1408
1425
|
auth: {
|
|
1409
1426
|
get identity() {
|
|
@@ -1414,7 +1431,11 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1414
1431
|
},
|
|
1415
1432
|
},
|
|
1416
1433
|
broadcast: (delta) => {
|
|
1417
|
-
|
|
1434
|
+
${A?` if (writeBookmark !== undefined && (schema as unknown as SchemaLike).tables[delta.table]?.shardMode?.kind === "global") {
|
|
1435
|
+
this.recordGlobalWrite(delta.table, writeBookmark);
|
|
1436
|
+
} else {
|
|
1437
|
+
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1438
|
+
}`:" this.recordChangedTable(delta.table, delta.indexKeys);"}
|
|
1418
1439
|
},
|
|
1419
1440
|
// Read at call time, not captured: the baseline belongs to the
|
|
1420
1441
|
// dispatch in flight, and a queued mutation admitted after a
|
|
@@ -1462,37 +1483,39 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1462
1483
|
scheduler,
|
|
1463
1484
|
schema: schema as unknown as SchemaLike,
|
|
1464
1485
|
sql: this.sql as SqlExec,
|
|
1465
|
-
storage,${
|
|
1486
|
+
storage,${A?`
|
|
1466
1487
|
globalDb,`:""}
|
|
1467
1488
|
}`,_t=b?`
|
|
1468
1489
|
vectors,`:"",Dt=re?`
|
|
1469
|
-
orm: bindOrm(facade),`:"",
|
|
1490
|
+
orm: bindOrm(facade),`:"",ne=ee?"config.hyperdriveGlobal":"config.d1",It=A?` const bookmark = options.readBookmark ?? this.getInboundBookmark();
|
|
1491
|
+
let writeBookmark: string | undefined;
|
|
1470
1492
|
const globalRequest = {
|
|
1471
1493
|
...this.globalCdcOptions(config.cdc ?? false),
|
|
1472
1494
|
...(bookmark === undefined ? {} : { bookmark }),
|
|
1473
1495
|
get identity(): Record<string, unknown> | undefined {
|
|
1474
1496
|
return readIdentity();
|
|
1475
1497
|
},
|
|
1476
|
-
onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
|
|
1498
|
+
onBookmark: (bookmarkValue: string | undefined) => { writeBookmark = bookmarkValue; if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
|
|
1499
|
+
onWrite: (table: string) => { this.recordGlobalWrite(table, writeBookmark); },
|
|
1477
1500
|
get userId(): string | undefined {
|
|
1478
1501
|
return readUserId();
|
|
1479
1502
|
},
|
|
1480
1503
|
};
|
|
1481
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1482
|
-
`:"",Et=Zr(p&&
|
|
1504
|
+
const globalDb: DatabaseWriterLike = ${ne}?.(env, globalRequest) ?? globalDbStub;
|
|
1505
|
+
`:"",Et=Zr(p&&A,ne)+en(d.tables.filter(a=>a.shardMode==="global").map(a=>a.name),ne),Ct=c?` protected override roomHandlerPath(topic: string): string | undefined {
|
|
1483
1506
|
// Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
|
|
1484
1507
|
return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
|
|
1485
1508
|
}
|
|
1486
1509
|
`:"",Lt=w?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
|
|
1487
1510
|
return LUNORA_SOCKETS[path];
|
|
1488
1511
|
}
|
|
1489
|
-
`:"",{externalSourceOverride:Pt,sourceBootstrap:Nt,sourceClientCacheConst:$t}=
|
|
1512
|
+
`:"",{externalSourceOverride:Pt,sourceBootstrap:Nt,sourceClientCacheConst:$t}=tn($),Mt=`
|
|
1490
1513
|
private shardInitDeferred = false;
|
|
1491
1514
|
private deferredShardInit?: Promise<void>;
|
|
1492
1515
|
|
|
1493
1516
|
protected override async runShardInit(): Promise<void> {
|
|
1494
1517
|
this.ensureMigrated();
|
|
1495
|
-
${
|
|
1518
|
+
${ie?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1496
1519
|
`:""}
|
|
1497
1520
|
if (this.blockedUniqueIndexes.length > 0) {
|
|
1498
1521
|
this.shardInitDeferred = true;
|
|
@@ -1532,7 +1555,7 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1532
1555
|
|
|
1533
1556
|
await this.deferredShardInit;
|
|
1534
1557
|
}
|
|
1535
|
-
`,qt=
|
|
1558
|
+
`,qt=de.length>0?`
|
|
1536
1559
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1537
1560
|
void this.scheduleTtlSweep();
|
|
1538
1561
|
}
|
|
@@ -1615,18 +1638,18 @@ ${E?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
|
1615
1638
|
if (preparation !== undefined) await preparation;
|
|
1616
1639
|
`:"",Kt=jr(P).replace("__PREPARE_FUNCTION__",Wt),Ht=Ur(c,u,Fe),Vt=re?`
|
|
1617
1640
|
const facade = db as unknown as Record<string, FacadeEntry>;
|
|
1618
|
-
${d.tables.map(
|
|
1641
|
+
${d.tables.map(a=>` defineLazyFacade(db, ${JSON.stringify(a.name)});`).join(`
|
|
1619
1642
|
`)}
|
|
1620
|
-
`:"",Gt=`${S.everyBuild}${N.build}${
|
|
1643
|
+
`:"",Gt=`${S.everyBuild}${N.build}${z.build}
|
|
1621
1644
|
const secrets = createSecrets(env);
|
|
1622
|
-
`,Qt=`${S.everyFields}${N.contextField}${
|
|
1623
|
-
secrets,`,
|
|
1645
|
+
`,Qt=`${S.everyFields}${N.contextField}${J.contextField}${z.contextField}
|
|
1646
|
+
secrets,`,Jt=J.build,zt=v?`
|
|
1624
1647
|
const live = {
|
|
1625
1648
|
publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
|
|
1626
1649
|
await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
|
|
1627
1650
|
},
|
|
1628
1651
|
};
|
|
1629
|
-
`:"",Yt=[...S.actionFields,...
|
|
1652
|
+
`:"",Yt=[...S.actionFields,..._.length>0?["services"]:[],...v?["live"]:[]],Xt=`${S.actionBuild}${Y.build}${zt}`;return`${Tr}${M.join(`
|
|
1630
1653
|
`)}
|
|
1631
1654
|
|
|
1632
1655
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1662,7 +1685,7 @@ const LUNORA_TABLE_COLUMNS = ${m(ot,`Record<
|
|
|
1662
1685
|
const LUNORA_STORAGE_COLUMNS = ${m(it,"Record<string, string[]>")};
|
|
1663
1686
|
|
|
1664
1687
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1665
|
-
const LUNORA_TTL_SWEEPS = ${nr(
|
|
1688
|
+
const LUNORA_TTL_SWEEPS = ${nr(de,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1666
1689
|
|
|
1667
1690
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1668
1691
|
const LUNORA_ADVISORY_RULES = ${m(Ge,"Record<string, Partial<AdvisoryFinding>>")};
|
|
@@ -1676,13 +1699,13 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
|
1676
1699
|
})();
|
|
1677
1700
|
|
|
1678
1701
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1679
|
-
const LUNORA_RLS_METADATA = ${m(
|
|
1702
|
+
const LUNORA_RLS_METADATA = ${m(ae,"RlsPoliciesResult")};
|
|
1680
1703
|
${lt}
|
|
1681
1704
|
/** 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. */
|
|
1682
|
-
const LUNORA_MASK_METADATA = ${m(
|
|
1705
|
+
const LUNORA_MASK_METADATA = ${m(Je,"MaskPoliciesResult")};
|
|
1683
1706
|
|
|
1684
1707
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1685
|
-
const LUNORA_STORAGE_RULES = ${m(
|
|
1708
|
+
const LUNORA_STORAGE_RULES = ${m(ze,"StorageRulesResult")};
|
|
1686
1709
|
|
|
1687
1710
|
/** 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. */
|
|
1688
1711
|
const LUNORA_STUDIO_FEATURES = ${m(Ye,"StudioFeaturesResult")};
|
|
@@ -1706,7 +1729,7 @@ export interface ShardDOConfig {
|
|
|
1706
1729
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1707
1730
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1708
1731
|
/** \`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. */
|
|
1709
|
-
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${
|
|
1732
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ft}${S.configFields}${N.configField}${je}${bt}${yt}${wt}${Z.configField}
|
|
1710
1733
|
}
|
|
1711
1734
|
${q("schedulerStub",kt,["cancel","runAfter","runAt"])}${q("storageStub",St,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${Rt}${$t}${Ot}${S.stubs}${He}
|
|
1712
1735
|
// \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
|
|
@@ -1731,13 +1754,13 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
|
|
|
1731
1754
|
private blockedUniqueIndexes: readonly string[] = [];
|
|
1732
1755
|
private migrated = false;
|
|
1733
1756
|
private migrationRetryAt = 0;${Ft}${Bt}${Ht}
|
|
1734
|
-
${
|
|
1757
|
+
${le.override}
|
|
1735
1758
|
${Kt}
|
|
1736
1759
|
${dt}${ht}${Et}${Pt}
|
|
1737
1760
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1738
1761
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1739
1762
|
}
|
|
1740
|
-
${Ct}${Lt}${
|
|
1763
|
+
${Ct}${Lt}${ue}${Z.override}${Mt}
|
|
1741
1764
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1742
1765
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1743
1766
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1894,6 +1917,6 @@ ${te?`
|
|
|
1894
1917
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1895
1918
|
}
|
|
1896
1919
|
`:""}${xt}
|
|
1897
|
-
${Pr({hasSensitiveArgs:P,lazyFunctions:u,actionOnlyFields:Yt,agentsBuild:Ne,agentsContextField:$e,agentsSchedulerSource:qe,containersBuild:Te,containersContextField:_e,databaseOptions:Tt,everyContextBuild:Gt,everyContextField:Qt,facadeBlock:Vt,globalDatabaseLine:It,notifyBuild:
|
|
1920
|
+
${Pr({hasSensitiveArgs:P,lazyFunctions:u,actionOnlyFields:Yt,agentsBuild:Ne,agentsContextField:$e,agentsSchedulerSource:qe,containersBuild:Te,containersContextField:_e,databaseOptions:Tt,everyContextBuild:Gt,everyContextField:Qt,facadeBlock:Vt,globalDatabaseLine:It,notifyBuild:Jt,ormContextField:Dt,paymentsBuild:Be,paymentsContextField:We,queuesBuild:we,queuesContextField:ve,topicsBuild:Re,topicsContextField:xe,vectorsBuild:At,vectorsContextField:_t,workflowsBuild:Ee,workflowsContextField:Ce,actionOnlyBuild:Xt})}
|
|
1898
1921
|
};
|
|
1899
|
-
`};export{Kr as b,
|
|
1922
|
+
`};export{Kr as b,Sn as e};
|