@lunora/codegen 1.0.0-alpha.116 → 1.0.0-alpha.118
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-hlnTcuPd.mjs → GENERATED_HEADER-BIP8JE2o.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DpRms_jN.mjs → OPENRPC_VERSION-CK8lskQm.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CGCzlXbr.mjs → SCHEMA_SNAPSHOT_FILENAME-KYdkEFZu.mjs} +1 -1
- package/dist/packem_shared/{SDK_LANGUAGES-BHYgTciL.mjs → SDK_LANGUAGES-CFyux-74.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-ClEtrbbS.mjs → buildOpenApiDocument-xvbIL1q6.mjs} +1 -1
- package/dist/packem_shared/{emit-CV6JjAt9.mjs → emit-C935cHCe.mjs} +127 -120
- package/dist/packem_shared/{emitApp-BBcZ_fPU.mjs → emitApp-BpHICt5i.mjs} +1 -1
- package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
- package/package.json +1 -1
- package/dist/packem_shared/isTypedSchema-BBIBMZTg.mjs +0 -2
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-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.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-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4eSpCR6m.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DOirwCWw.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-D-09Qb8S.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-sGAt-yC1.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-DhNToI6C.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-CTZI61e3.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-B6e4j4rD.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Pw0_c1aS.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-D_wHstA-.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-DthHu3mC.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.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-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4eSpCR6m.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DOirwCWw.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-D-09Qb8S.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-sGAt-yC1.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-DhNToI6C.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-CTZI61e3.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-B6e4j4rD.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Pw0_c1aS.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-D_wHstA-.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-DthHu3mC.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-C935cHCe.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-BpHICt5i.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-xvbIL1q6.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-CK8lskQm.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as qe,readProjectTarget as Be,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CIH5PRk1.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Xe,createCodegenProject as Ze,findTsconfig as $e,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-KYdkEFZu.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-Dc1aZAph.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as gr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,T as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,je as OPENRPC_VERSION,ee as QUEUES_FILENAME,Xe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Ze 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,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,ge as emitAgents,Oe as emitApi,Ge as emitApp,Re as emitCollections,Me as emitContainers,he as emitCrons,Ce as emitDataModel,_e as emitDrizzleSchema,Te as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Ie as emitServer,Le as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,gr as findLunoraSolution,$e as findTsconfig,m as formatAdvisories,Er as generateSdk,Rr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,qe as platformMatrixIds,Y as readPackageDependencies,Be as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.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-DIqnj_32.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-C935cHCe.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-C935cHCe.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 N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-
|
|
1
|
+
import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-C935cHCe.mjs";import{l as h,a as E,c as y,p as S,f as xt,i as gs,r as Et,e as ms}from"./discover-ast-D33zP-NZ.mjs";import hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as xs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as Es}from"./discoverSandboxUsage-L0lV17de.mjs";import vs from"./discoverStorageRulesMetadata-DthHu3mC.mjs";import{discoverWorkflows as Ss}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as As,resolveCodegenTarget as Ns}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as ys,b as bs,s as te,f as Is,g as Ps,d as ws}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Ts,procedureHandler as vt,chainUsesWrappedCall as St,isDatabaseAccessor as K,chainHasStep as Cs,discoverFunctions as Rs,resolveStandardSchemaType as Os}from"./discoverFunctions-4eSpCR6m.mjs";import Fs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Ls from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Ds}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import ks from"./discoverHttpRoutes-DOirwCWw.mjs";import Ms from"./discoverInserts-YX8AmrzL.mjs";import Ks,{discoverMaskStrategies as _s,discoverMaskMetadata as zs,discoverMaskHasNonLiteralPolicy as Us}from"./discoverMaskProcedures-D-09Qb8S.mjs";import Bs from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as qs,isDefineMutatorCallee as $s,discoverMutators as js}from"./MUTATORS_FILENAME-sGAt-yC1.mjs";import Vs from"./discoverNondeterministicCalls-DhNToI6C.mjs";import{discoverNotifyConfig as Ws,discoverNotifyCalls as Hs}from"./NOTIFY_FILENAME-CTZI61e3.mjs";import Gs from"./discoverR2sqlCalls-B6e4j4rD.mjs";import Ys,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Pw0_c1aS.mjs";import Xs from"./discoverSchema-D_wHstA-.mjs";import{secretKindOf as Zs,redact as Js,isHeuristicSecretKind as en,isSecretishName as tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as sn}from"./SHAPES_FILENAME-DTp6VI6K.mjs";import{emitApp as nn}from"./emitApp-BpHICt5i.mjs";import{buildOpenApiDocument as rn,emitOpenApiModule as on}from"./buildOpenApiDocument-xvbIL1q6.mjs";import{buildOpenRpcDocument as an,emitOpenRpcModule as cn}from"./OPENRPC_VERSION-CK8lskQm.mjs";import{s as ln}from"./parse-validator-C5ycrhR3.mjs";import{buildSchemaSnapshot as un}from"./SchemaSnapshotParseError-Dc1aZAph.mjs";const dn=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},fn=(e,t)=>{if(t===void 0)return;const s=dn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
2
2
|
`);throw new O("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${n}
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{modelSources as ce,toPascalCase as o,referencedModels as N,generatedHeaderLines as f,commentText as l,argsChoice as p,stringLiteral as $,kotlinLiteral as v,allMethods as P,toSnakeCase as B,parseSpec as ke,assertGeneratable as Oe,withDeclaredModels as Ne,unrepresentableFunctions as Ce,undeclaredModels as Le}from"./isTypedSchema-
|
|
1
|
+
import{modelSources as ce,toPascalCase as o,referencedModels as N,generatedHeaderLines as f,commentText as l,argsChoice as p,stringLiteral as $,kotlinLiteral as v,allMethods as P,toSnakeCase as B,parseSpec as ke,assertGeneratable as Oe,withDeclaredModels as Ne,unrepresentableFunctions as Ce,undeclaredModels as Le}from"./isTypedSchema-B_qlBbE-.mjs";import{isTypedSchema as br}from"./isTypedSchema-B_qlBbE-.mjs";const We=async(e,n)=>{if(n.quicktype===void 0)return"";const r=ce(e);if(r.length===0)return"";const{InputData:t,JSONSchemaInput:a,JSONSchemaStore:i,quicktype:s}=await import("quicktype-core");class u extends i{fetch(){return Promise.resolve(void 0)}}const m=new a(new u);for(const g of r)await m.addSource({name:g.name,schema:JSON.stringify(g.schema)});const d=new t;d.addInput(m);const{lines:c}=await s({inputData:d,lang:n.quicktype.lang,rendererOptions:n.quicktype.rendererOptions??{}});return c.join(`
|
|
2
2
|
`)},L=`${f("dart").map(e=>`// ${e}`).join(`
|
|
3
3
|
`)}
|
|
4
4
|
|
package/dist/packem_shared/{buildOpenApiDocument-ClEtrbbS.mjs → buildOpenApiDocument-xvbIL1q6.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-C935cHCe.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"],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 ot}from"@lunora/agent/component";import{LunoraError as te}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
1
|
+
import{agentComponent as ot}from"@lunora/agent/component";import{LunoraError as te}from"@lunora/errors";import{serializeSchemaSnapshot as hn,hashSchemaSnapshot as gn}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{s as S}from"./paths-C-9fwEgQ.mjs";const at=[{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. */
|
|
@@ -15,38 +15,40 @@ import{agentComponent as ot}from"@lunora/agent/component";import{LunoraError as
|
|
|
15
15
|
/**
|
|
16
16
|
* R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
|
|
17
17
|
*/
|
|
18
|
-
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],
|
|
18
|
+
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],fn=at,bn=new Map(fn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Kr=at.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),st=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,yn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),it=e=>e.column!==void 0,kn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
19
19
|
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
20
20
|
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
21
21
|
`;case"null":return`if (${t} !== null) return DEFER;
|
|
22
22
|
`;default:return`if (typeof ${t} !== "string") return DEFER;
|
|
23
|
-
`}},
|
|
24
|
-
`}},We=(e,t,n)=>{if(!it(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(
|
|
23
|
+
`}},xn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!st.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
24
|
+
`}},We=(e,t,n)=>{if(!it(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(yn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:kn(e.kind,t)};switch(e.kind){case"array":return wn(e,t,n);case"literal":return xn(e,t);case"object":return Rn(e,t,n);default:return}}},wn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=We(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
|
|
25
25
|
const ${s} = new Array(${t}.length);
|
|
26
26
|
for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
|
|
27
27
|
const ${a} = ${t}[${i}];
|
|
28
28
|
${c.pre}${s}[${i}] = ${c.out};
|
|
29
29
|
}
|
|
30
|
-
`;return{out:s,pre:d}},
|
|
30
|
+
`;return{out:s,pre:d}},vn=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||it(t))return;const{inner:i}=t;if(!i)return;const a=We(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,h=`let ${d} = false;
|
|
31
31
|
let ${p};
|
|
32
32
|
if (${n} !== undefined) {
|
|
33
33
|
${a.pre}${p} = ${a.out};
|
|
34
34
|
${d} = true;
|
|
35
35
|
}
|
|
36
|
-
`;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:h}}const s=We(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},lt=(e,t,n)=>{let r="";const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)return;const a=
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
`;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:h}}const s=We(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},$n=new Set(Object.getOwnPropertyNames(Object.prototype)),lt=(e,t,n)=>{let r="";const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)return;const a=JSON.stringify(s);let c=`${t}[${a}]`;if($n.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
|
|
37
|
+
`,c=p}const d=vn(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},ct=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
|
|
38
|
+
`},Rn=(e,t,n)=>{const r=e.shape??{},o=lt(r,t,n);if(!o)return;const s=n.next(),i=`__obj${String(s)}`,a=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
|
|
39
|
+
${ct(t)}${o.pre}const ${i} = { ${o.entries} };
|
|
40
|
+
`;return{out:i,pre:a}},Sn=e=>{let t=0;const r=lt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
|
|
39
41
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
40
|
-
${r.pre}return { ${r.entries} };
|
|
42
|
+
${ct("source")}${r.pre}return { ${r.entries} };
|
|
41
43
|
}`},R=`// GENERATED by @lunora/codegen — do not edit.
|
|
42
44
|
// Run \`lunora codegen\` to regenerate.
|
|
43
45
|
|
|
44
|
-
`,ne=(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"},
|
|
46
|
+
`,ne=(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"},dt=/^[A-Za-z_$][\w$]*$/u,Nn=/^[\w./-]+$/u,g=(e,t)=>{if(!dt.test(e))throw new te("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},qe=e=>e.charAt(0).toUpperCase()+e.slice(1),_=e=>dt.test(e)?e:JSON.stringify(e),Tn={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"},An=e=>{if(e===void 0)return"unknown";if(!st.test(e))throw new te("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},N=e=>{const t=Tn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?N(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 An(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>ut(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?N(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?N(e.keyType):"string",r=e.valueType?N(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>N(n)).join(" | "):"never";default:return"unknown"}},ut=(e,t)=>{const n=_(e);if(t.kind==="optional"){const r=t.inner?N(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${N(t)}`},ke=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>ut(n,r)).join("; ")} }`},pt=e=>e.kind==="optional"||!!e.column?.hasDefault,re=e=>e.kind==="optional"&&e.inner?e.inner:e,On=e=>{g(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=re(o),i=N(s),a=_(r);return pt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
|
|
45
47
|
`),n=t?`
|
|
46
48
|
${t}
|
|
47
49
|
`:"";return`export interface Insert_${e.name} {
|
|
48
50
|
_id?: Id<"${e.name}">;
|
|
49
|
-
_creationTime?: number;${n}}`},Ue="schema",
|
|
51
|
+
_creationTime?: number;${n}}`},Ue="schema",Qr=e=>{for(const u of e.tables)g(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,w])=>{const v=_(x);if(w.kind==="optional"){const I=w.inner?N(w.inner):"unknown";return` ${v}?: ${I};`}return` ${v}: ${N(w)};`}).join(`
|
|
50
52
|
`),f=l?`
|
|
51
53
|
${l}
|
|
52
54
|
`:"";return`export interface Doc_${u.name} {
|
|
@@ -58,7 +60,7 @@ ${l}
|
|
|
58
60
|
`),i=e.tables.map(u=>{const l=u.searchIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
59
61
|
`),a=e.tables.map(u=>{const l=u.rankIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
60
62
|
`),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
61
|
-
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>
|
|
63
|
+
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>On(u)).join(`
|
|
62
64
|
|
|
63
65
|
`),h=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
|
|
64
66
|
`),b=e.tables.map(u=>{const l=u.relations.map(f=>(g(f.table,"relation target table"),` ${_(f.name)}: ${f.kind==="one"?"OneRelation":"ManyRelation"}<"${f.table}">;`)).join(`
|
|
@@ -157,11 +159,11 @@ export interface Relations {
|
|
|
157
159
|
${b}
|
|
158
160
|
}
|
|
159
161
|
|
|
160
|
-
`,Ue)},
|
|
162
|
+
`,Ue)},In=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,mt=/^(?:\.\.?\/)*_generated\//u,ht=/\.[A-Za-z]\w*$/u,Cn=e=>e.replaceAll(In,(t,n)=>{const r=n.replace(mt,"./");return`import("${ht.test(r)?r:`${r}.js`}")`}),Ln=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,_n=/^(?:\.\.?\/)+/u,En=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("/")},Dn=(e,t)=>e.replaceAll(Ln,(n,r)=>{if(mt.test(r.replace(_n,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${En(`${o}/${r}`)}`;return`import("${ht.test(i)?i:`${i}.js`}")`}),E=(e,t)=>Cn(Dn(e,t)),Fn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Pn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Fn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Mn={flags:new Set(["/web"]),platform:new Set},gt=(e,t)=>t?e.replaceAll(Pn,(n,r,o)=>{const s=Mn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Ke=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),Bn=e=>e.output===void 0||e.output.kind==="any"?e.returnType:N(e.output),Qe=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))},nt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=E(ke(s.args),s.filePath),a=E(Bn(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
|
|
161
163
|
`);return` ${_(S(n))}: {
|
|
162
164
|
${o}
|
|
163
165
|
};`};return Qe(e).map(n=>t(n)).join(`
|
|
164
|
-
`)},
|
|
166
|
+
`)},jn=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
|
|
165
167
|
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
166
168
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
167
169
|
readonly isLunoraWorkflow: true;
|
|
@@ -193,7 +195,7 @@ export const agents: AgentsRef = {
|
|
|
193
195
|
${i}
|
|
194
196
|
};
|
|
195
197
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
196
|
-
`)}return{block:r,importLine:n.join("")}},
|
|
198
|
+
`)}return{block:r,importLine:n.join("")}},qn=()=>Object.keys(ot().functions).toSorted((e,t)=>e.localeCompare(t)),ft=e=>new Set(e.filter(t=>S(t.filePath)==="agents").map(t=>t.exportName)),Wn=()=>new Set(Object.entries(ot().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Un=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=ft(t),o=Wn(),s=t.find(a=>S(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new te("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=qn().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
197
199
|
`,lines:i.map(a=>` "agents:${a}": lunoraAgentRuntimeFunctions.${a} as unknown as RegisteredLunoraFunction,`).join(`
|
|
198
200
|
`),prelude:`
|
|
199
201
|
/**
|
|
@@ -202,8 +204,8 @@ ${i}
|
|
|
202
204
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
203
205
|
*/
|
|
204
206
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
205
|
-
`}},
|
|
206
|
-
`,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"}},
|
|
207
|
+
`}},Kn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>S(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new te("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";
|
|
208
|
+
`,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"}},Qn=(e,t)=>{if(e.length===0)return[];const n=ft(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))},Vn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>S(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}))},Hn=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Qe(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=E(d.chunkType??"unknown",d.filePath),h=E(ke(d.searchParams),d.filePath),b=E(ke(d.params),d.filePath);return` ${_(d.exportName)}: HttpStreamRef<${p}, ${h}, ${b}>;`}).join(`
|
|
207
209
|
`);return` ${_(S(i))}: {
|
|
208
210
|
${c}
|
|
209
211
|
};`}).join(`
|
|
@@ -220,7 +222,7 @@ ${r}
|
|
|
220
222
|
export const httpStreams: HttpStreamsRef = {
|
|
221
223
|
${o}
|
|
222
224
|
};
|
|
223
|
-
`,body:r}},
|
|
225
|
+
`,body:r}},Vr=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=ne(s),c=[...n.filter($=>$.visibility!=="internal"),...Qn(t,n),...Vn(o,n)],d=n.filter($=>$.visibility==="internal"),p=nt(c),h=nt(d),b=Hn(r),u=`${p}
|
|
224
226
|
${h}
|
|
225
227
|
${b.body}`,l=Ke(u),f=l.length>0?`
|
|
226
228
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
@@ -228,7 +230,7 @@ import type { ${l.join(", ")} } from "./dataModel.js";
|
|
|
228
230
|
${p}
|
|
229
231
|
`:"",w=h?`
|
|
230
232
|
${h}
|
|
231
|
-
`:"",v=
|
|
233
|
+
`:"",v=jn(i,t),I=`export interface ApiTypes {${x}}
|
|
232
234
|
|
|
233
235
|
export const api = anyApi as unknown as ApiTypes;
|
|
234
236
|
|
|
@@ -237,9 +239,9 @@ export interface InternalApiTypes {${w}}
|
|
|
237
239
|
|
|
238
240
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
239
241
|
${v.block}${b.block}`,P=[...I.includes("FunctionReference<")?["FunctionReference"]:[],...b.block===""?[]:["HttpStreamRef"]],C=P.length>0?`import type { ${P.join(", ")} } from "${a.client}";
|
|
240
|
-
`:"";return
|
|
242
|
+
`:"";return gt(`${R}import { anyApi } from "${a.client}";
|
|
241
243
|
${C}${v.importLine}${f}
|
|
242
|
-
${I}`,s)},
|
|
244
|
+
${I}`,s)},Hr=e=>e?`${R}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
243
245
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
244
246
|
|
|
245
247
|
import schema from "../schema.js";
|
|
@@ -256,7 +258,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
256
258
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
257
259
|
*/
|
|
258
260
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
259
|
-
`:"",
|
|
261
|
+
`:"",Gr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ne(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(ke(c.args),c.filePath),h=Object.keys(c.args).length>0,b=h?` args: ${p};`:` args?: ${p};`,u=h?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
|
|
260
262
|
export interface ${qe(l)} {
|
|
261
263
|
${b}
|
|
262
264
|
/**
|
|
@@ -310,7 +312,7 @@ import type { Collection } from "@tanstack/db";
|
|
|
310
312
|
import { createCollection } from "@tanstack/db";
|
|
311
313
|
${a}
|
|
312
314
|
${s}
|
|
313
|
-
`},
|
|
315
|
+
`},Gn=(e,t)=>`lunora_${S(e)}_${String(t)}`,Jn=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
314
316
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
315
317
|
|
|
316
318
|
if (!registered) {
|
|
@@ -318,13 +320,13 @@ ${s}
|
|
|
318
320
|
}
|
|
319
321
|
|
|
320
322
|
return (await registered.handler(context, args ?? {})) as R;
|
|
321
|
-
};`,
|
|
323
|
+
};`,zn=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,Gn(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(!Nn.test(l))throw new te("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${f} from "../${l}.js";`}).join(`
|
|
322
324
|
`),a=e.map(l=>` "${S(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
323
325
|
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
324
326
|
`),d=n.map(l=>` "${S(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
325
327
|
`),p=r.map(l=>` "${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
|
|
326
328
|
`),h=n.map(l=>`${S(l.filePath)}:${l.exportName}`),b=[a,d].filter(l=>l.length>0).join(`
|
|
327
|
-
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f
|
|
329
|
+
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f=Sn(l.args);return f===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${f});`}).filter(l=>l!==void 0).join(`
|
|
328
330
|
`);return{dispatchBody:b.length>0?`
|
|
329
331
|
${b}
|
|
330
332
|
`:"",importBlock:i.length>0?`${i}
|
|
@@ -333,7 +335,7 @@ ${b}
|
|
|
333
335
|
${c}
|
|
334
336
|
`:"",mutatorPaths:h,shapeBody:p.length>0?`
|
|
335
337
|
${p}
|
|
336
|
-
`:""}},
|
|
338
|
+
`:""}},Yn=e=>{const t=Qe(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=E(ke(a.args),a.filePath),d=c==="{}"?"?":"",p=E(a.returnType,a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
|
|
337
339
|
`);return` ${_(S(o))}: {
|
|
338
340
|
${i}
|
|
339
341
|
};`}).join(`
|
|
@@ -341,7 +343,7 @@ ${i}
|
|
|
341
343
|
`);return` ${_(i)}: {
|
|
342
344
|
${a}
|
|
343
345
|
},`}).join(`
|
|
344
|
-
`),types:n}},
|
|
346
|
+
`),types:n}},Xn=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=re(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))]},Jr=({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:h=!1,hasPayments:b=!1,hasPipelines:u=!1,hasR2sql:l=!1,hasX402:f=!1,identity:x,queues:w=[],schema:v,storageRuleBuckets:I=[],useUmbrella:P=!1,workflows:C=[]}={})=>{const $=ne(P),k=Xn(v??{tables:[]},I).map(m=>JSON.stringify(m)).join(" | "),M=o?`import type { LunoraAi } from "@lunora/ai";
|
|
345
347
|
`:"",oe=o?`
|
|
346
348
|
readonly ai: LunoraAi;`:"",B=b?`import type { LunoraPayment } from "@lunora/payment";
|
|
347
349
|
`:"",ae=b?`
|
|
@@ -374,7 +376,7 @@ ${O}`:""}
|
|
|
374
376
|
}
|
|
375
377
|
|
|
376
378
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
377
|
-
export type Env = CloudflareBindings;`,j=(m,Me)=>Me?
|
|
379
|
+
export type Env = CloudflareBindings;`,j=(m,Me)=>Me?bn.get(m)?.field??"":"",ie=j("kv",p),le=j("analytics",s),Se=j("hyperdrive",c),Ne=j("browser",i),Te=j("images",d),ce=j("pipelines",u),V=j("r2sql",l),F=(v?.vectorIndexes.length??0)>0,H=F?' | "vectors"':"",Z=F?`
|
|
378
380
|
readonly vectors: VectorSearch<VectorIndexName>;`:"",de=F?`
|
|
379
381
|
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",G=F?`import type { VectorSearch, VectorSearchReader } from "${$.server}";
|
|
380
382
|
import type { VectorIndexName } from "./dataModel.js";
|
|
@@ -614,22 +616,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
614
616
|
*/
|
|
615
617
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
616
618
|
|
|
617
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${
|
|
619
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${H}${me}${ge}> {
|
|
618
620
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
619
621
|
readonly orm: OrmReader;
|
|
620
622
|
readonly storage: ReadOnlyStorage<StorageBucketName>;${de}${U}${ie}${K}${Q}${le}${fe}${he}
|
|
621
623
|
}
|
|
622
624
|
|
|
623
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${
|
|
625
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${H}${xe}${me}${ge}> {
|
|
624
626
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
625
627
|
readonly orm: OrmWriter;
|
|
626
628
|
readonly storage: ReadOnlyStorage<StorageBucketName>;${Z}${U}${ie}${K}${Q}${le}${fe}${we}${ve}${$e}${he}
|
|
627
629
|
}
|
|
628
630
|
|
|
629
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${
|
|
631
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${H}${xe}${me}${ge}> {
|
|
630
632
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
631
633
|
readonly orm: OrmWriter;
|
|
632
|
-
readonly storage: StorageBase<StorageBucketName>;${Z}${U}${oe}${ae}${W}${X}${ie}${K}${Q}${Se}${Ne}${Te}${le}${ce}${
|
|
634
|
+
readonly storage: StorageBase<StorageBucketName>;${Z}${U}${oe}${ae}${W}${X}${ie}${K}${Q}${Se}${Ne}${Te}${le}${ce}${V}${fe}${we}${ve}${$e}${he}
|
|
633
635
|
}
|
|
634
636
|
|
|
635
637
|
/**
|
|
@@ -704,12 +706,12 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${De}>();
|
|
|
704
706
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
705
707
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
706
708
|
};
|
|
707
|
-
`},
|
|
709
|
+
`},Zn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${S(n.filePath)}:${n.exportName}`);return t},zr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ne(i),{dispatchBody:p,importBlock:h,installBlock:b,migrationBody:u,mutatorPaths:l,shapeBody:f}=zn(n,r,o,s),x=Un(t,n),w=Kn(a,n),v=[x.lines,w.lines].filter(L=>L.length>0).join(`
|
|
708
710
|
`);let I=p;v.length>0&&(I=p.length>0?`${p.trimEnd()}
|
|
709
711
|
${v}
|
|
710
712
|
`:`
|
|
711
713
|
${v}
|
|
712
|
-
`);const P=
|
|
714
|
+
`);const P=Zn(n),C=s.length>0?`import type { RegisteredShape } from "${d.server}";
|
|
713
715
|
`:"",$=s.length>0?`
|
|
714
716
|
/**
|
|
715
717
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
@@ -733,14 +735,14 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(L=>JSO
|
|
|
733
735
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
734
736
|
*/
|
|
735
737
|
${b}
|
|
736
|
-
`:"",B=
|
|
738
|
+
`:"",B=Yn(n),ae=B.types?`
|
|
737
739
|
${B.types}
|
|
738
740
|
`:"",se=B.implementation?`
|
|
739
741
|
${B.implementation}
|
|
740
742
|
`:"",W=Ke(B.types),A=W.length>0?`import type { ${W.join(", ")} } from "./dataModel.js";
|
|
741
|
-
`:"",X=c?"context":"_context",O=c?`${
|
|
743
|
+
`:"",X=c?"context":"_context",O=c?`${Jn}
|
|
742
744
|
|
|
743
|
-
`:"";return
|
|
745
|
+
`:"";return gt(`${R}${h}${x.importLine}${w.importLine}${M}${C}import { LunoraError } from "${d.server}";
|
|
744
746
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
745
747
|
${A}
|
|
746
748
|
/**
|
|
@@ -836,7 +838,7 @@ export interface RegisteredDataMigration {
|
|
|
836
838
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
837
839
|
*/
|
|
838
840
|
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
|
|
839
|
-
`,i)},
|
|
841
|
+
`,i)},er=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=re(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},tr=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))re(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},nr=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},rr=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},or=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},ar=(e,t)=>{const n=re(t),r={name:e,optional:pt(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=or(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},sr=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"}];for(const[o,s]of Object.entries(n.shape))r.push(ar(o,s));t[n.name]=r}return t},ir=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
840
842
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
841
843
|
this.ensureMigrated();
|
|
842
844
|
|
|
@@ -844,7 +846,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}}
|
|
|
844
846
|
|
|
845
847
|
return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
|
|
846
848
|
}
|
|
847
|
-
`}:{importFragment:"",override:""},
|
|
849
|
+
`}:{importFragment:"",override:""},lr=e=>{if(!e)return{build:"",configField:"",contextField:"",stub:""};const t='throw new Error("ctx.ai: no AI binding found. Add an \\`ai\\` binding (env.AI) to wrangler.jsonc, or pass \\`ai\\` to createShardDO().");';return{build:`
|
|
848
850
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
849
851
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
850
852
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -882,12 +884,12 @@ const aiStub: LunoraAi = {
|
|
|
882
884
|
const ${e} = {
|
|
883
885
|
${s}
|
|
884
886
|
}${r};
|
|
885
|
-
`},D={build:"",configField:"",contextField:"",importLines:[],stub:""},
|
|
887
|
+
`},D={build:"",configField:"",contextField:"",importLines:[],stub:""},cr=e=>e?{build:`
|
|
886
888
|
const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
|
|
887
889
|
const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
|
|
888
890
|
`,configField:`
|
|
889
891
|
kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
|
|
890
|
-
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:T("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:D,
|
|
892
|
+
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:T("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:D,dr=(e,t)=>e?{build:`
|
|
891
893
|
const flags: import("${t}").LunoraFlags = createFlags({
|
|
892
894
|
hooks: flagsConfig.hooks,
|
|
893
895
|
logger: flagsConfig.logger,
|
|
@@ -896,17 +898,17 @@ ${s}
|
|
|
896
898
|
});
|
|
897
899
|
`,configField:`
|
|
898
900
|
flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
|
|
899
|
-
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,
|
|
901
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,ur=e=>e?{build:`
|
|
900
902
|
const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
|
|
901
903
|
`,configField:"",contextField:`
|
|
902
904
|
notify,
|
|
903
|
-
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,
|
|
905
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,pr=e=>e?{build:`
|
|
904
906
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
905
907
|
`,configField:"",contextField:`
|
|
906
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,
|
|
908
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,mr=e=>e?{build:`
|
|
907
909
|
const access = accessFacade(identity, userId);
|
|
908
910
|
`,configField:"",contextField:`
|
|
909
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,
|
|
911
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,hr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
|
|
910
912
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
911
913
|
const flags: import("${n}").LunoraFlags = createFlags({
|
|
912
914
|
hooks: flagsConfig.hooks,
|
|
@@ -970,25 +972,25 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
970
972
|
|
|
971
973
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
972
974
|
}
|
|
973
|
-
`;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},
|
|
975
|
+
`;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},gr=e=>e?{build:`
|
|
974
976
|
const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
|
|
975
977
|
const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
|
|
976
978
|
`,configField:`
|
|
977
979
|
analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
|
|
978
|
-
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:T("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:D,
|
|
980
|
+
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:T("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:D,fr=e=>e?{build:`
|
|
979
981
|
const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
|
|
980
982
|
const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
|
|
981
983
|
`,configField:`
|
|
982
984
|
images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
|
|
983
|
-
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:T("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:D,
|
|
985
|
+
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:T("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:D,br=e=>e?{build:`
|
|
984
986
|
const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
|
|
985
987
|
`,configField:`
|
|
986
988
|
sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
|
|
987
|
-
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:T("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:D,
|
|
989
|
+
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:T("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:D,yr=e=>e?{build:`
|
|
988
990
|
const browser: Browser = config.browser ? config.browser(env) : browserStub;
|
|
989
991
|
`,configField:`
|
|
990
992
|
browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
|
|
991
|
-
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:T("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:D,
|
|
993
|
+
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:T("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:D,kr=e=>e?{build:`
|
|
992
994
|
const r2sqlEnv = env as Record<string, unknown>;
|
|
993
995
|
const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
|
|
994
996
|
const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
|
|
@@ -999,11 +1001,11 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
999
1001
|
? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
|
|
1000
1002
|
: r2sqlStub;
|
|
1001
1003
|
`,configField:`
|
|
1002
|
-
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:T("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:D,
|
|
1004
|
+
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:T("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:D,xr=e=>e?{build:`
|
|
1003
1005
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1004
1006
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1005
1007
|
`,configField:`
|
|
1006
|
-
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:T("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:D,
|
|
1008
|
+
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:T("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:D,Yr=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(g(s.exportName,`container export "${s.exportName}"`),g(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
|
|
1007
1009
|
export class ${s.className} extends LunoraContainer {
|
|
1008
1010
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1009
1011
|
super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
|
|
@@ -1028,7 +1030,7 @@ import { ${o} } from "../containers.js";
|
|
|
1028
1030
|
|
|
1029
1031
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1030
1032
|
|
|
1031
|
-
${r}`},
|
|
1033
|
+
${r}`},wr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)g(r.exportName,`container export "${r.exportName}"`),g(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
|
|
1032
1034
|
`);return{build:`
|
|
1033
1035
|
const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
|
|
1034
1036
|
`,contextField:`
|
|
@@ -1037,7 +1039,7 @@ ${r}`},br=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1037
1039
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1038
1040
|
${n}
|
|
1039
1041
|
];
|
|
1040
|
-
`}},
|
|
1042
|
+
`}},Xr=e=>{if(e.length===0)return"";const t=e.map(r=>(g(r.exportName,`workflow export "${r.exportName}"`),g(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
|
|
1041
1043
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1042
1044
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1043
1045
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
@@ -1065,7 +1067,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1065
1067
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1066
1068
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1067
1069
|
|
|
1068
|
-
${t}`},
|
|
1070
|
+
${t}`},Zr=e=>{if(e.length===0)return"";const n=e.filter(a=>a.voice).length>0,r=e.map(a=>{g(a.exportName,`agent export "${a.exportName}"`),g(a.className,`agent class "${a.className}"`);const c=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
|
|
1069
1071
|
export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1070
1072
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1071
1073
|
super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
|
|
@@ -1093,7 +1095,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1093
1095
|
|
|
1094
1096
|
import { ${o} } from "../agents.js";
|
|
1095
1097
|
|
|
1096
|
-
${r}`},
|
|
1098
|
+
${r}`},eo=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)g(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
|
|
1097
1099
|
`);return`${R}/**
|
|
1098
1100
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1099
1101
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
@@ -1108,7 +1110,7 @@ import { ${n} } from "../queues.js";
|
|
|
1108
1110
|
export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
|
|
1109
1111
|
${r}
|
|
1110
1112
|
};
|
|
1111
|
-
`},
|
|
1113
|
+
`},vr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`workflow export "${n.exportName}"`),g(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
|
|
1112
1114
|
`);return{build:`
|
|
1113
1115
|
const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
|
|
1114
1116
|
`,contextField:`
|
|
@@ -1117,7 +1119,7 @@ ${r}
|
|
|
1117
1119
|
const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
|
|
1118
1120
|
${t}
|
|
1119
1121
|
];
|
|
1120
|
-
`}}
|
|
1122
|
+
`}},$r=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`queue export "${n.exportName}"`),g(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
|
|
1121
1123
|
`);return{build:`
|
|
1122
1124
|
const queues = createQueueContext(env, LUNORA_QUEUES);
|
|
1123
1125
|
`,contextField:`
|
|
@@ -1126,7 +1128,7 @@ ${t}
|
|
|
1126
1128
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
1127
1129
|
${t}
|
|
1128
1130
|
];
|
|
1129
|
-
`}},
|
|
1131
|
+
`}},Rr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`agent export "${n.exportName}"`),g(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
|
|
1130
1132
|
`);return{build:`
|
|
1131
1133
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1132
1134
|
`,contextField:`
|
|
@@ -1135,28 +1137,28 @@ ${t}
|
|
|
1135
1137
|
const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
|
|
1136
1138
|
${t}
|
|
1137
1139
|
];
|
|
1138
|
-
`}},
|
|
1140
|
+
`}},bt=(e,t,n,r,o)=>({constant:`
|
|
1139
1141
|
${o}
|
|
1140
1142
|
const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
1141
1143
|
`,override:`
|
|
1142
1144
|
protected override ${n}(): ${t} {
|
|
1143
1145
|
return ${e};
|
|
1144
1146
|
}
|
|
1145
|
-
`}),
|
|
1147
|
+
`}),Sr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return bt("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Nr=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return bt("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Tr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
|
|
1146
1148
|
const payments: LunoraPayment = config.payment
|
|
1147
1149
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1148
1150
|
: paymentStub;
|
|
1149
1151
|
`,configField:`
|
|
1150
1152
|
payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
|
|
1151
|
-
payments,`,stub:T("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},
|
|
1153
|
+
payments,`,stub:T("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},Ar=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
|
|
1152
1154
|
const x402: X402Pay = config.x402
|
|
1153
1155
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1154
1156
|
: x402Stub;
|
|
1155
1157
|
`,configField:`
|
|
1156
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:T("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:""},
|
|
1158
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:T("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:""},Or=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],to=({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:h=!1,hasImages:b=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:x=!1,hasR2sql:w=!1,hasX402:v=!1,maskMetadata:I,mutators:P=[],queues:C=[],rlsMetadata:$,schema:k,schemaSnapshot:M,shapes:oe=[],storageRules:B,studioFeatures:ae,useUmbrella:se=!1,workflows:W=[]})=>{const A=ne(se),X=P.length>0,O=oe.length>0,L=M===void 0?"":hn(M),j=M===void 0?"":`
|
|
1157
1159
|
/** 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. */
|
|
1158
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1159
|
-
`,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Se,contextField:Ne,stub:Te}=
|
|
1160
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(gn(M))}, json: ${JSON.stringify(L)} };
|
|
1161
|
+
`,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Se,contextField:Ne,stub:Te}=lr(a),ce=mr(i),V=cr(u),F=dr(p,A.flags),H=hr(s,p,A.flags),Z=ur(l),de=pr(o),G=gr(c),U=fr(b),K=br(h),Q=yr(d),q=kr(w),ee=xr(x),{build:Ae,contextField:xe,importLines:we,specs:ue}=$r(C),{build:Oe,contextField:Ie,importLines:ve,specs:pe}=wr(r,k.jurisdiction),{build:Ce,contextField:Le,importLines:$e,specs:_e}=vr(W),{build:Ee,contextField:me,importLines:he,specs:De}=Rr(n),{build:Fe,configField:Pe,contextField:ge,imports:fe,stub:He}=Tr(f),{build:m,configField:Me,imports:kt,stub:xt}=Ar(v),wt=e,vt=t,$t=$??{policies:[],roles:[]},Rt=I??{columns:[]},St=B??{rules:[]},Nt=ae??{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:Tt,override:At}=Sr(W),{constant:Ot,override:It}=Nr(C),J=k.vectorIndexes.length>0,Ge=new Set(k.tables.filter(y=>typeof y.shardMode=="object"&&y.shardMode.kind==="shardBy").map(y=>y.name)),Re=k.vectorIndexes.some(y=>Ge.has(y.table)),be=k.tables.some(y=>y.shardMode==="global"),Be=k.tables.some(y=>y.shardMode==="global"&&y.globalBackend==="hyperdrive"),Je=k.tables.some(y=>y.shardMode==="global"&&y.globalBackend!=="hyperdrive"),z=k.tables.some(y=>y.externalSource!==void 0);if(Je&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const je=k.tables.length>0,Ct=er(k),Lt=nr(k),_t=sr(k),Et=tr(k),ze=rr(k),Ye=Or(J,W.length>0,C.length>0,p);O&&Ye.push("WhereInput");const Xe=ir(be),Dt=O?`
|
|
1160
1162
|
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 {
|
|
1161
1163
|
const shape = LUNORA_SHAPES[name];
|
|
1162
1164
|
|
|
@@ -1209,30 +1211,30 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1209
1211
|
|
|
1210
1212
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1211
1213
|
}
|
|
1212
|
-
`:"",
|
|
1214
|
+
`:"",Ft=X?`
|
|
1213
1215
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1214
1216
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1215
1217
|
}
|
|
1216
|
-
`:"",
|
|
1217
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1218
|
-
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1219
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1220
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1218
|
+
`:"",Pt=O?"\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":"",Mt=O?"assertShapeShardable, ":"",ye=[`import type { ${Ye.join(", ")} } from "${A.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${Mt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Xe.importFragment}ShardDO as ShardDOBase } from "${A.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${A.do}";`]:[],O?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${A.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${A.server}";`];je&&ye.push(`import { bindOrm, bindTableFacade } from "${A.server}";`),J&&ye.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ye.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ye.push(...ce.importLines,...V.importLines,...F.importLines,...Z.importLines,...de.importLines,...G.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...$e,...we,...he,...fe,...kt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...X?["LUNORA_MUTATOR_PATHS"]:[],...O?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Bt=J?`
|
|
1219
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",jt=Je?`
|
|
1220
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",qt=Be?`
|
|
1221
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Wt=z?`
|
|
1222
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ut='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Kt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Qt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Vt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Ht=be?T("globalDbStub: DatabaseWriterLike",Ut,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Gt=J?T("vectorsStub: VectorSearchLike",Kt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Jt=Re?`
|
|
1221
1223
|
const vectorShardKey = this.currentShardKey();
|
|
1222
|
-
`:"",
|
|
1224
|
+
`:"",zt=Re?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Yt=Re?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${k.vectorIndexes.filter(y=>Ge.has(y.table)).map(y=>JSON.stringify(y.name)).join(", ")}] }`:"",Xt=J?`
|
|
1223
1225
|
let vectors: VectorSearchLike;
|
|
1224
1226
|
let onWrite: WriteHook | undefined;
|
|
1225
1227
|
|
|
1226
1228
|
if (config.vectors) {
|
|
1227
1229
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1228
|
-
${
|
|
1229
|
-
vectors = createContextVectors(lunora${
|
|
1230
|
-
onWrite = createVectorSyncHook({ ${
|
|
1230
|
+
${Jt}
|
|
1231
|
+
vectors = createContextVectors(lunora${Yt});
|
|
1232
|
+
onWrite = createVectorSyncHook({ ${zt}schema: schema as unknown as VectorSchemaLike, vectors });
|
|
1231
1233
|
} else {
|
|
1232
1234
|
vectors = vectorsStub;
|
|
1233
1235
|
onWrite = undefined;
|
|
1234
1236
|
}
|
|
1235
|
-
`:"",
|
|
1237
|
+
`:"",Zt=`{
|
|
1236
1238
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1237
1239
|
broadcast: (delta) => {
|
|
1238
1240
|
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
@@ -1259,11 +1261,11 @@ ${Gt}
|
|
|
1259
1261
|
scheduler,
|
|
1260
1262
|
schema: schema as unknown as SchemaLike,
|
|
1261
1263
|
sql: this.sql as SqlExec,
|
|
1262
|
-
});`,
|
|
1263
|
-
vectors,`:"",
|
|
1264
|
-
orm: bindOrm(facade),`:"",Ze=Be?"config.hyperdriveGlobal":"config.d1",
|
|
1264
|
+
});`,en=J?`
|
|
1265
|
+
vectors,`:"",tn=je?`
|
|
1266
|
+
orm: bindOrm(facade),`:"",Ze=Be?"config.hyperdriveGlobal":"config.d1",nn=be?` const globalRequest = { bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
|
|
1265
1267
|
const globalDb: DatabaseWriterLike = ${Ze}?.(env, globalRequest) ?? globalDbStub;
|
|
1266
|
-
`:"",
|
|
1268
|
+
`:"",rn=O&&be?`
|
|
1267
1269
|
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 }>> {
|
|
1268
1270
|
const env = this.env as Record<string, unknown>;
|
|
1269
1271
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1297,10 +1299,10 @@ ${Gt}
|
|
|
1297
1299
|
|
|
1298
1300
|
return rows;
|
|
1299
1301
|
}
|
|
1300
|
-
`:"",
|
|
1302
|
+
`:"",on=z?`
|
|
1301
1303
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1302
1304
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1303
|
-
`:"",
|
|
1305
|
+
`:"",an=z?`
|
|
1304
1306
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1305
1307
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1306
1308
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1435,7 +1437,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1435
1437
|
|
|
1436
1438
|
return nextDueAt;
|
|
1437
1439
|
}
|
|
1438
|
-
`:"",et=ze.length>0,
|
|
1440
|
+
`:"",et=ze.length>0,sn=z||et?`
|
|
1439
1441
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1440
1442
|
super(state, env);
|
|
1441
1443
|
${z?`
|
|
@@ -1453,21 +1455,21 @@ ${z?`
|
|
|
1453
1455
|
void this.scheduleTtlSweep();
|
|
1454
1456
|
}
|
|
1455
1457
|
`:""} }
|
|
1456
|
-
`:"",
|
|
1458
|
+
`:"",ln=je?`
|
|
1457
1459
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1458
1460
|
${k.tables.map(y=>` facade[${JSON.stringify(y.name)}] = bindTableFacade(db, ${JSON.stringify(y.name)});`).join(`
|
|
1459
1461
|
`)}
|
|
1460
|
-
`:"",
|
|
1462
|
+
`:"",cn=`${ce.build}${V.build}${F.build}${G.build}${de.build}
|
|
1461
1463
|
const secrets = createSecrets(env);
|
|
1462
|
-
`,
|
|
1463
|
-
secrets,`,
|
|
1464
|
+
`,dn=`${ce.contextField}${V.contextField}${F.contextField}${Z.contextField}${G.contextField}${de.contextField}
|
|
1465
|
+
secrets,`,un=Z.build,tt=b||h||d||w||x||v,pn=tt?`
|
|
1464
1466
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1465
1467
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1466
1468
|
if (isAction) {
|
|
1467
1469
|
${U.build}${K.build}${Q.build}${q.build}${ee.build}${m}${[...b?[" ctx.images = images;"]:[],...h?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...w?[" ctx.r2sql = r2sql;"]:[],...x?[" ctx.pipelines = pipelines;"]:[],...v?[" ctx.x402 = x402;"]:[]].join(`
|
|
1468
1470
|
`)}
|
|
1469
1471
|
}
|
|
1470
|
-
`:"",
|
|
1472
|
+
`:"",mn=tt?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1471
1473
|
`:"";return`${R}${ye.join(`
|
|
1472
1474
|
`)}
|
|
1473
1475
|
|
|
@@ -1478,47 +1480,50 @@ interface FunctionReference {
|
|
|
1478
1480
|
}
|
|
1479
1481
|
|
|
1480
1482
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1481
|
-
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(
|
|
1483
|
+
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Ct,void 0,4)};
|
|
1482
1484
|
|
|
1483
1485
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1484
|
-
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(
|
|
1486
|
+
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Lt,void 0,4)};
|
|
1485
1487
|
|
|
1486
1488
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1487
|
-
const LUNORA_TABLE_COLUMNS: Record<
|
|
1489
|
+
const LUNORA_TABLE_COLUMNS: Record<
|
|
1490
|
+
string,
|
|
1491
|
+
Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }>
|
|
1492
|
+
> = ${JSON.stringify(_t,void 0,4)};
|
|
1488
1493
|
|
|
1489
1494
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1490
|
-
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(
|
|
1495
|
+
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(Et,void 0,4)};
|
|
1491
1496
|
|
|
1492
1497
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1493
1498
|
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(ze,void 0,4)};
|
|
1494
1499
|
|
|
1495
1500
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1496
|
-
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(
|
|
1501
|
+
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(wt,void 0,4)};
|
|
1497
1502
|
|
|
1498
1503
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1499
|
-
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(
|
|
1504
|
+
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(vt,void 0,4)};
|
|
1500
1505
|
|
|
1501
1506
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1502
|
-
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(
|
|
1507
|
+
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify($t,void 0,4)};
|
|
1503
1508
|
|
|
1504
1509
|
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1505
|
-
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(
|
|
1510
|
+
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(Rt,void 0,4)};
|
|
1506
1511
|
|
|
1507
1512
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1508
|
-
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(
|
|
1513
|
+
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(St,void 0,4)};
|
|
1509
1514
|
|
|
1510
1515
|
/** 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. */
|
|
1511
|
-
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(
|
|
1512
|
-
${j}${
|
|
1516
|
+
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Nt,void 0,4)};
|
|
1517
|
+
${j}${H.constant}${Pt}${Tt}${Ot}${pe}${_e}${ue}${De}
|
|
1513
1518
|
export interface ShardDOConfig {
|
|
1514
1519
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1515
1520
|
cdc?: boolean;
|
|
1516
1521
|
/** 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. */
|
|
1517
1522
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1518
1523
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1519
|
-
storage?: (env: Record<string, unknown>) => unknown;${
|
|
1524
|
+
storage?: (env: Record<string, unknown>) => unknown;${Bt}${Se}${V.configField}${F.configField}${G.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Pe}${Me}${jt}${qt}${Wt}
|
|
1520
1525
|
}
|
|
1521
|
-
${T("schedulerStub",
|
|
1526
|
+
${T("schedulerStub",Qt,["cancel","runAfter","runAt"])}${T("storageStub",Vt,["delete","download","getMetadata","getSignedUrl","getUrl","list","upload"],{sync:["getUrl"]})}${Ht}${on}${Gt}${Te}${V.stub}${F.stub}${G.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${He}${xt}
|
|
1522
1527
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1523
1528
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1524
1529
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1555,7 +1560,7 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
|
|
|
1555
1560
|
* from the worker entry so wrangler binds it by name.
|
|
1556
1561
|
*/
|
|
1557
1562
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1558
|
-
class extends ShardDOBase {${
|
|
1563
|
+
class extends ShardDOBase {${sn}
|
|
1559
1564
|
private migrated = false;
|
|
1560
1565
|
|
|
1561
1566
|
public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker): Promise<unknown> {
|
|
@@ -1649,7 +1654,7 @@ ${Xe.override}
|
|
|
1649
1654
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
|
|
1650
1655
|
};
|
|
1651
1656
|
}
|
|
1652
|
-
${
|
|
1657
|
+
${Ft}${Dt}${rn}${an}
|
|
1653
1658
|
protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
|
|
1654
1659
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1655
1660
|
}
|
|
@@ -1666,7 +1671,9 @@ ${Dt}${Et}${nn}${on}
|
|
|
1666
1671
|
return LUNORA_TTL_SWEEPS;
|
|
1667
1672
|
}
|
|
1668
1673
|
|
|
1669
|
-
protected override tableColumns(
|
|
1674
|
+
protected override tableColumns(
|
|
1675
|
+
table: string,
|
|
1676
|
+
): Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }> {
|
|
1670
1677
|
return LUNORA_TABLE_COLUMNS[table] ?? [];
|
|
1671
1678
|
}
|
|
1672
1679
|
|
|
@@ -1689,7 +1696,7 @@ ${Dt}${Et}${nn}${on}
|
|
|
1689
1696
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1690
1697
|
return LUNORA_STUDIO_FEATURES;
|
|
1691
1698
|
}
|
|
1692
|
-
${
|
|
1699
|
+
${H.evaluateOverride}${H.subscriptionOverride}${At}${It}
|
|
1693
1700
|
protected override advisories(): AdvisoryFinding[] {
|
|
1694
1701
|
return LUNORA_ADVISORIES;
|
|
1695
1702
|
}
|
|
@@ -1922,7 +1929,7 @@ ${Y}
|
|
|
1922
1929
|
// dispatch path) fall back to the per-request fields as before.
|
|
1923
1930
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
1924
1931
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
1925
|
-
${
|
|
1932
|
+
${Xt}${le}${cn}${Oe}${Ce}${Ae}${Ee}
|
|
1926
1933
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
1927
1934
|
// Build the storage adapter once and share it between \`ctx.storage\`
|
|
1928
1935
|
// and \`ctx.db.system._storage\` so both read the same R2 binding. The
|
|
@@ -1949,13 +1956,13 @@ ${Yt}${le}${ln}${Oe}${Ce}${Ae}${Ee}
|
|
|
1949
1956
|
// so both write to the same trace.
|
|
1950
1957
|
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
1951
1958
|
|
|
1952
|
-
${
|
|
1959
|
+
${nn} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
1953
1960
|
// adds aggregate counters (call count, total time, per-operation
|
|
1954
1961
|
// breakdown) to the wide event rather than a span per call, so a
|
|
1955
1962
|
// handler making hundreds of queries stays readable. See
|
|
1956
1963
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
1957
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
1958
|
-
${
|
|
1964
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Zt}), logFunctionPath, traceAnchor, observability);
|
|
1965
|
+
${ln}${Fe}
|
|
1959
1966
|
|
|
1960
1967
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
1961
1968
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -1963,7 +1970,7 @@ ${sn}${Fe}
|
|
|
1963
1970
|
// writing mutation's trace from the shared per-request field.
|
|
1964
1971
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
1965
1972
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
1966
|
-
${
|
|
1973
|
+
${un}
|
|
1967
1974
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
1968
1975
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
1969
1976
|
// Query/mutation handlers must be deterministic (they may be re-run on
|
|
@@ -1986,13 +1993,13 @@ ${dn}
|
|
|
1986
1993
|
ip: this.getCurrentIp(),
|
|
1987
1994
|
log,
|
|
1988
1995
|
metrics,
|
|
1989
|
-
now,${
|
|
1996
|
+
now,${tn}
|
|
1990
1997
|
scheduler,
|
|
1991
1998
|
span,
|
|
1992
1999
|
storage,
|
|
1993
|
-
trace,${
|
|
2000
|
+
trace,${en}${Ne}${dn}${ge}${Ie}${Le}${xe}${me}
|
|
1994
2001
|
};
|
|
1995
|
-
${
|
|
2002
|
+
${mn}${pn}
|
|
1996
2003
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
1997
2004
|
ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
|
|
1998
2005
|
ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("query", reference.__lunoraRef, fnArgs, ctx);
|
|
@@ -2000,21 +2007,21 @@ ${pn}${un}
|
|
|
2000
2007
|
return ctx;
|
|
2001
2008
|
}
|
|
2002
2009
|
};
|
|
2003
|
-
`},
|
|
2010
|
+
`},Ve=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:N(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:N(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?Ve(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},yt=(e,t)=>{const n=re(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Ir=(e,t,n)=>{g(e,"drizzle column name");const r=Ve(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=yt(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},Cr=e=>{g(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(g(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},Lr=(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}: ${Ir(o,s,t)},`)].join(`
|
|
2004
2011
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2005
|
-
${e.indexes.map(o=>
|
|
2012
|
+
${e.indexes.map(o=>Cr(o)).join(`
|
|
2006
2013
|
`)}
|
|
2007
2014
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2008
2015
|
${n}
|
|
2009
|
-
}${r});`},
|
|
2010
|
-
`;const n=ne(t),r=new Set(e.map(h=>h.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=
|
|
2016
|
+
}${r});`},_r=e=>e.typeAnnotation?.includes('Id<"')??!1,Er=(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=Ve(a);n.add(c.builder),s=s||_r(c),o=o||yt(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}},rt=(e,t=!1)=>{if(e.length===0)return`${R}export {};
|
|
2017
|
+
`;const n=ne(t),r=new Set(e.map(h=>h.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Er(e,r),c=[...s,...o].toSorted((h,b)=>h.localeCompare(b)),d=e.map(h=>Lr(h,r)).join(`
|
|
2011
2018
|
|
|
2012
2019
|
`),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2013
2020
|
`:"",a?`import type { Id } from "./dataModel.js";
|
|
2014
2021
|
`:""].join("");return`${R}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2015
2022
|
${p}
|
|
2016
2023
|
${d}
|
|
2017
|
-
`},
|
|
2024
|
+
`},no=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:E(rt(n,t),Ue),shard:E(rt(r,t),Ue)}},ro=e=>{const t=new Map;for(const i of e){const a=t.get(i.cron);a?a.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
|
|
2018
2025
|
`),r=n.length>0?`
|
|
2019
2026
|
${n}
|
|
2020
2027
|
`:"",o=[...t.entries()].map(([i,a])=>{const c=a.map(d=>{const p=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${p}, args: ${JSON.stringify(d.args)} },`}).join(`
|
|
@@ -2048,7 +2055,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2048
2055
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2049
2056
|
*/
|
|
2050
2057
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
|
|
2051
|
-
`},
|
|
2058
|
+
`},oo=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
|
|
2052
2059
|
`),n=t.length>0?`
|
|
2053
2060
|
${t}
|
|
2054
2061
|
`:"";return`${R}/**
|
|
@@ -2072,4 +2079,4 @@ export interface LunoraVectorIndex {
|
|
|
2072
2079
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2073
2080
|
*/
|
|
2074
2081
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2075
|
-
`},
|
|
2082
|
+
`},ao=e=>[...new Set(e.map(t=>t.cron))];export{Kr as A,fn as C,R as G,Fn as U,Vr as a,Gr as b,Yr as c,ro as d,Zr as e,Qr as f,no as g,zr as h,Jr as i,to as j,oo as k,Xr as l,ao as m,tr as n,eo as o,Hr as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as D}from"./emit-
|
|
1
|
+
import{A as S,G as D}from"./emit-C935cHCe.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]),g=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";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, 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(l),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(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";']},I=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>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const b=/[^a-zA-Z0-9]+/gu,M=/([a-z0-9])([A-Z])/gu,p=t=>t.split(b).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),L=t=>t.replaceAll(M,"$1_$2").replaceAll(b,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),O=t=>t==="query"?"query":t==="action"?"action":"mutation",i=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>i(o,e+1));const r=t;if(r.type==="integer"&&r.format==="int64"||r.type==="string"&&r.contentEncoding==="base64")return!0;const{properties:n}=r;return n!==null&&typeof n=="object"&&Object.values(n).some(o=>i(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>i(r[o],e+1))},R=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),T=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),j=["$","{","'","$","'","}"].join(""),D=t=>T(t).split("$").join(j),_=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,h=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const r=t;return r.type==="null"||Array.isArray(r.type)&&r.type.includes("null")?!0:["anyOf","oneOf"].some(n=>{const o=r[n];return Array.isArray(o)&&o.some(s=>h(s,e+1))})},E=(t,e,r)=>e.length===0?r===0?[]:[t]:e.map(n=>({properties:{...t.properties,...n.properties},required:new Set([...t.required,...n.required])})),C=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const r=t.required;return[{properties:e,required:new Set(Array.isArray(r)?r.filter(n=>typeof n=="string"):[])}]},m=(t,e,r)=>{const n=t[e];return Array.isArray(n)?n.flatMap(o=>A(o,r+1)):[]},A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[...C(r),...m(r,"allOf",e)],o={properties:Object.assign({},...n.map(a=>a.properties)),required:new Set(n.flatMap(a=>[...a.required]))},s=[...m(r,"anyOf",e),...m(r,"oneOf",e)];return E(o,s,n.length)},S=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[r];for(const o of["anyOf","oneOf","allOf"]){const s=r[o];if(Array.isArray(s))for(const a of s)n.push(...S(a,e+1))}return n},y=(t,e,r,n=0)=>{if(n>f||t===null||typeof t!="object")return;const o=A(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,l)=>a.localeCompare(l));for(const a of s){const l=[...e,a],u=o.every(c=>c.required.has(a)),g=o.map(c=>c.properties[a]).filter(c=>c!==void 0);u?g.some(c=>h(c))&&r.nullable.push(l):r.optional.push(l);for(const c of g)y(c,l,r,n+1)}for(const a of S(t))for(const l of["additionalProperties","items"]){const u=a[l];u!==null&&typeof u=="object"&&y(u,[...e,"*"],r,n+1)}},N=(t,e)=>t.join("\0").localeCompare(e.join("\0")),k=t=>{const e={nullable:[],optional:[]};y(t,[],e);const r=n=>[...new Map(n.map(o=>[o.join("\0"),o])).values()].toSorted(N);return{nullable:r(e.nullable),optional:r(e.optional)}},w=t=>{const[e="",r=""]=t.name.split(":"),n=`${p(e)}${p(r)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:k(o),argsType:d(o)&&!i(o)?`${n}Args`:void 0,takesArgs:d(o),functionName:r,functionPath:t.name,namespace:e,resultType:d(s)&&!i(s)?`${n}Result`:void 0,summary:t.summary??t.name,verb:O(t["x-lunora-function-kind"])}},x=t=>{const e=new Map;for(const r of t.methods){const n=w(r),o=e.get(n.namespace);o===void 0?e.set(n.namespace,[n]):o.push(n)}return[...e.entries()].toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({methods:n.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:r}))},I=t=>t.methods.flatMap(e=>{const r=w(e);return[{name:r.argsType,schema:e.params?.[0]?.schema},{name:r.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,r)=>e.name.localeCompare(r.name)),P=/^[A-Za-z][A-Za-z0-9]*$/u,$=t=>P.test(t),q=t=>{const e=new Map;for(const r of t.methods){const n=p(r.functionName);if(!$(n))throw new Error(`sdk: function "${r.functionPath}" produces the invalid identifier "${n}" — rename the export so it starts with a letter.`);const o=r.verb==="query"?[n,`Subscribe${n}`,`Watch${n}`]:[n];for(const s of o){const a=e.get(s);if(a!==void 0){const l=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${r.functionPath}" both generate "${s}"${l} — rename one so the generated methods stay distinct.`)}e.set(s,r.functionPath)}}},z=t=>{const e=new Map;for(const r of t){const n=p(r.name);if(!$(n))throw new Error(`sdk: namespace "${r.name}" produces the invalid identifier "${n}" — rename the file so it starts with a letter.`);const o=e.get(n);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${r.name}" both generate "${n}" — rename one so the generated types stay distinct.`);e.set(n,r.name),q(r)}},v=t=>t.flatMap(e=>e.methods),H=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],U=(t,e)=>{const r=n=>n!==void 0&&new RegExp(String.raw`\b${n}\b`,"u").test(e)?n:void 0;return t.map(n=>({methods:n.methods.map(o=>({...o,argsType:r(o.argsType),resultType:r(o.resultType)})),name:n.name}))},W=t=>t.methods.filter(e=>i(e.params?.[0]?.schema)||i(e.result?.schema)).map(e=>e.name).toSorted((e,r)=>e.localeCompare(r)),Z=(t,e)=>[...new Set(v(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!new RegExp(String.raw`\b${r}\b`,"u").test(e)))].toSorted((r,n)=>r.localeCompare(n)),F=t=>[...new Set(v(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,r)=>e.localeCompare(r));export{v as allMethods,_ as argsChoice,z as assertGeneratable,R as commentText,H as generatedHeaderLines,i as hasUnrepresentableWireType,d as isTypedSchema,D as kotlinLiteral,I as modelSources,k as nullPathsOf,w as parseMethod,x as parseSpec,F as referencedModels,T as stringLiteral,p as toPascalCase,L as toSnakeCase,Z as undeclaredModels,W as unrepresentableFunctions,O as verbForKind,U as withDeclaredModels};
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const b=/[^a-zA-Z0-9]+/gu,M=/([a-z0-9])([A-Z])/gu,p=t=>t.split(b).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),L=t=>t.replaceAll(M,"$1_$2").replaceAll(b,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),O=t=>t==="query"?"query":t==="action"?"action":"mutation",i=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>i(o,e+1));const r=t;if(r.type==="integer"&&r.format==="int64"||r.type==="string"&&r.contentEncoding==="base64")return!0;const{properties:n}=r;return n!==null&&typeof n=="object"&&Object.values(n).some(o=>i(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>i(r[o],e+1))},R=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),T=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
-
`,"\\n").replaceAll("\r","\\r"),j=["$","{","'","$","'","}"].join(""),_=t=>T(t).split("$").join(j),D=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const r=t;return r.type==="null"||Array.isArray(r.type)&&r.type.includes("null")?!0:["anyOf","oneOf"].some(n=>{const o=r[n];return Array.isArray(o)&&o.some(a=>A(a,e+1))})},E=(t,e,r)=>e.length===0?r===0?[]:[t]:e.map(n=>({properties:{...t.properties,...n.properties},required:new Set([...t.required,...n.required])})),C=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const r=t.required;return[{properties:e,required:new Set(Array.isArray(r)?r.filter(n=>typeof n=="string"):[])}]},m=(t,e,r)=>{const n=t[e];return Array.isArray(n)?n.flatMap(o=>h(o,r+1)):[]},h=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[...C(r),...m(r,"allOf",e)],o={properties:Object.assign({},...n.map(s=>s.properties)),required:new Set(n.flatMap(s=>[...s.required]))},a=[...m(r,"anyOf",e),...m(r,"oneOf",e)];return E(o,a,n.length)},S=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[r];for(const o of["anyOf","oneOf","allOf"]){const a=r[o];if(Array.isArray(a))for(const s of a)n.push(...S(s,e+1))}return n},y=(t,e,r,n=0)=>{if(n>f||t===null||typeof t!="object")return;const o=h(t),a=[...new Set(o.flatMap(s=>Object.keys(s.properties)))].toSorted((s,c)=>s.localeCompare(c));for(const s of a){const c=[...e,s],u=o.every(l=>l.required.has(s)),g=o.map(l=>l.properties[s]).filter(l=>l!==void 0);u?g.some(l=>A(l))&&r.nullable.push(c):r.optional.push(c);for(const l of g)y(l,c,r,n+1)}for(const s of S(t))for(const c of["additionalProperties","items"]){const u=s[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],r,n+1)}},N=(t,e)=>t.join("\0").localeCompare(e.join("\0")),k=t=>{const e={nullable:[],optional:[]};y(t,[],e);const r=n=>[...new Map(n.map(o=>[o.join("\0"),o])).values()].toSorted(N);return{nullable:r(e.nullable),optional:r(e.optional)}},w=t=>{const[e="",r=""]=t.name.split(":"),n=`${p(e)}${p(r)}`,o=t.params?.[0]?.schema,a=t.result?.schema;return{argsNullPaths:k(o),argsType:d(o)&&!i(o)?`${n}Args`:void 0,takesArgs:d(o),functionName:r,functionPath:t.name,namespace:e,resultType:d(a)&&!i(a)?`${n}Result`:void 0,summary:t.summary??t.name,verb:O(t["x-lunora-function-kind"])}},x=t=>{const e=new Map;for(const r of t.methods){const n=w(r),o=e.get(n.namespace);o===void 0?e.set(n.namespace,[n]):o.push(n)}return[...e.entries()].toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({methods:n.toSorted((o,a)=>o.functionName.localeCompare(a.functionName)),name:r}))},I=t=>t.methods.flatMap(e=>{const r=w(e);return[{name:r.argsType,schema:e.params?.[0]?.schema},{name:r.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,r)=>e.name.localeCompare(r.name)),P=/^[A-Za-z][A-Za-z0-9]*$/u,$=t=>P.test(t),q=t=>{const e=new Map;for(const r of t.methods){const n=p(r.functionName);if(!$(n))throw new Error(`sdk: function "${r.functionPath}" produces the invalid identifier "${n}" — rename the export so it starts with a letter.`);const o=r.verb==="query"?[n,`Subscribe${n}`]:[n];for(const a of o){const s=e.get(a);if(s!==void 0)throw new Error(`sdk: functions "${s}" and "${r.functionPath}" both generate "${a}" — rename one so the generated methods stay distinct.`);e.set(a,r.functionPath)}}},z=t=>{const e=new Map;for(const r of t){const n=p(r.name);if(!$(n))throw new Error(`sdk: namespace "${r.name}" produces the invalid identifier "${n}" — rename the file so it starts with a letter.`);const o=e.get(n);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${r.name}" both generate "${n}" — rename one so the generated types stay distinct.`);e.set(n,r.name),q(r)}},v=t=>t.flatMap(e=>e.methods),H=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],U=(t,e)=>{const r=n=>n!==void 0&&new RegExp(String.raw`\b${n}\b`,"u").test(e)?n:void 0;return t.map(n=>({methods:n.methods.map(o=>({...o,argsType:r(o.argsType),resultType:r(o.resultType)})),name:n.name}))},Z=t=>t.methods.filter(e=>i(e.params?.[0]?.schema)||i(e.result?.schema)).map(e=>e.name).toSorted((e,r)=>e.localeCompare(r)),F=(t,e)=>[...new Set(v(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!new RegExp(String.raw`\b${r}\b`,"u").test(e)))].toSorted((r,n)=>r.localeCompare(n)),G=t=>[...new Set(v(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,r)=>e.localeCompare(r));export{v as allMethods,D as argsChoice,z as assertGeneratable,R as commentText,H as generatedHeaderLines,i as hasUnrepresentableWireType,d as isTypedSchema,_ as kotlinLiteral,I as modelSources,k as nullPathsOf,w as parseMethod,x as parseSpec,G as referencedModels,T as stringLiteral,p as toPascalCase,L as toSnakeCase,F as undeclaredModels,Z as unrepresentableFunctions,O as verbForKind,U as withDeclaredModels};
|