@lunora/codegen 1.0.0-alpha.227 → 1.0.0-alpha.229

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs";import{default as h}from"./packem_shared/discoverCrons-MfKw7IFf.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BedPDCsR.mjs";import{default as D}from"./packem_shared/discoverFunctions-BsmX-sEq.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-BcXI9CNt.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs";import{default as y}from"./packem_shared/discoverInserts-CFJ3IVeI.mjs";import{d as W}from"./packem_shared/index-BoaHhVtM.mjs";import{default as V}from"./packem_shared/discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-B-f4jO-x.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-BO4qC77y.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CPmAGL0W.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-CgmfgDTS.mjs";import{default as xe}from"./packem_shared/discoverSchema-QO1eQYjw.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-zJgzynXR.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-6YJU3YbV.mjs";import{emitApp as We}from"./packem_shared/emitApp-BiATunRA.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-D1dd4rBh.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-DAxS0CaZ.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-kmm2i4Fw.mjs";import{loadProjectConfig as ir,readProjectConfigLiterals as mr}from"./packem_shared/loadProjectConfig-CKsFNgn3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as fr,createCodegenProject as pr,findTsconfig as cr,refreshCodegenProject as nr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-YIXfZGqF.mjs";import{SchemaSnapshotParseError as xr,buildSchemaSnapshot as Er,evaluateSchemaDrift as Ar,parseSchemaSnapshot as ur}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Cr,validatorIrToJsonSchema as Or}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Mr,SDK_TARGETS as Tr,generateSdk as _r}from"./packem_shared/SDK_LANGUAGES-Cmn8nq91.mjs";import{redact as Lr,secretKindOf as Fr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Pr,findSolutionByMessage as Dr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Ur,findProjectConfigFile as br}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{isTypedSchema as jr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Cr as LUNORA_ERROR_CODES,Pr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,Ur as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,fr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Mr as SDK_LANGUAGES,Tr as SDK_TARGETS,Ae as SHAPES_FILENAME,xr as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,Er as buildSchemaSnapshot,pr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,Dr as findLunoraSolution,br as findProjectConfigFile,cr as findTsconfig,m as formatAdvisories,_r as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,jr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,ir as loadProjectConfig,ur as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,mr as readProjectConfigLiterals,tr as readProjectTarget,Lr as redact,nr as refreshCodegenProject,sr as resolveCodegenTarget,lr as runCodegen,Nr as schemaFromIr,Fr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Or as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs";import{default as h}from"./packem_shared/discoverCrons-MfKw7IFf.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BedPDCsR.mjs";import{default as D}from"./packem_shared/discoverFunctions-BsmX-sEq.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-BcXI9CNt.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs";import{default as y}from"./packem_shared/discoverInserts-CFJ3IVeI.mjs";import{d as W}from"./packem_shared/index-BoaHhVtM.mjs";import{default as V}from"./packem_shared/discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-B-f4jO-x.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-BO4qC77y.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CPmAGL0W.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-CgmfgDTS.mjs";import{default as xe}from"./packem_shared/discoverSchema-D8DBDHEg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-zJgzynXR.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-6YJU3YbV.mjs";import{emitApp as We}from"./packem_shared/emitApp-BiATunRA.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-D1dd4rBh.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-DAxS0CaZ.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-kmm2i4Fw.mjs";import{loadProjectConfig as ir,readProjectConfigLiterals as mr}from"./packem_shared/loadProjectConfig-CKsFNgn3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as fr,createCodegenProject as pr,findTsconfig as cr,refreshCodegenProject as nr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BveaOaFr.mjs";import{SchemaSnapshotParseError as xr,buildSchemaSnapshot as Er,evaluateSchemaDrift as Ar,parseSchemaSnapshot as ur}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Cr,validatorIrToJsonSchema as Or}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Mr,SDK_TARGETS as Tr,generateSdk as _r}from"./packem_shared/SDK_LANGUAGES-Cmn8nq91.mjs";import{redact as Lr,secretKindOf as Fr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Pr,findSolutionByMessage as Dr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Ur,findProjectConfigFile as br}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{isTypedSchema as jr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Cr as LUNORA_ERROR_CODES,Pr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,Ur as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,fr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Mr as SDK_LANGUAGES,Tr as SDK_TARGETS,Ae as SHAPES_FILENAME,xr as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,Er as buildSchemaSnapshot,pr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,Dr as findLunoraSolution,br as findProjectConfigFile,cr as findTsconfig,m as formatAdvisories,_r as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,jr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,ir as loadProjectConfig,ur as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,mr as readProjectConfigLiterals,tr as readProjectTarget,Lr as redact,nr as refreshCodegenProject,sr as resolveCodegenTarget,lr as runCodegen,Nr as schemaFromIr,Fr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Or as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as w,mkdirSync as Ls,readFileSync as $t,writeFileSync as Ds,rmSync as ks}from"node:fs";import{join as y,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as Ms}from"@lunora/advisor";import{LunoraError as K}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as Ks,Project as dt}from"ts-morph";import{serializeSchemaSnapshot as _s}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as zs}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as $s}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as Us}from"./paths-C-9fwEgQ.mjs";import{C as ce,o as Ut,j as qs,f as Bs,k as js,b as Vs,c as Ws,m as Hs,e as Gs,p as Ys,d as Qs,i as Xs,l as Zs,g as Js,q as en,n as tn,a as sn,h as nn}from"./emit-6YJU3YbV.mjs";import{isD1GlobalTable as qt,isHyperdriveGlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as rn}from"./AGENTS_FILENAME-DoPI92Wu.mjs";import{discoverContainers as on}from"./CONTAINERS_FILENAME-B6TFs82W.mjs";import an from"./discoverCrons-MfKw7IFf.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,bindingKeyName as Q,propertyKeyName as E,unwrapExpression as X,listSecurityScanFiles as me,objectLiteralFromCallbackBody as jt,propertyInitializer as b,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as cn,limitNameOf as Vt,optionsObjectLiteral as Wt,isContextIdentifier as Fe,handlerOf as ln,isDatabaseAccessor as _,readTargetOf as Ht,enclosingExportName as un}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import dn from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as fn}from"./QUEUES_FILENAME-CxkPcMH1.mjs";import{discoverSandboxUsage as gn}from"./discoverSandboxUsage-CgmfgDTS.mjs";import pn from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as A,c as z,d as Gt,e as mn}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as hn}from"./WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{gatePlatformFeatures as vn,resolveCodegenTarget as Yt,readTargetDiagnostics as xn,studioPlatformFor as En}from"./DEFAULT_TARGET-kmm2i4Fw.mjs";import{i as k,a as U,e as S,r as Sn,b as yn,s as he,c as An,f as bn,d as Nn}from"./queries-B-f4jO-x.mjs";import{r as ve,s as Pn}from"./parse-validator-C94Yiabo.mjs";import wn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as In,a as Tn,e as Cn,b as Fn,d as On,c as Rn}from"./unwrap-handler-return-CoV_GK33.mjs";import Ln from"./discoverFunctions-BsmX-sEq.mjs";import Dn from"./discoverHttpRoutes-BcXI9CNt.mjs";import kn from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import Mn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Me,a as ue,s as Qt,d as Kn}from"./index-BoaHhVtM.mjs";import{e as Xt}from"./exported-procedure-chains-CmCDiPBV.mjs";import _n from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as zn,isDefineMutatorCallee as $n,discoverMutators as Un}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import qn from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Bn,discoverNotifyCalls as jn}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import Vn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Wn from"./discoverRlsProcedures-BO4qC77y.mjs";import Hn from"./discoverRlsMetadata-CPmAGL0W.mjs";import Gn from"./discoverSchema-QO1eQYjw.mjs";import{secretKindOf as Yn,redact as Qn,isHeuristicSecretKind as Xn,isSecretishName as Zn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Jn}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as er}from"./emitApp-BiATunRA.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-D1dd4rBh.mjs";import{buildOpenRpcDocument as nr,emitOpenRpcModule as rr}from"./OPENRPC_VERSION-DAxS0CaZ.mjs";import{buildSchemaSnapshot as ir}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft={error:"ERROR",info:"INFO",warn:"WARN"},gt={ERROR:2,INFO:0,WARN:1},or=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),ar=(e,t)=>{const{advisor:s}=$s(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(ft,n)?ft[n]:void 0;return i===void 0?[...t,or(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(r=>gt[r.level]>=gt[i])},pt=(e,t="api")=>{const s=new Map;for(const n of e){const i=Us(n),r=s.get(i);if(r===void 0){s.set(i,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new K("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},cr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:r}=t,a=[];e.tables.some(c=>qt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Bt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ce)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},lr=(e,t,s={})=>{if(t===void 0)return;const n=cr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const i=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
1
+ import{existsSync as w,mkdirSync as Ls,readFileSync as $t,writeFileSync as Ds,rmSync as ks}from"node:fs";import{join as y,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as Ms}from"@lunora/advisor";import{LunoraError as K}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as Ks,Project as dt}from"ts-morph";import{serializeSchemaSnapshot as _s}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as zs}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as $s}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as Us}from"./paths-C-9fwEgQ.mjs";import{C as ce,o as Ut,j as qs,f as Bs,k as js,b as Vs,c as Ws,m as Hs,e as Gs,p as Ys,d as Qs,i as Xs,l as Zs,g as Js,q as en,n as tn,a as sn,h as nn}from"./emit-6YJU3YbV.mjs";import{isD1GlobalTable as qt,isHyperdriveGlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as rn}from"./AGENTS_FILENAME-DoPI92Wu.mjs";import{discoverContainers as on}from"./CONTAINERS_FILENAME-B6TFs82W.mjs";import an from"./discoverCrons-MfKw7IFf.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,bindingKeyName as Q,propertyKeyName as E,unwrapExpression as X,listSecurityScanFiles as me,objectLiteralFromCallbackBody as jt,propertyInitializer as b,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as cn,limitNameOf as Vt,optionsObjectLiteral as Wt,isContextIdentifier as Fe,handlerOf as ln,isDatabaseAccessor as _,readTargetOf as Ht,enclosingExportName as un}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import dn from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as fn}from"./QUEUES_FILENAME-CxkPcMH1.mjs";import{discoverSandboxUsage as gn}from"./discoverSandboxUsage-CgmfgDTS.mjs";import pn from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as A,c as z,d as Gt,e as mn}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as hn}from"./WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{gatePlatformFeatures as vn,resolveCodegenTarget as Yt,readTargetDiagnostics as xn,studioPlatformFor as En}from"./DEFAULT_TARGET-kmm2i4Fw.mjs";import{i as k,a as U,e as S,r as Sn,b as yn,s as he,c as An,f as bn,d as Nn}from"./queries-B-f4jO-x.mjs";import{r as ve,s as Pn}from"./parse-validator-C94Yiabo.mjs";import wn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as In,a as Tn,e as Cn,b as Fn,d as On,c as Rn}from"./unwrap-handler-return-CoV_GK33.mjs";import Ln from"./discoverFunctions-BsmX-sEq.mjs";import Dn from"./discoverHttpRoutes-BcXI9CNt.mjs";import kn from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import Mn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Me,a as ue,s as Qt,d as Kn}from"./index-BoaHhVtM.mjs";import{e as Xt}from"./exported-procedure-chains-CmCDiPBV.mjs";import _n from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as zn,isDefineMutatorCallee as $n,discoverMutators as Un}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import qn from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Bn,discoverNotifyCalls as jn}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import Vn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Wn from"./discoverRlsProcedures-BO4qC77y.mjs";import Hn from"./discoverRlsMetadata-CPmAGL0W.mjs";import Gn from"./discoverSchema-D8DBDHEg.mjs";import{secretKindOf as Yn,redact as Qn,isHeuristicSecretKind as Xn,isSecretishName as Zn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Jn}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as er}from"./emitApp-BiATunRA.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-D1dd4rBh.mjs";import{buildOpenRpcDocument as nr,emitOpenRpcModule as rr}from"./OPENRPC_VERSION-DAxS0CaZ.mjs";import{buildSchemaSnapshot as ir}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft={error:"ERROR",info:"INFO",warn:"WARN"},gt={ERROR:2,INFO:0,WARN:1},or=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),ar=(e,t)=>{const{advisor:s}=$s(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(ft,n)?ft[n]:void 0;return i===void 0?[...t,or(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(r=>gt[r.level]>=gt[i])},pt=(e,t="api")=>{const s=new Map;for(const n of e){const i=Us(n),r=s.get(i);if(r===void 0){s.set(i,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new K("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},cr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:r}=t,a=[];e.tables.some(c=>qt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Bt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ce)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},lr=(e,t,s={})=>{if(t===void 0)return;const n=cr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const i=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
2
  `);throw new K("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${i}
4
4
 
@@ -0,0 +1 @@
1
+ import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as C}from"node:module";import{join as F}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{r as B,p as V}from"./parse-validator-C94Yiabo.mjs";const q=(e,n)=>`table "${e}" is .global() and declares vector index "${n}". 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.`,J=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}},U=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}:{}}),m=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:U(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=m(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=J(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([a,o])=>[a,m(o)]));break}case"record":{s.valueType=m(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=m(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(a=>m(a));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,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(t).map(([r,a])=>[r,m(a)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([o,l])=>G(l,o)),r=e.vectorIndexes??{},a=Object.entries(r??{}).map(([o,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:o,table:l.table??""}));return{bareTables:s,bareVectorIndexes:a,key:n}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},H=e=>{const n=X(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const a=r.getModuleSpecifierValue();for(const o of r.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===n)return{importedName:o.getName(),moduleSpecifier:a,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:a,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:a,propertyPath:[]}}},Q=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},Y=(e,n)=>{const t=H(e);if(t)try{const s=C(F(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),a=s(r),o=Q(a,t);return typeof o!="object"||o===null?void 0:W(o)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,n)=>{const t=u(e,n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},f=(e,n)=>{const t=b(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},x=(e,n)=>{const t=b(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},L=(e,n)=>{const t=b(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},h=(e,n)=>{const t=b(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,n)=>{const t=h(e,n);return t!==void 0&&t.length>0?t:void 0},A=(e,n,t,s,r)=>{let a=e;for(;;){const o=a.getParent();if(!o||!i.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!i.isCallExpression(l))break;if(o.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${n}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${t} ${JSON.stringify(g)} — expected ${r}`);return g}a=l}},ne=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.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,n)=>{if(ae.has(e))throw d(n,`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(le.has(e))throw d(n,`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(!N.test(e))throw d(n,`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(ie(e))throw d(n,`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.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,a]=n.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const o=r.getLiteralText();let l="_unknown_",c="_id",g;return a&&i.isObjectLiteralExpression(a)&&(l=f(a,"field")??l,c=f(a,"references")??c,g=s==="one"?ce(f(a,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:o}},ue=e=>{const n=de(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=fe(s);r&&t.push(r)}return t},pe=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),a=`${s}${r.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw d(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${a}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=u(e,"unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw d(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},me=e=>{const[n,t,s]=e,r=ge(s),a=y(n),o=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of o)if(!i.isStringLiteral(c))throw d(c,`index "${a}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),a);return{fields:l.map(c=>c.getLiteralText()),name:a,unique:r}},be=e=>{const[n,t]=e;let s="_unknown_",r,a,o,l;return t&&i.isObjectLiteralExpression(t)&&(s=f(t,"field")??s,r=h(t,"filterFields"),a=f(t,"language"),o=L(t,"staged"),l=f(t,"strategy")),{field:s,filterFields:r,language:a,name:y(n),staged:o,strategy:l}},xe=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=f(t,"field")??s,r=x(t,"precision")),{field:s,name:y(n),precision:r}},he=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=x(t,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const n=f(e,"field");return n===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:n}},ve=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const a=u(t,"sortBy");if(a&&i.isPropertyAssignment(a)){const o=a.getInitializer();o&&i.isArrayLiteralExpression(o)&&(s=o.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(t,"partitionBy")}return{name:y(n),partitionBy:r,sortBy:s}},Ee=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:n}},Ie=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&f(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=u(e,"field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},Se=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(n,"binding")??"",columns:te(n,"columns"),hasReconcile:u(n,"reconcileEveryMs")!==void 0,hasSoftDelete:u(n,"softDeleteColumn")!==void 0,hasTenantBy:u(n,"tenantBy")!==void 0,idColumn:f(n,"idColumn"),mode:f(n,"mode"),query:f(n,"query")}},ke=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(t));break}case"global":{e.shardMode="global",e.globalBackend=Ie(t);break}case"index":{e.indexes.push(me(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(t[0])};break}case"source":{e.externalSource=Se(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(t);break}case"vectorize":{const r=Ee(t,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const a of _){const o=`${r.name}${a}`;if(!s.has(o))continue;const l=a==="__vocab"?`the \`fts5vocab\` companion for "${o}" 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 "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${n}" declares search indexes "${r.name}" and "${o}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${o}" as its "${a}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,n,t)=>{if(t.ttl!==void 0&&t.shardMode==="global")throw d(e,ne(n))},P=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const a=r.getExpression(),o=r.getArguments();if(i.isPropertyAccessExpression(a))ke(t,a.getName(),o,n),r=a.getExpression();else if(i.isIdentifier(a)&&a.getText()==="defineTable"){const l=o[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,n,t.searchIndexes),_e(e,n,t),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},j=(e,n=[],t=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const o=B(r.getExpression());o!==void 0&&!s.has(o)&&j(o,n,t,s);continue}if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(a){const o=I(r);if(w(o,r.getNameNode()),t.has(o))throw d(r.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(o),n.push(P(a,o))}}return n},Le=e=>{const n=u(e,"source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return f(t,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),a=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:a,table:Le(s)}},$=e=>{const n=[];for(const t of e.getProperties()){const s=Oe(t);s&&n.push(s)}return n},S=(e,n)=>`${e}_${n}`,Ae=(e,n)=>{if(!N.test(e))throw d(n,`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.`)},E=(e,n,t)=>t.has(e)?S(n,e):e,Ne=(e,n,t)=>{const s=S(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:E(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:E(r.table,n,t)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,n)=>{const t=Pe(e);if(t){if(i.isPropertyAccessExpression(n)){const s=De(t);return s?b(s,n.getName()):void 0}return t}},Me=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,je(n))return n;const s=$e(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,o=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=ze(o,n)}},Re=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),keyNode:n,options:t}},Ce=e=>{const n=u(e,"tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(!a)continue;const o=I(r);w(o,r.getNameNode()),s.push(P(a,o))}return s},Fe=e=>{const n=u(e,"vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:$(t)},D=(e,n,t,s)=>{Ae(e,s);const r=new Set(n.map(l=>l.name)),a=n.map(l=>Ne(l,e,r)),o=t.map(l=>({...l,name:S(e,l.name),table:E(l.table,e,r)}));return{tables:a,vectorIndexes:o}},Be=(e,n,t)=>D(e,Ce(t),Fe(t),n),Ve=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=Me(t);if(!s){if(n!==void 0){const a=Y(t,n);if(a){for(const o of a.bareTables)w(o.name,t);return D(a.key,a.bareTables,a.bareVectorIndexes,t)}}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},Je=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=[];for(const a of qe(e)){const o=Ve(a,t);if(o){for(const l of o.tables){if(s.has(l.name))throw d(a,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...o.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let n=e;for(;;){const t=n.getParent(),s=t?.getParent();if(!t||!i.isPropertyAccessExpression(t)||!s||!i.isCallExpression(s))return!1;if(t.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}n=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${n}`);const a=r.getArguments()[0];if(!a||!i.isObjectLiteralExpression(a))throw d(r,"defineSchema() expects an object literal");const o=j(a),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,o,t),k=[...o.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(o.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:o,vectorIndexes:k}};export{rt as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.227",
3
+ "version": "1.0.0-alpha.229",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.164",
50
- "@lunora/agent": "1.0.0-alpha.146",
51
- "@lunora/container": "1.0.0-alpha.60",
52
- "@lunora/errors": "1.0.0-alpha.44",
49
+ "@lunora/advisor": "1.0.0-alpha.165",
50
+ "@lunora/agent": "1.0.0-alpha.147",
51
+ "@lunora/container": "1.0.0-alpha.61",
52
+ "@lunora/errors": "1.0.0-alpha.45",
53
53
  "@lunora/platform": "1.0.0-alpha.41",
54
- "@lunora/queue": "1.0.0-alpha.73",
55
- "@lunora/scheduler": "1.0.0-alpha.91",
56
- "@lunora/values": "1.0.0-alpha.55",
57
- "@lunora/workflow": "1.0.0-alpha.66",
54
+ "@lunora/queue": "1.0.0-alpha.74",
55
+ "@lunora/scheduler": "1.0.0-alpha.92",
56
+ "@lunora/values": "1.0.0-alpha.56",
57
+ "@lunora/workflow": "1.0.0-alpha.67",
58
58
  "jiti": "^2.7.0",
59
59
  "quicktype-core": "^26.0.0",
60
60
  "ts-morph": "^28.0.0"
@@ -1 +0,0 @@
1
- import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as C}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as R}from"node:module";import{join as F}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{r as B,p as V}from"./parse-validator-C94Yiabo.mjs";const q=(e,n)=>`table "${e}" is .global() and declares vector index "${n}". 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.`,J=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}},U=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}:{}}),m=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:U(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=m(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=J(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([a,o])=>[a,m(o)]));break}case"record":{s.valueType=m(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=m(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(a=>m(a));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,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(t).map(([r,a])=>[r,m(a)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([o,l])=>G(l,o)),r=e.vectorIndexes??{},a=Object.entries(r??{}).map(([o,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:o,table:l.table??""}));return{bareTables:s,bareVectorIndexes:a,key:n}},H=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},Q=e=>{const n=H(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const a=r.getModuleSpecifierValue();for(const o of r.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===n)return{importedName:o.getName(),moduleSpecifier:a,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:a,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:a,propertyPath:[]}}},X=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},Y=(e,n)=>{const t=Q(e);if(t)try{const s=R(F(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),a=s(r),o=X(a,t);return typeof o!="object"||o===null?void 0:W(o)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,n)=>{const t=u(e,n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=b(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},x=(e,n)=>{const t=b(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},O=(e,n)=>{const t=b(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},h=(e,n)=>{const t=b(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,n)=>{const t=h(e,n);return t!==void 0&&t.length>0?t:void 0},N=(e,n,t,s,r)=>{let a=e;for(;;){const o=a.getParent();if(!o||!i.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!i.isCallExpression(l))break;if(o.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw f(c,`unknown ${t} ${JSON.stringify(g)} — expected ${r}`);return g}a=l}},ne=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.`,re=new Set(["cascade","restrict","set null"]),se=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),ie=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),P=/^[A-Za-z_$][\w$]*$/u,w=(e,n)=>{if(se.has(e))throw f(n,`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(ie.has(e))throw f(n,`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(!P.test(e))throw f(n,`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.`)},oe=e=>e&&re.has(e)?e:void 0,ae=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},le=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,a]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const o=r.getLiteralText();let l="_unknown_",c="_id",g;return a&&i.isObjectLiteralExpression(a)&&(l=d(a,"field")??l,c=d(a,"references")??c,g=s==="one"?oe(d(a,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:o}},ce=e=>{const n=ae(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=le(s);r&&t.push(r)}return t},de=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),a=`${s}${r.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${a}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},fe=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=u(e,"unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},ue=e=>{const[n,t,s]=e,r=fe(s),a=y(n),o=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of o)if(!i.isStringLiteral(c))throw f(c,`index "${a}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>i.isStringLiteral(c));for(const c of l)de(c,c.getLiteralText(),a);return{fields:l.map(c=>c.getLiteralText()),name:a,unique:r}},pe=e=>{const[n,t]=e;let s="_unknown_",r,a,o,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=h(t,"filterFields"),a=d(t,"language"),o=O(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:a,name:y(n),staged:o,strategy:l}},ge=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"precision")),{field:s,name:y(n),precision:r}},me=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=x(t,"after")),{after:r,field:s}},be=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},xe=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const a=u(t,"sortBy");if(a&&i.isPropertyAssignment(a)){const o=a.getInitializer();o&&i.isArrayLiteralExpression(o)&&(s=o.getElements().map(l=>be(l)).filter(l=>l!==void 0))}r=h(t,"partitionBy")}return{name:y(n),partitionBy:r,sortBy:s}},he=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},ye=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},ve=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=u(e,"field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},Ee=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:te(n,"columns"),hasReconcile:u(n,"reconcileEveryMs")!==void 0,hasSoftDelete:u(n,"softDeleteColumn")!==void 0,hasTenantBy:u(n,"tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},Ie=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ge(t));break}case"global":{e.shardMode="global",e.globalBackend=ye(t);break}case"index":{e.indexes.push(ue(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(xe(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ce(r));break}case"searchIndex":{e.searchIndexes.push(pe(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:ve(t[0])};break}case"source":{e.externalSource=Ee(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=me(t);break}case"vectorize":{const r=he(t,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],we=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const a of L){const o=`${r.name}${a}`;if(!s.has(o))continue;const l=a==="__vocab"?`the \`fts5vocab\` companion for "${o}" 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 "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw f(e,`table "${n}" declares search indexes "${r.name}" and "${o}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${o}" as its "${a}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Se=(e,n,t)=>{if(t.ttl!==void 0&&t.shardMode==="global")throw f(e,ne(n))},_=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const a=r.getExpression(),o=r.getArguments();if(i.isPropertyAccessExpression(a))Ie(t,a.getName(),o,n),r=a.getExpression();else if(i.isIdentifier(a)&&a.getText()==="defineTable"){const l=o[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw f(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),we(e,n,t.searchIndexes),Se(e,n,t),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},j=(e,n=[],t=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const o=B(r.getExpression());o!==void 0&&!s.has(o)&&j(o,n,t,s);continue}if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(a){const o=I(r);if(w(o,r.getNameNode()),t.has(o))throw f(r.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(o),n.push(_(a,o))}}return n},ke=e=>{const n=u(e,"source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},Te=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),a=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(d(s,"metric")),name:a,table:ke(s)}},$=e=>{const n=[];for(const t of e.getProperties()){const s=Te(t);s&&n.push(s)}return n},S=(e,n)=>`${e}_${n}`,Le=(e,n)=>{if(!P.test(e))throw f(n,`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.`)},E=(e,n,t)=>t.has(e)?S(n,e):e,Oe=(e,n,t)=>{const s=S(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:E(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:E(r.table,n,t)}))}},Ae=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ne=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Pe=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},_e=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},je=(e,n)=>{const t=Ae(e);if(t){if(i.isPropertyAccessExpression(n)){const s=_e(t);return s?b(s,n.getName()):void 0}return t}},$e=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ne(n))return n;const s=Pe(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,o=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=je(o,n)}},De=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),keyNode:n,options:t}},ze=e=>{const n=u(e,"tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(!a)continue;const o=I(r);w(o,r.getNameNode()),s.push(_(a,o))}return s},Me=e=>{const n=u(e,"vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:$(t)},D=(e,n,t,s)=>{Le(e,s);const r=new Set(n.map(l=>l.name)),a=n.map(l=>Oe(l,e,r)),o=t.map(l=>({...l,name:S(e,l.name),table:E(l.table,e,r)}));return{tables:a,vectorIndexes:o}},Ce=(e,n,t)=>D(e,ze(t),Me(t),n),Re=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=$e(t);if(!s){if(n!==void 0){const a=Y(t,n);if(a){for(const o of a.bareTables)w(o.name,t);return D(a.key,a.bareTables,a.bareVectorIndexes,t)}}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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=De(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ce(r.key,r.keyNode,r.options)},Fe=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},Be=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=[];for(const a of Fe(e)){const o=Re(a,t);if(o){for(const l of o.tables){if(s.has(l.name))throw f(a,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...o.vectorIndexes)}}return r},Ve=new Set(["eu","fedramp","us"]),qe=e=>N(e,"jurisdiction","jurisdiction",Ve,'"eu", "us", or "fedramp"'),Je=e=>{let n=e;for(;;){const t=n.getParent(),s=t?.getParent();if(!t||!i.isPropertyAccessExpression(t)||!s||!i.isCallExpression(s))return!1;if(t.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuth")===!0}n=s}},Ue=new Set(["required"]),Ke=e=>N(e,"rls","rls mode",Ue,'"required"'),et=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(C.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${n}`);const a=r.getArguments()[0];if(!a||!i.isObjectLiteralExpression(a))throw f(r,"defineSchema() expects an object literal");const o=j(a),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Be(r,o,t),k=[...o.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(o.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw f(r,q(v.table,v.name));return{jurisdiction:qe(r),...Je(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:Ke(r),tables:o,vectorIndexes:k}};export{et as default};