@lunora/codegen 1.0.0-alpha.138 → 1.0.0-alpha.139
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/{GENERATED_HEADER-Gajqa19J.mjs → GENERATED_HEADER-BT6vm22F.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-X4hs2-hb.mjs → OPENRPC_VERSION-CgE7dKyx.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-D1R4OORJ.mjs → SCHEMA_SNAPSHOT_FILENAME--KH8_wfq.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-CGl09_Pi.mjs → buildOpenApiDocument-DKGnSpzJ.mjs} +1 -1
- package/dist/packem_shared/{emit-BQNGQnaS.mjs → emit-CMv9Snzk.mjs} +71 -71
- package/dist/packem_shared/{emitApp-BQcIWzkh.mjs → emitApp-BVvidAuv.mjs} +1 -1
- package/package.json +1 -1
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-CftvRWB8.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-D1qA0h5m.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-C35kkayg.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-oKaARMoA.mjs";import{default as C}from"./packem_shared/discoverCrons-wXBfQcfn.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BasxlnVS.mjs";import{default as F}from"./packem_shared/discoverFunctions-BBDziFXy.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-Dmow2gql.mjs";import{default as G}from"./packem_shared/discoverInserts-C5l2INmE.mjs";import{d as b}from"./packem_shared/index-CCDlo9L7.mjs";import{default as y}from"./packem_shared/discoverMigrations-CWH7T6qz.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-DJvAhDlD.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-JsO91i57.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-B-eIjru_.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/queries-B_xEHIeL.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-D229WtRm.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-BbfOpwE4.mjs";import{default as ae}from"./packem_shared/discoverRlsProcedures-CRshfYZE.mjs";import{default as me}from"./packem_shared/discoverRlsMetadata-DGUGYgWs.mjs";import{discoverSandboxUsage as fe}from"./packem_shared/discoverSandboxUsage-DdewAOuj.mjs";import{default as ce}from"./packem_shared/discoverSchema-Bp8DcNq7.mjs";import{SHAPES_FILENAME as Se,discoverShapes as le}from"./packem_shared/SHAPES_FILENAME-BTdasTq2.mjs";import{default as xe}from"./packem_shared/discoverStorageRulesMetadata-gyO60A5S.mjs";import{WORKFLOWS_FILENAME as ue,discoverWorkflows as ve}from"./packem_shared/WORKFLOWS_FILENAME-DRaiCNa6.mjs";import{G as ge,e as Oe,a as Re,b as Me,c as he,d as Ce,f as _e,g as Te,h as Ie,i as Le,j as Fe,k as De,l as Pe,m as Ue}from"./packem_shared/emit-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-D1qA0h5m.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-C35kkayg.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-oKaARMoA.mjs";import{default as C}from"./packem_shared/discoverCrons-wXBfQcfn.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BasxlnVS.mjs";import{default as F}from"./packem_shared/discoverFunctions-BBDziFXy.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-Dmow2gql.mjs";import{default as G}from"./packem_shared/discoverInserts-C5l2INmE.mjs";import{d as b}from"./packem_shared/index-CCDlo9L7.mjs";import{default as y}from"./packem_shared/discoverMigrations-CWH7T6qz.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-DJvAhDlD.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-JsO91i57.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-B-eIjru_.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/queries-B_xEHIeL.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-D229WtRm.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-BbfOpwE4.mjs";import{default as ae}from"./packem_shared/discoverRlsProcedures-CRshfYZE.mjs";import{default as me}from"./packem_shared/discoverRlsMetadata-DGUGYgWs.mjs";import{discoverSandboxUsage as fe}from"./packem_shared/discoverSandboxUsage-DdewAOuj.mjs";import{default as ce}from"./packem_shared/discoverSchema-Bp8DcNq7.mjs";import{SHAPES_FILENAME as Se,discoverShapes as le}from"./packem_shared/SHAPES_FILENAME-BTdasTq2.mjs";import{default as xe}from"./packem_shared/discoverStorageRulesMetadata-gyO60A5S.mjs";import{WORKFLOWS_FILENAME as ue,discoverWorkflows as ve}from"./packem_shared/WORKFLOWS_FILENAME-DRaiCNa6.mjs";import{G as ge,e as Oe,a as Re,b as Me,c as he,d as Ce,f as _e,g as Te,h as Ie,i as Le,j as Fe,k as De,l as Pe,m as Ue}from"./packem_shared/emit-CMv9Snzk.mjs";import{emitApp as He}from"./packem_shared/emitApp-BVvidAuv.mjs";import{buildOpenApiDocument as ke,emitOpenApi as ye,emitOpenApiModule as We}from"./packem_shared/buildOpenApiDocument-DKGnSpzJ.mjs";import{OPENRPC_VERSION as Ke,buildOpenRpcDocument as Ve,emitOpenRpc as ze,emitOpenRpcModule as Qe}from"./packem_shared/OPENRPC_VERSION-CgE7dKyx.mjs";import{DEFAULT_TARGET as qe,platformMatrixIds as Be,readProjectTarget as Je,resolveCodegenTarget as Ye}from"./packem_shared/DEFAULT_TARGET-CrhWLUK7.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Ze,createCodegenProject as $e,findTsconfig as er,refreshCodegenProject as rr,runCodegen as or}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME--KH8_wfq.mjs";import{SchemaSnapshotParseError as sr,buildSchemaSnapshot as ar,evaluateSchemaDrift as ir,parseSchemaSnapshot as mr}from"./packem_shared/SchemaSnapshotParseError-D2h88OHU.mjs";import{schemaFromIr as fr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as cr,validatorIrToJsonSchema as nr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as lr,SDK_TARGETS as Er,generateSdk as xr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as ur,secretKindOf as vr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as gr,findSolutionByMessage as Or}from"@lunora/errors";import{isTypedSchema as Mr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,qe as DEFAULT_TARGET,T as FLAGS_FILENAME,ge as GENERATED_HEADER,cr as LUNORA_ERROR_CODES,gr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,Ke as OPENRPC_VERSION,ee as QUEUES_FILENAME,Ze as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,lr as SDK_LANGUAGES,Er as SDK_TARGETS,Se as SHAPES_FILENAME,sr as SchemaSnapshotParseError,e as VERSION,ue as WORKFLOWS_FILENAME,ke as buildOpenApiDocument,Ve as buildOpenRpcDocument,ar as buildSchemaSnapshot,$e as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,M as discoverContainers,C as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,z as discoverNondeterministicCalls,q as discoverNotifyCalls,B as discoverNotifyConfig,Z as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,me as discoverRlsMetadata,ae as discoverRlsProcedures,fe as discoverSandboxUsage,ce as discoverSchema,le as discoverShapes,xe as discoverStorageRulesMetadata,ve as discoverWorkflows,Oe as emitAgents,Re as emitApi,He as emitApp,Me as emitCollections,he as emitContainers,Ce as emitCrons,_e as emitDataModel,Te as emitDrizzleSchema,Ie as emitFunctions,ye as emitOpenApi,We as emitOpenApiModule,ze as emitOpenRpc,Qe as emitOpenRpcModule,Le as emitServer,Fe as emitShard,De as emitVectors,Pe as emitWorkflows,Ue as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ir as evaluateSchemaDrift,Or as findLunoraSolution,er as findTsconfig,m as formatAdvisories,xr as generateSdk,Mr as isTypedSchema,d as lintSchema,mr as parseSchemaSnapshot,Be as platformMatrixIds,Y as readPackageDependencies,Je as readProjectTarget,ur as redact,rr as refreshCodegenProject,Ye as resolveCodegenTarget,or as runCodegen,fr as schemaFromIr,vr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,nr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-CMv9Snzk.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-CMv9Snzk.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as b,mkdirSync as ss,readFileSync as At,writeFileSync as ns,rmSync as rs}from"node:fs";import{join as f,dirname as fe}from"node:path";import{performance as pe}from"node:perf_hooks";import{runAdvisor as is}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Xe}from"ts-morph";import{serializeSchemaSnapshot as os}from"./SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{toAdvisorContext as as}from"./formatAdvisories-CkEu1eye.mjs";import{discoverAgents as cs}from"./AGENTS_FILENAME-D1qA0h5m.mjs";import{discoverContainers as ls}from"./CONTAINERS_FILENAME-oKaARMoA.mjs";import{diagnosticAt as se}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ne}from"./module-specifiers-WF8iAydP.mjs";import{C as ge,i as us,f as ds,n as fs,j as ps,b as gs,c as ms,l as hs,e as xs,o as Es,d as vs,k as Ss,g as As,p as ys,m as Ns,a as bs,h as Ps}from"./emit-
|
|
1
|
+
import{existsSync as b,mkdirSync as ss,readFileSync as At,writeFileSync as ns,rmSync as rs}from"node:fs";import{join as f,dirname as fe}from"node:path";import{performance as pe}from"node:perf_hooks";import{runAdvisor as is}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Xe}from"ts-morph";import{serializeSchemaSnapshot as os}from"./SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{toAdvisorContext as as}from"./formatAdvisories-CkEu1eye.mjs";import{discoverAgents as cs}from"./AGENTS_FILENAME-D1qA0h5m.mjs";import{discoverContainers as ls}from"./CONTAINERS_FILENAME-oKaARMoA.mjs";import{diagnosticAt as se}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ne}from"./module-specifiers-WF8iAydP.mjs";import{C as ge,i as us,f as ds,n as fs,j as ps,b as gs,c as ms,l as hs,e as xs,o as Es,d as vs,k as Ss,g as As,p as ys,m as Ns,a as bs,h as Ps}from"./emit-CMv9Snzk.mjs";import{l as g,a as E,f as P,p as y,g as yt,j as Ee,h as Is,i as L,b as Ze,r as Nt,e as ws}from"./ast-CjWtsS6S.mjs";import Ts from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as Cs}from"./QUEUES_FILENAME-D229WtRm.mjs";import{discoverSandboxUsage as Fs}from"./discoverSandboxUsage-DdewAOuj.mjs";import Os from"./discoverStorageRulesMetadata-gyO60A5S.mjs";import{discoverWorkflows as Rs}from"./WORKFLOWS_FILENAME-DRaiCNa6.mjs";import{gatePlatformFeatures as Ls,resolveCodegenTarget as Ds}from"./DEFAULT_TARGET-CrhWLUK7.mjs";import{i as T,a as M,e as v,r as ks,b as Ms,s as re,c as Ks,f as _s,d as zs}from"./queries-B_xEHIeL.mjs";import{a as A,c as K,d as bt,e as Us}from"./classify-procedure-call-AKeIK05y.mjs";import Bs from"./discoverAuthApiCalls-C35kkayg.mjs";import qs from"./discoverCrons-wXBfQcfn.mjs";import Je from"./discoverFunctions-BBDziFXy.mjs";import{i as $s,r as js,e as Vs}from"./unwrap-handler-return-CmIWbykC.mjs";import et from"./discoverHttpRoutes-Dmow2gql.mjs";import Ws from"./discoverInserts-C5l2INmE.mjs";import{m as Ae,a as X,s as Pt,d as Hs}from"./index-CCDlo9L7.mjs";import{e as It}from"./exported-procedure-chains-MlZRKqSD.mjs";import Gs from"./discoverMigrations-CWH7T6qz.mjs";import{MUTATORS_FILENAME as Ys,isDefineMutatorCallee as Qs,discoverMutators as tt}from"./MUTATORS_FILENAME-DJvAhDlD.mjs";import Xs from"./discoverNondeterministicCalls-JsO91i57.mjs";import{discoverNotifyConfig as Zs,discoverNotifyCalls as Js}from"./NOTIFY_FILENAME-B-eIjru_.mjs";import en from"./discoverR2sqlCalls-BbfOpwE4.mjs";import tn from"./discoverRlsProcedures-CRshfYZE.mjs";import sn from"./discoverRlsMetadata-DGUGYgWs.mjs";import nn from"./discoverSchema-Bp8DcNq7.mjs";import{secretKindOf as rn,redact as on,isHeuristicSecretKind as an,isSecretishName as cn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as ln}from"./SHAPES_FILENAME-BTdasTq2.mjs";import{emitApp as un}from"./emitApp-BVvidAuv.mjs";import{buildOpenApiDocument as dn,emitOpenApiModule as fn}from"./buildOpenApiDocument-DKGnSpzJ.mjs";import{buildOpenRpcDocument as pn,emitOpenRpcModule as gn}from"./OPENRPC_VERSION-CgE7dKyx.mjs";import{s as mn}from"./parse-validator-BFTp87yz.mjs";import{buildSchemaSnapshot as hn}from"./SchemaSnapshotParseError-D2h88OHU.mjs";const xn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},En=(e,t)=>{if(t===void 0)return;const s=xn(e).filter(i=>!t.has(i.name));if(s.length===0)return;const n=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
|
|
2
2
|
`);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${n}
|
|
4
4
|
|
package/dist/packem_shared/{buildOpenApiDocument-CGl09_Pi.mjs → buildOpenApiDocument-DKGnSpzJ.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-CMv9Snzk.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as dt}from"@lunora/agent/component";import{LunoraError as
|
|
1
|
+
import{agentComponent as dt}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as kn,hashSchemaSnapshot as xn}from"./SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";const ut=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
|
|
2
2
|
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
3
3
|
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -43,7 +43,7 @@ ${gt("source")}${r.pre}return { ${r.entries} };
|
|
|
43
43
|
}`},$=`// GENERATED by @lunora/codegen — do not edit.
|
|
44
44
|
// Run \`lunora codegen\` to regenerate.
|
|
45
45
|
|
|
46
|
-
`,
|
|
46
|
+
`,oe=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},ft=/^[A-Za-z_$][\w$]*$/u,Ln=/^[\w./-]+$/u,g=(e,t)=>{if(!ft.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>ft.test(e)?e:JSON.stringify(e),X=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),_n={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},En=e=>{if(e===void 0)return"unknown";if(!pt.test(e))throw new Z("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=_n[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?A(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return g(n,"v.id() table name"),`Id<"${n}">`}case"literal":return En(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>bt(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?A(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?A(e.keyType):"string",r=e.valueType?A(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>A(n)).join(" | "):"never";default:return"unknown"}},bt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>bt(n,r)).join("; ")} }`},yt=e=>e.kind==="optional"||!!e.column?.hasDefault,ae=e=>e.kind==="optional"&&e.inner?e.inner:e,Dn=e=>{g(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=ae(o),i=A(s),a=q(r);return yt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
|
|
47
47
|
`),n=t?`
|
|
48
48
|
${t}
|
|
49
49
|
`:"";return`export interface Insert_${e.name} {
|
|
@@ -160,7 +160,7 @@ export interface Relations {
|
|
|
160
160
|
${y}
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
-
`,Ge)},Pn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,wt=/^(?:\.\.?\/)*_generated\//u,kt=/\.[A-Za-z]\w*$/u,Fn=e=>e.replaceAll(Pn,(t,n)=>{const r=n.replace(wt,"./");return`import("${kt.test(r)?r:`${r}.js`}")`}),Mn=/import\("(?<spec>[^"]+)"\)/gu,it="node_modules/",Bn=/^@types\//u,jn=e=>e.replaceAll(Mn,(t,n)=>{const r=n.lastIndexOf(it);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+it.length);return o===""||Bn.test(o)?t:`import("${o}")`}),qn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Wn=/^(?:\.\.?\/)+/u,Un=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Kn=(e,t)=>e.replaceAll(qn,(n,r)=>{if(wt.test(r.replace(Wn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Un(`${o}/${r}`)}`;return`import("${kt.test(i)?i:`${i}.js`}")`}),E=(e,t)=>Fn(Kn(jn(e),t)),Qn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Vn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Qn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Hn={flags:new Set(["/web"]),platform:new Set},xt=(e,t)=>t?e.replaceAll(Vn,(n,r,o)=>{const s=Hn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Je=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),vt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),ze=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},lt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=E(
|
|
163
|
+
`,Ge)},Pn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,wt=/^(?:\.\.?\/)*_generated\//u,kt=/\.[A-Za-z]\w*$/u,Fn=e=>e.replaceAll(Pn,(t,n)=>{const r=n.replace(wt,"./");return`import("${kt.test(r)?r:`${r}.js`}")`}),Mn=/import\("(?<spec>[^"]+)"\)/gu,it="node_modules/",Bn=/^@types\//u,jn=e=>e.replaceAll(Mn,(t,n)=>{const r=n.lastIndexOf(it);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+it.length);return o===""||Bn.test(o)?t:`import("${o}")`}),qn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Wn=/^(?:\.\.?\/)+/u,Un=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Kn=(e,t)=>e.replaceAll(qn,(n,r)=>{if(wt.test(r.replace(Wn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Un(`${o}/${r}`)}`;return`import("${kt.test(i)?i:`${i}.js`}")`}),E=(e,t)=>Fn(Kn(jn(e),t)),Qn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Vn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Qn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Hn={flags:new Set(["/web"]),platform:new Set},xt=(e,t)=>t?e.replaceAll(Vn,(n,r,o)=>{const s=Hn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Je=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),vt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),ze=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},lt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=E(xe(s.args),s.filePath),a=E(vt(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
|
|
164
164
|
`);return` ${q(N(n))}: {
|
|
165
165
|
${o}
|
|
166
166
|
};`};return ze(e).map(n=>t(n)).join(`
|
|
@@ -173,7 +173,7 @@ export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
|
173
173
|
readonly name: string;
|
|
174
174
|
}
|
|
175
175
|
`,e.length>0){const o=[...e].toSorted((a,c)=>a.exportName.localeCompare(c.exportName)),s=o.map(a=>` ${a.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${a.exportName}>>;`).join(`
|
|
176
|
-
`),i=o.map(a=>` ${a.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.exportName)} },`).join(`
|
|
176
|
+
`),i=o.map(a=>` ${X(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.exportName)} },`).join(`
|
|
177
177
|
`);r+=`
|
|
178
178
|
/** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
|
|
179
179
|
export interface WorkflowsRef {
|
|
@@ -185,7 +185,7 @@ ${i}
|
|
|
185
185
|
};
|
|
186
186
|
`,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
187
187
|
`)}if(t.length>0){const o=[...t].toSorted((a,c)=>a.exportName.localeCompare(c.exportName)),s=o.map(a=>` ${a.exportName}: WorkflowReference<AgentRunInput>;`).join(`
|
|
188
|
-
`),i=o.map(a=>` ${a.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.name)} },`).join(`
|
|
188
|
+
`),i=o.map(a=>` ${X(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.name)} },`).join(`
|
|
189
189
|
`);r+=`
|
|
190
190
|
/** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
|
|
191
191
|
export interface AgentsRef {
|
|
@@ -196,7 +196,7 @@ export const agents: AgentsRef = {
|
|
|
196
196
|
${i}
|
|
197
197
|
};
|
|
198
198
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
199
|
-
`)}return{block:r,importLine:n.join("")}},Jn=()=>Object.keys(dt().functions).toSorted((e,t)=>e.localeCompare(t)),Rt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),zn=()=>new Set(Object.entries(dt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Yn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Rt(t),o=zn(),s=t.find(a=>N(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new
|
|
199
|
+
`)}return{block:r,importLine:n.join("")}},Jn=()=>Object.keys(dt().functions).toSorted((e,t)=>e.localeCompare(t)),Rt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),zn=()=>new Set(Object.entries(dt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Yn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Rt(t),o=zn(),s=t.find(a=>N(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new Z("INTERNAL",`@lunora/codegen: "agents:${s.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${s.exportName}" export in ${s.filePath}`);const i=Jn().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
200
200
|
`,lines:i.map(a=>` "agents:${a}": lunoraAgentRuntimeFunctions.${a} as unknown as RegisteredLunoraFunction,`).join(`
|
|
201
201
|
`),prelude:`
|
|
202
202
|
/**
|
|
@@ -205,13 +205,13 @@ ${i}
|
|
|
205
205
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
206
206
|
*/
|
|
207
207
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
208
|
-
`}},Xn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>N(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new
|
|
209
|
-
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},Zn=(e,t)=>{if(e.length===0)return[];const n=Rt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},er=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>N(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},tr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=ze(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=E(d.chunkType??"unknown",d.filePath),m=E(
|
|
208
|
+
`}},Xn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>N(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new Z("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
209
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},Zn=(e,t)=>{if(e.length===0)return[];const n=Rt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},er=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>N(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},tr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=ze(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=E(d.chunkType??"unknown",d.filePath),m=E(xe(d.searchParams),d.filePath),y=E(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${p}, ${m}, ${y}>;`}).join(`
|
|
210
210
|
`);return` ${q(N(i))}: {
|
|
211
211
|
${c}
|
|
212
212
|
};`}).join(`
|
|
213
|
-
`),o=n.map(([i,a])=>{const c=a.map(d=>` ${
|
|
214
|
-
`);return` ${
|
|
213
|
+
`),o=n.map(([i,a])=>{const c=a.map(d=>` ${X(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
|
|
214
|
+
`);return` ${X(N(i))}: {
|
|
215
215
|
${c}
|
|
216
216
|
},`}).join(`
|
|
217
217
|
`);return{block:`
|
|
@@ -223,7 +223,7 @@ ${r}
|
|
|
223
223
|
export const httpStreams: HttpStreamsRef = {
|
|
224
224
|
${o}
|
|
225
225
|
};
|
|
226
|
-
`,body:r}},eo=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=
|
|
226
|
+
`,body:r}},eo=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=oe(s),c=[...n.filter(v=>v.visibility!=="internal"),...Zn(t,n),...er(o,n)],d=n.filter(v=>v.visibility==="internal"),p=lt(c),m=lt(d),y=tr(r),u=`${p}
|
|
227
227
|
${m}
|
|
228
228
|
${y.body}`,l=Je(u),f=l.length>0?`
|
|
229
229
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
@@ -259,7 +259,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
259
259
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
260
260
|
*/
|
|
261
261
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
262
|
-
`:"",no=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=
|
|
262
|
+
`:"",no=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=oe(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{g(c.exportName,"shape export name");const d=o(c),p=E(xe(c.args),c.filePath),m=Object.keys(c.args).length>0,y=m?` args: ${p};`:` args?: ${p};`,u=m?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
|
|
263
263
|
export interface ${Ve(l)} {
|
|
264
264
|
${y}
|
|
265
265
|
/**
|
|
@@ -321,7 +321,7 @@ ${s}
|
|
|
321
321
|
}
|
|
322
322
|
|
|
323
323
|
return (await registered.handler(context, args ?? {})) as R;
|
|
324
|
-
};`,or=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,nr(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,f])=>{if(!Ln.test(l))throw new
|
|
324
|
+
};`,or=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,nr(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,f])=>{if(!Ln.test(l))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${f} from "../${l}.js";`}).join(`
|
|
325
325
|
`),a=e.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
326
326
|
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
327
327
|
`),d=n.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
@@ -336,22 +336,22 @@ ${y}
|
|
|
336
336
|
${c}
|
|
337
337
|
`:"",mutatorPaths:m,shapeBody:p.length>0?`
|
|
338
338
|
${p}
|
|
339
|
-
`:""}},ar=e=>{const t=ze(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=E(
|
|
339
|
+
`:""}},ar=e=>{const t=ze(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=E(xe(a.args),a.filePath),d=c==="{}"?"?":"",p=E(vt(a),a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
|
|
340
340
|
`);return` ${q(N(o))}: {
|
|
341
341
|
${i}
|
|
342
342
|
};`}).join(`
|
|
343
|
-
`);return{implementation:t.map(([o,s])=>{const i=N(o),a=s.map(c=>` ${c.exportName}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
|
|
344
|
-
`);return` ${
|
|
343
|
+
`);return{implementation:t.map(([o,s])=>{const i=N(o),a=s.map(c=>` ${X(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
|
|
344
|
+
`);return` ${X(i)}: {
|
|
345
345
|
${a}
|
|
346
346
|
},`}).join(`
|
|
347
|
-
`),types:n}},sr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=
|
|
348
|
-
`:"",
|
|
347
|
+
`),types:n}},sr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=ae(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},ro=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasFlags:a=!1,hasHyperdrive:c=!1,hasImages:d=!1,hasKv:p=!1,hasNotify:m=!1,hasPayments:y=!1,hasPipelines:u=!1,hasR2sql:l=!1,hasX402:f=!1,identity:k,queues:R=[],schema:x,storageRuleBuckets:I=[],useUmbrella:T=!1,workflows:_=[]}={})=>{const v=oe(T),w=sr(x??{tables:[]},I).map(h=>JSON.stringify(h)).join(" | "),F=o?`import type { LunoraAi } from "@lunora/ai";
|
|
348
|
+
`:"",se=o?`
|
|
349
349
|
readonly ai: LunoraAi;`:"",M=y?`import type { LunoraPayment } from "@lunora/payment";
|
|
350
|
-
`:"",
|
|
351
|
-
readonly payments: LunoraPayment;`:"",
|
|
350
|
+
`:"",ie=y?`
|
|
351
|
+
readonly payments: LunoraPayment;`:"",le=f?`import type { X402Pay } from "@lunora/x402/pay";
|
|
352
352
|
`:"",W=f?`
|
|
353
353
|
readonly x402: X402Pay;`:"",C=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
354
|
-
`:"",
|
|
354
|
+
`:"",ee=t.length>0?`
|
|
355
355
|
readonly containers: {${t.map(h=>`
|
|
356
356
|
readonly ${h.exportName}: ContainerAccessor;`).join("")}
|
|
357
357
|
};`:"",L=[...o?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(g(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
|
|
@@ -377,8 +377,8 @@ ${L}`:""}
|
|
|
377
377
|
}
|
|
378
378
|
|
|
379
379
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
380
|
-
export type Env = CloudflareBindings;`,B=(h,qe
|
|
381
|
-
readonly vectors: VectorSearch<VectorIndexName>;`:"",
|
|
380
|
+
export type Env = CloudflareBindings;`,B=(h,qe,Ne)=>{const re=Rn.get(h);if(re!==void 0&&re.tier!==Ne)throw new Z("INTERNAL",`@lunora/codegen: capability "${h}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Ne}" context — update whichever is wrong.`);return qe?re?.field??"":""},ce=B("kv",p,"every"),de=B("analytics",s,"every"),Ae=B("hyperdrive",c,"action"),Oe=B("browser",i,"action"),Ie=B("images",d,"action"),ue=B("pipelines",u,"action"),V=B("r2sql",l,"action"),P=(x?.vectorIndexes.length??0)>0,H=P?' | "vectors"':"",te=P?`
|
|
381
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",pe=P?`
|
|
382
382
|
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",G=P?`import type { VectorSearch, VectorSearchReader } from "${v.server}";
|
|
383
383
|
import type { VectorIndexName } from "./dataModel.js";
|
|
384
384
|
`:"",U=r?`
|
|
@@ -389,7 +389,7 @@ import type { VectorIndexName } from "./dataModel.js";
|
|
|
389
389
|
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
390
390
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
391
391
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
392
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",j=_.length>0,
|
|
392
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",j=_.length>0,ne=j?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
393
393
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
394
394
|
`:"",Ce=j?`
|
|
395
395
|
|
|
@@ -404,10 +404,10 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
404
404
|
export interface LunoraWorkflows {
|
|
405
405
|
${_.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
|
|
406
406
|
`)}
|
|
407
|
-
}`:"",
|
|
408
|
-
readonly workflows: LunoraWorkflows;`:"",
|
|
407
|
+
}`:"",ve=j?' | "workflows"':"",Re=j?`
|
|
408
|
+
readonly workflows: LunoraWorkflows;`:"",he=R.length>0,Le=he?`import type { QueueProducer } from "@lunora/queue";
|
|
409
409
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
410
|
-
`:"",_e=
|
|
410
|
+
`:"",_e=he?`
|
|
411
411
|
|
|
412
412
|
/** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
|
|
413
413
|
type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
|
|
@@ -416,15 +416,15 @@ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body }
|
|
|
416
416
|
export interface LunoraQueues {
|
|
417
417
|
${R.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
|
|
418
418
|
`)}
|
|
419
|
-
}`:"",
|
|
420
|
-
readonly queues: LunoraQueues;`:"",
|
|
421
|
-
`:"",De=
|
|
419
|
+
}`:"",Se=he?`
|
|
420
|
+
readonly queues: LunoraQueues;`:"",me=e.length>0,Ee=me?`import type { AgentHandle } from "@lunora/agent";
|
|
421
|
+
`:"",De=me?`
|
|
422
422
|
|
|
423
423
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
424
424
|
export interface LunoraAgents {
|
|
425
425
|
${e.map(h=>(g(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
|
|
426
426
|
`)}
|
|
427
|
-
}`:""
|
|
427
|
+
}`:"",$e=me?`
|
|
428
428
|
readonly agents: LunoraAgents;`:"",Pe=k?`import type { InferIdentity } from "${v.server}";
|
|
429
429
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
430
430
|
`:"",Fe=k?`
|
|
@@ -433,12 +433,12 @@ import type * as lunoraIdentityContract from "../identity.js";
|
|
|
433
433
|
export type Identity = InferIdentity<typeof lunoraIdentityContract.${k.exportName}>;
|
|
434
434
|
|
|
435
435
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
436
|
-
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",
|
|
436
|
+
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",ge=k?' | "auth"':"",fe=k?`
|
|
437
437
|
readonly auth: NarrowedAuth;`:"",Me=k?", Identity":"",Be=n?`import type * as lunoraEnvContract from "../env.js";
|
|
438
438
|
`:"",je=n?`
|
|
439
439
|
|
|
440
440
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
441
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",
|
|
441
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${$}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${v.server}";
|
|
442
442
|
import type {
|
|
443
443
|
ActionBuilder,
|
|
444
444
|
ActionCtx as ActionCtxBase,
|
|
@@ -495,7 +495,7 @@ export type {
|
|
|
495
495
|
} from "${v.serverDataModel}";
|
|
496
496
|
|
|
497
497
|
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
498
|
-
${G}${F}${M}${
|
|
498
|
+
${G}${F}${M}${le}${C}${ne}${Le}${Ee}${Pe}${Be}
|
|
499
499
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
500
500
|
|
|
501
501
|
/**
|
|
@@ -618,22 +618,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
618
618
|
*/
|
|
619
619
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
620
620
|
|
|
621
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${H}${
|
|
621
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${H}${ge}${be}> {
|
|
622
622
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
623
623
|
readonly orm: OrmReader;
|
|
624
|
-
readonly storage: ReadOnlyStorage<StorageBucketName>;${
|
|
624
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${pe}${U}${ce}${K}${Q}${de}${ye}${fe}
|
|
625
625
|
}
|
|
626
626
|
|
|
627
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${H}${
|
|
627
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${H}${ve}${ge}${be}> {
|
|
628
628
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
629
629
|
readonly orm: OrmWriter;
|
|
630
|
-
readonly storage: MutationStorage<StorageBucketName>;${
|
|
630
|
+
readonly storage: MutationStorage<StorageBucketName>;${te}${U}${ce}${K}${Q}${de}${ye}${Re}${Se}${$e}${fe}
|
|
631
631
|
}
|
|
632
632
|
|
|
633
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${H}${
|
|
633
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${H}${ve}${ge}${be}> {
|
|
634
634
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
635
635
|
readonly orm: OrmWriter;
|
|
636
|
-
readonly storage: StorageBase<StorageBucketName>;${
|
|
636
|
+
readonly storage: StorageBase<StorageBucketName>;${te}${U}${se}${ie}${W}${ee}${ce}${K}${Q}${Ae}${Oe}${Ie}${de}${ue}${V}${ye}${Re}${Se}${$e}${fe}
|
|
637
637
|
}
|
|
638
638
|
|
|
639
639
|
/**
|
|
@@ -708,7 +708,7 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Me}>();
|
|
|
708
708
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
709
709
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
710
710
|
};
|
|
711
|
-
`},ir=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${N(n.filePath)}:${n.exportName}`);return t},oo=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=
|
|
711
|
+
`},ir=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${N(n.filePath)}:${n.exportName}`);return t},oo=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:p,importBlock:m,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:f}=or(n,r,o,s),k=Yn(t,n),R=Xn(a,n),x=[k.lines,R.lines].filter(S=>S.length>0).join(`
|
|
712
712
|
`);let I=p;x.length>0&&(I=p.length>0?`${p.trimEnd()}
|
|
713
713
|
${x}
|
|
714
714
|
`:`
|
|
@@ -730,19 +730,19 @@ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${f}};
|
|
|
730
730
|
*/
|
|
731
731
|
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(S=>JSON.stringify(S)).join(", ")}]);
|
|
732
732
|
`:"",F=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
|
|
733
|
-
`:"",
|
|
733
|
+
`:"",se=y.length>0?`
|
|
734
734
|
/**
|
|
735
735
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
736
736
|
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
737
737
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
738
738
|
*/
|
|
739
739
|
${y}
|
|
740
|
-
`:"",M=ar(n),
|
|
740
|
+
`:"",M=ar(n),ie=M.types?`
|
|
741
741
|
${M.types}
|
|
742
|
-
`:"",
|
|
742
|
+
`:"",le=M.implementation?`
|
|
743
743
|
${M.implementation}
|
|
744
744
|
`:"",W=Je(M.types),C=W.length>0?`import type { ${W.join(", ")} } from "./dataModel.js";
|
|
745
|
-
`:"",
|
|
745
|
+
`:"",ee=c?"context":"_context",L=c?`${rr}
|
|
746
746
|
|
|
747
747
|
`:"";return xt(`${$}${m}${k.importLine}${R.importLine}${F}${_}import { LunoraError } from "${d.server}";
|
|
748
748
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
@@ -784,7 +784,7 @@ ${k.prelude}${R.prelude}
|
|
|
784
784
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
785
785
|
*/
|
|
786
786
|
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${I}};
|
|
787
|
-
${
|
|
787
|
+
${se}${v}${w}
|
|
788
788
|
/**
|
|
789
789
|
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
790
790
|
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
@@ -829,10 +829,10 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
829
829
|
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
830
830
|
* \`runAction\` but without re-stating the function path.
|
|
831
831
|
*/
|
|
832
|
-
export interface Caller {${
|
|
832
|
+
export interface Caller {${ie}}
|
|
833
833
|
|
|
834
834
|
${L}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
835
|
-
export const createCaller = (${
|
|
835
|
+
export const createCaller = (${ee}: CallerCtx): Caller => ({${le}});
|
|
836
836
|
|
|
837
837
|
/**
|
|
838
838
|
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
@@ -852,7 +852,7 @@ export interface RegisteredDataMigration {
|
|
|
852
852
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
853
853
|
*/
|
|
854
854
|
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
|
|
855
|
-
`,i)},lr=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=
|
|
855
|
+
`,i)},lr=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=ae(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},cr=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))ae(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},dr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(o=>({fields:[...o.fields],name:o.name,type:"index",...o.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(o=>({fields:[o.field,...o.filterFields??[]],name:o.name,type:"search"})),...(n.geoIndexes??[]).map(o=>({fields:[o.field],name:o.name,type:"geo"})),...n.rankIndexes.map(o=>({fields:o.sortBy.map(s=>s.field),name:o.name,type:"rank"})),...n.vectorIndexes.map(o=>({fields:o.field===void 0?[]:[o.field],name:o.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},ur=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},pr=e=>{if(e.kind!=="union"||e.members===void 0||e.members.length===0)return;const t=[];for(const n of e.members){if(n.kind!=="literal"||n.literalValue===void 0)return;try{const r=JSON.parse(n.literalValue);if(typeof r!="string")return;t.push(r)}catch{return}}return t},hr=(e,t)=>{const n=ae(t),r={name:e,optional:yt(t),type:n.kind};n.kind==="id"&&n.tableName!==void 0&&(r.ref=n.tableName),n.kind==="storage"&&(r.isStorage=!0,n.bucket!==void 0&&(r.bucket=n.bucket));const o=pr(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},mr=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...n.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]];for(const[o,s]of Object.entries(n.shape))r.push(hr(o,s));t[n.name]=r}return t},gr=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
856
856
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
857
857
|
this.ensureMigrated();
|
|
858
858
|
|
|
@@ -1174,10 +1174,10 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
|
1174
1174
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1175
1175
|
: x402Stub;
|
|
1176
1176
|
`,configField:`
|
|
1177
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:O("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Fr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],co=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:m=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:k=!1,hasR2sql:R=!1,hasX402:x=!1,maskMetadata:I,mutators:T=[],queues:_=[],rlsMetadata:v,schema:w,schemaSnapshot:F,shapes:
|
|
1177
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:O("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Fr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],co=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:m=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:k=!1,hasR2sql:R=!1,hasX402:x=!1,maskMetadata:I,mutators:T=[],queues:_=[],rlsMetadata:v,schema:w,schemaSnapshot:F,shapes:se=[],storageRules:M,studioFeatures:ie,useUmbrella:le=!1,workflows:W=[]})=>{const C=oe(le),ee=T.length>0,L=se.length>0,S=F===void 0?"":kn(F),B=F===void 0?"":`
|
|
1178
1178
|
/** 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. */
|
|
1179
1179
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(xn(F))}, json: ${JSON.stringify(S)} };
|
|
1180
|
-
`,
|
|
1180
|
+
`,ce=F===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Ae,contextField:Oe,stub:Ie}=fr(a),ue=xr(i),V=br(u),P=yr(p,C.flags),H=vr(s,p,C.flags),te=wr(l),pe=kr(o),G=Rr(c),U=Sr(y),K=$r(m),Q=Nr(d),j=Tr(R),ne=Ar(k),{build:Ce,contextField:ve,importLines:Re,specs:he}=Cr(_),{build:Le,contextField:_e,importLines:Se,specs:me}=Or(r,w.jurisdiction),{build:Ee,contextField:De,importLines:$e,specs:Pe}=Ir(W),{build:Fe,contextField:ge,importLines:fe,specs:Me}=Lr(n),{build:Be,configField:je,contextField:be,imports:ye,stub:Xe}=Dr(f),{build:h,configField:qe,imports:Ne,stub:re}=Pr(x),Nt=e,Tt=t,At=v??{policies:[],roles:[]},Ot=I??{columns:[]},It=M??{rules:[]},Ct=ie??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Lt,override:_t}=_r(W),{constant:Et,override:Dt}=Er(_),J=w.vectorIndexes.length>0,Ze=new Set(w.tables.filter(b=>typeof b.shardMode=="object"&&b.shardMode.kind==="shardBy").map(b=>b.name)),Te=w.vectorIndexes.some(b=>Ze.has(b.table)),we=w.tables.some(b=>b.shardMode==="global"),We=w.tables.some(b=>b.shardMode==="global"&&b.globalBackend==="hyperdrive"),et=w.tables.some(b=>b.shardMode==="global"&&b.globalBackend!=="hyperdrive"),z=w.tables.some(b=>b.externalSource!==void 0),tt=w.tables.some(b=>b.memory===!0),Ue=w.tables.some(b=>b.shardMode!=="global"&&b.searchIndexes.length>0);if(et&&We)throw new Z("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Ke=w.tables.length>0,Pt=lr(w),Ft=dr(w),Mt=mr(w),Bt=cr(w),nt=ur(w),rt=Fr(J,W.length>0,_.length>0,p,Ue);L&&rt.push("WhereInput");const ot=gr(we),jt=L?`
|
|
1181
1181
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1182
1182
|
const shape = LUNORA_SHAPES[name];
|
|
1183
1183
|
|
|
@@ -1230,17 +1230,17 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1230
1230
|
|
|
1231
1231
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1232
1232
|
}
|
|
1233
|
-
`:"",qt=
|
|
1233
|
+
`:"",qt=ee?`
|
|
1234
1234
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1235
1235
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1236
1236
|
}
|
|
1237
|
-
`:"",Wt=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Ut=L?"assertShapeShardable, ":"",
|
|
1237
|
+
`:"",Wt=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Ut=L?"assertShapeShardable, ":"",ke=[`import type { ${rt.join(", ")} } from "${C.do}";`,`import { applyCdcChanges, ${Ue?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${tt?"clearMemoryTables, ":""}${Ut}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Te?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ot.importFragment}ShardDO as ShardDOBase } from "${C.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${C.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${C.server}";`:`import { asBucketStorage, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${C.server}";`];Ke&&ke.push(`import { bindOrm, bindTableFacade } from "${C.server}";`),J&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...ue.importLines,...V.importLines,...P.importLines,...te.importLines,...pe.importLines,...G.importLines,...U.importLines,...K.importLines,...Q.importLines,...j.importLines,...ne.importLines,...Se,...$e,...Re,...fe,...ye,...Ne,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Kt=J?`
|
|
1238
1238
|
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Qt=et?`
|
|
1239
1239
|
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Vt=We?`
|
|
1240
1240
|
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ht=z?`
|
|
1241
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Gt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Jt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',zt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Yt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Xt=
|
|
1241
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Gt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Jt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',zt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Yt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Xt=we?O("globalDbStub: DatabaseWriterLike",Gt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Zt=J?O("vectorsStub: VectorSearchLike",Jt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",en=Te?`
|
|
1242
1242
|
const vectorShardKey = this.currentShardKey();
|
|
1243
|
-
`:"",tn=
|
|
1243
|
+
`:"",tn=Te?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",nn=Te?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(b=>Ze.has(b.table)).map(b=>JSON.stringify(b.name)).join(", ")}] }`:"",rn=J?`
|
|
1244
1244
|
let vectors: VectorSearchLike;
|
|
1245
1245
|
let onWrite: WriteHook | undefined;
|
|
1246
1246
|
|
|
@@ -1287,7 +1287,7 @@ ${en}
|
|
|
1287
1287
|
scheduler,
|
|
1288
1288
|
schema: schema as unknown as SchemaLike,
|
|
1289
1289
|
sql: this.sql as SqlExec,
|
|
1290
|
-
storage,${
|
|
1290
|
+
storage,${we?`
|
|
1291
1291
|
globalDb,`:""}
|
|
1292
1292
|
}`,Y=` const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1293
1293
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
@@ -1303,9 +1303,9 @@ ${en}
|
|
|
1303
1303
|
sql: this.sql as SqlExec,
|
|
1304
1304
|
});`,an=J?`
|
|
1305
1305
|
vectors,`:"",sn=Ke?`
|
|
1306
|
-
orm: bindOrm(facade),`:"",Qe=We?"config.hyperdriveGlobal":"config.d1",ln=
|
|
1306
|
+
orm: bindOrm(facade),`:"",Qe=We?"config.hyperdriveGlobal":"config.d1",ln=we?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
|
|
1307
1307
|
const globalDb: DatabaseWriterLike = ${Qe}?.(env, globalRequest) ?? globalDbStub;
|
|
1308
|
-
`:"",cn=L&&
|
|
1308
|
+
`:"",cn=L&&we?`
|
|
1309
1309
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1310
1310
|
const env = this.env as Record<string, unknown>;
|
|
1311
1311
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1517,18 +1517,18 @@ ${z?`
|
|
|
1517
1517
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1518
1518
|
${w.tables.map(b=>` facade[${JSON.stringify(b.name)}] = bindTableFacade(db, ${JSON.stringify(b.name)});`).join(`
|
|
1519
1519
|
`)}
|
|
1520
|
-
`:"",gn=`${
|
|
1520
|
+
`:"",gn=`${ue.build}${V.build}${P.build}${G.build}${pe.build}
|
|
1521
1521
|
const secrets = createSecrets(env);
|
|
1522
|
-
`,fn=`${
|
|
1523
|
-
secrets,`,bn=
|
|
1522
|
+
`,fn=`${ue.contextField}${V.contextField}${P.contextField}${te.contextField}${G.contextField}${pe.contextField}
|
|
1523
|
+
secrets,`,bn=te.build,st=y||m||d||R||k||x,yn=st?`
|
|
1524
1524
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1525
1525
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1526
1526
|
if (isAction) {
|
|
1527
|
-
${U.build}${K.build}${Q.build}${j.build}${
|
|
1527
|
+
${U.build}${K.build}${Q.build}${j.build}${ne.build}${h}${[...y?[" ctx.images = images;"]:[],...m?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...R?[" ctx.r2sql = r2sql;"]:[],...k?[" ctx.pipelines = pipelines;"]:[],...x?[" ctx.x402 = x402;"]:[]].join(`
|
|
1528
1528
|
`)}
|
|
1529
1529
|
}
|
|
1530
1530
|
`:"",wn=st?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1531
|
-
`:"";return`${$}${
|
|
1531
|
+
`:"";return`${$}${ke.join(`
|
|
1532
1532
|
`)}
|
|
1533
1533
|
|
|
1534
1534
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1572,16 +1572,16 @@ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(It,void 0,4)};
|
|
|
1572
1572
|
|
|
1573
1573
|
/** 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. */
|
|
1574
1574
|
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Ct,void 0,4)};
|
|
1575
|
-
${B}${H.constant}${Wt}${Lt}${Et}${
|
|
1575
|
+
${B}${H.constant}${Wt}${Lt}${Et}${me}${Pe}${he}${Me}
|
|
1576
1576
|
export interface ShardDOConfig {
|
|
1577
1577
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1578
1578
|
cdc?: boolean;
|
|
1579
1579
|
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1580
1580
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1581
1581
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1582
|
-
storage?: (env: Record<string, unknown>) => unknown;${Kt}${Ae}${V.configField}${P.configField}${G.configField}${U.configField}${K.configField}${Q.configField}${j.configField}${
|
|
1582
|
+
storage?: (env: Record<string, unknown>) => unknown;${Kt}${Ae}${V.configField}${P.configField}${G.configField}${U.configField}${K.configField}${Q.configField}${j.configField}${ne.configField}${je}${qe}${Qt}${Vt}${Ht}
|
|
1583
1583
|
}
|
|
1584
|
-
${O("schedulerStub",zt,["cancel","runAfter","runAt"])}${O("storageStub",Yt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Xt}${dn}${Zt}${Ie}${V.stub}${P.stub}${G.stub}${U.stub}${K.stub}${Q.stub}${j.stub}${
|
|
1584
|
+
${O("schedulerStub",zt,["cancel","runAfter","runAt"])}${O("storageStub",Yt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Xt}${dn}${Zt}${Ie}${V.stub}${P.stub}${G.stub}${U.stub}${K.stub}${Q.stub}${j.stub}${ne.stub}${Xe}${re}
|
|
1585
1585
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1586
1586
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1587
1587
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -2040,7 +2040,7 @@ ${Y}
|
|
|
2040
2040
|
return;
|
|
2041
2041
|
}
|
|
2042
2042
|
|
|
2043
|
-
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${
|
|
2043
|
+
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ce} });
|
|
2044
2044
|
this.migrated = true;
|
|
2045
2045
|
}
|
|
2046
2046
|
${Ue?`
|
|
@@ -2062,7 +2062,7 @@ ${Ue?`
|
|
|
2062
2062
|
// dispatch path) fall back to the per-request fields as before.
|
|
2063
2063
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
2064
2064
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
2065
|
-
${rn}${
|
|
2065
|
+
${rn}${de}${gn}${Le}${Ee}${Ce}${Fe}
|
|
2066
2066
|
// \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
|
|
2067
2067
|
// reaches through, and pending jobs live in the SchedulerDO — nothing the
|
|
2068
2068
|
// CDC changelog records — so reading them must forfeit a delta resume.
|
|
@@ -2165,7 +2165,7 @@ ${bn}
|
|
|
2165
2165
|
scheduler,
|
|
2166
2166
|
span,
|
|
2167
2167
|
storage: contextStorage,
|
|
2168
|
-
trace,${an}${Oe}${fn}${
|
|
2168
|
+
trace,${an}${Oe}${fn}${be}${_e}${De}${ve}${ge}
|
|
2169
2169
|
};
|
|
2170
2170
|
${wn}${yn}
|
|
2171
2171
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
@@ -2193,14 +2193,14 @@ ${wn}${yn}
|
|
|
2193
2193
|
return ctx;
|
|
2194
2194
|
}
|
|
2195
2195
|
};
|
|
2196
|
-
`},Ye=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ye(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},$t=(e,t)=>{const n=
|
|
2196
|
+
`},Ye=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ye(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},$t=(e,t)=>{const n=ae(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Mr=(e,t,n)=>{g(e,"drizzle column name");const r=Ye(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=$t(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},Br=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(g(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${X(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},jr=(e,t)=>{g(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${Mr(o,s,t)},`)].join(`
|
|
2197
2197
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2198
2198
|
${e.indexes.map(o=>Br(o)).join(`
|
|
2199
2199
|
`)}
|
|
2200
2200
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2201
2201
|
${n}
|
|
2202
2202
|
}${r});`},qr=e=>e.typeAnnotation?.includes('Id<"')??!1,Wr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Ye(a);n.add(c.builder),s=s||qr(c),o=o||$t(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},ct=(e,t=!1)=>{if(e.length===0)return`${$}export {};
|
|
2203
|
-
`;const n=
|
|
2203
|
+
`;const n=oe(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Wr(e,r),c=[...s,...o].toSorted((m,y)=>m.localeCompare(y)),d=e.map(m=>jr(m,r)).join(`
|
|
2204
2204
|
|
|
2205
2205
|
`),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2206
2206
|
`:"",a?`import type { Id } from "./dataModel.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as D}from"./emit-
|
|
1
|
+
import{A as S,G as D}from"./emit-CMv9Snzk.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],C=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,O=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],T=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],L=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:h,hasWorkflow:u,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),r&&g.push("FrameworkHostHandler");const w=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,a),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...h?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...u?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...O(e),`import type { ${[...g].toSorted((f,y)=>f.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${w} } from "${i}";`,"",...A(e.identity),...T(e),...n||o?['import schema from "../schema.js";']:[],...C(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},q=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. */
|
|
2
2
|
interface StorageDeclaration<Env> {
|
|
3
3
|
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
4
4
|
bucket: Selector<Env, R2BucketLike>;
|