@lunora/codegen 1.0.0-alpha.349 → 1.0.0-alpha.350
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.d.mts +10 -4
- package/dist/index.d.ts +10 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/OPENRPC_VERSION-DfSmacMR.mjs +3 -0
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-8WCMDjUZ.mjs → SCHEMA_SNAPSHOT_FILENAME-DYEopqtc.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-CJG4S6CK.mjs +1 -0
- package/dist/packem_shared/{emitShard-X1mcPmq6.mjs → emitShard-CFUBJcKw.mjs} +1 -1
- package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
- package/dist/packem_shared/{shard-C_cP6i89.mjs → shard-6Xk0XLNG.mjs} +28 -21
- package/dist/sdk/index.mjs +1 -1
- package/package.json +8 -8
- package/dist/packem_shared/OPENRPC_VERSION-l4HD4osw.mjs +0 -3
- package/dist/packem_shared/discoverFunctions-DkPOc8b9.mjs +0 -1
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +0 -4
package/dist/index.d.mts
CHANGED
|
@@ -1498,6 +1498,12 @@ interface FunctionIR {
|
|
|
1498
1498
|
kind: "room";
|
|
1499
1499
|
name: string;
|
|
1500
1500
|
};
|
|
1501
|
+
/**
|
|
1502
|
+
* The doc comment on the statement that declares the registration, when there
|
|
1503
|
+
* is one. Read from the JSDoc description only (tags are dropped). Absent when
|
|
1504
|
+
* the export has no doc comment, or when it is an `export default`.
|
|
1505
|
+
*/
|
|
1506
|
+
description?: string;
|
|
1501
1507
|
exportName: string;
|
|
1502
1508
|
/**
|
|
1503
1509
|
* Set by the `.expose({ rest: true })` builder modifier (plan 167). When
|
|
@@ -4451,10 +4457,10 @@ interface OpenRpcEmitInput {
|
|
|
4451
4457
|
/**
|
|
4452
4458
|
* Emit an OpenRPC 1.x document describing Lunora's JSON-RPC surface.
|
|
4453
4459
|
*
|
|
4454
|
-
*
|
|
4455
|
-
* function, `name` = `file:fn
|
|
4456
|
-
*
|
|
4457
|
-
*
|
|
4460
|
+
* `query`/`mutation`/`action`/`stream` functions become `methods` — one per
|
|
4461
|
+
* function, `name` = `file:fn`, with the kind in `x-lunora-function-kind`. `internal`
|
|
4462
|
+
* (off the external RPC path) is excluded. A stream's `result` is the description-only
|
|
4463
|
+
* placeholder: it has no single result. Each method's single `args` param is typed from
|
|
4458
4464
|
* the function's `v.*` validators (`argsObjectSchema`); `result` is the
|
|
4459
4465
|
* `.output()` schema when declared, else a best-effort inferred schema. The
|
|
4460
4466
|
* standard `LunoraError` codes ride along under each method's `errors`.
|
package/dist/index.d.ts
CHANGED
|
@@ -1498,6 +1498,12 @@ interface FunctionIR {
|
|
|
1498
1498
|
kind: "room";
|
|
1499
1499
|
name: string;
|
|
1500
1500
|
};
|
|
1501
|
+
/**
|
|
1502
|
+
* The doc comment on the statement that declares the registration, when there
|
|
1503
|
+
* is one. Read from the JSDoc description only (tags are dropped). Absent when
|
|
1504
|
+
* the export has no doc comment, or when it is an `export default`.
|
|
1505
|
+
*/
|
|
1506
|
+
description?: string;
|
|
1501
1507
|
exportName: string;
|
|
1502
1508
|
/**
|
|
1503
1509
|
* Set by the `.expose({ rest: true })` builder modifier (plan 167). When
|
|
@@ -4451,10 +4457,10 @@ interface OpenRpcEmitInput {
|
|
|
4451
4457
|
/**
|
|
4452
4458
|
* Emit an OpenRPC 1.x document describing Lunora's JSON-RPC surface.
|
|
4453
4459
|
*
|
|
4454
|
-
*
|
|
4455
|
-
* function, `name` = `file:fn
|
|
4456
|
-
*
|
|
4457
|
-
*
|
|
4460
|
+
* `query`/`mutation`/`action`/`stream` functions become `methods` — one per
|
|
4461
|
+
* function, `name` = `file:fn`, with the kind in `x-lunora-function-kind`. `internal`
|
|
4462
|
+
* (off the external RPC path) is excluded. A stream's `result` is the description-only
|
|
4463
|
+
* placeholder: it has no single result. Each method's single `args` param is typed from
|
|
4458
4464
|
* the function's `v.*` validators (`argsObjectSchema`); `result` is the
|
|
4459
4465
|
* `.output()` schema when declared, else a best-effort inferred schema. The
|
|
4460
4466
|
* standard `LunoraError` codes ride along under each method's `errors`.
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as g}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-isdHqPIt.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-C3QumE88.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-CScPrUD-.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs";import{default as P}from"./packem_shared/discoverCrons-B1_NUt19.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-DjRHg-Zk.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BQk3SX8D.mjs";import{default as K}from"./packem_shared/discoverFunctions-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as g}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-isdHqPIt.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-C3QumE88.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-CScPrUD-.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs";import{default as P}from"./packem_shared/discoverCrons-B1_NUt19.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-DjRHg-Zk.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BQk3SX8D.mjs";import{default as K}from"./packem_shared/discoverFunctions-CJG4S6CK.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DCDgDIYv.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-CL-d0IVo.mjs";import{default as J}from"./packem_shared/discoverInserts-BcoTjXqI.mjs";import{d as X}from"./packem_shared/index-CN8FVvr-.mjs";import{default as $}from"./packem_shared/discoverMigrations-BWxx8Wv9.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Cy9h3EVW.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-mFJNU8qY.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-9to_l_Kh.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-CxQRVuIV.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Civ-7SiI.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4oeTYEM.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-Cl6UKT7L.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-D0B4nCmG.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage--Z1vx7GM.mjs";import{default as he}from"./packem_shared/discoverSchema-Cwt-DQgh.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-DVJbfDZ8.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CitX6ziW.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-kXq07aGl.mjs";import{emitApp as je}from"./packem_shared/emitApp-BcLO2eih.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-DWdj2jvW.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DfSmacMR.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DYEopqtc.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-H9eQX4ui.mjs";import{default as vr}from"./packem_shared/fingerprintSchemaSources-BKXkgkj4.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-bct1OuH5.mjs";import{e as Ur}from"./packem_shared/server-DlEPJi5i.mjs";import{e as Hr}from"./packem_shared/shard-6Xk0XLNG.mjs";import{G as Br}from"./packem_shared/shared-8vTRkL2-.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-ClPr_MXM.mjs";import{s as Yr,t as Xr,u as Zr}from"./packem_shared/shard-runtime-ByYXjCKY.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-zynTVppI.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-lc-hnJYn.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-CuFqq97x.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-D7mopPiT.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,g as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,vr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{m}from"./modules-l-Db0C4S.mjs";import{r as u}from"./json-data-Chfs2Cz5.mjs";import{validatorIrToJsonSchema as p,objectSchema as l,LUNORA_ERROR_CODES as d}from"./LUNORA_ERROR_CODES-CIAJQeKB.mjs";import{G as h}from"./shared-8vTRkL2-.mjs";import{s as i}from"./dispatch-namespace-DwTjD7BU.mjs";const R="1.3.2",g={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},O=(e,r)=>e==="stream"?`Open the \`stream\` \`${r}\` over the Lunora WebSocket. It yields chunks rather than one result, so its \`result\` schema is a placeholder.`:`Invoke the \`${e}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${r}", "args": { … } }\`).`,S=(e,r)=>{const o=`${i(e.filePath)}:${e.exportName}`;return{description:O(e.kind,o),errors:d.map((s,a)=>({code:-32e3-a,data:{code:s},message:s})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:l(e.args)}],result:{name:"result",schema:e.output&&e.kind!=="stream"?p(e.output):g},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,...e.description?{"x-lunora-description":e.description}:{},"x-tags":[{name:r}]}},v=e=>{const r=e.version??"0.0.0",n=e.functions.filter(t=>t.visibility!=="internal"),o=e.modules??[],s=n.map(t=>S(t,m(o,t.filePath))).toSorted((t,c)=>t.name.localeCompare(c.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:r},methods:s,openrpc:R}},E=e=>`${JSON.stringify(v(e),void 0,2)}
|
|
2
|
+
`,N=e=>`${h}export const openRpcSpec = ${u(e,"Record<string, unknown>")};
|
|
3
|
+
`;export{R as OPENRPC_VERSION,v as buildOpenRpcDocument,E as emitOpenRpc,N as emitOpenRpcModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as M,readFileSync as Ge,mkdirSync as Bt,writeFileSync as gr,rmSync as ye,readdirSync as Cn}from"node:fs";import{dirname as Vt,join as E,relative as Tn}from"node:path";import{performance as ht}from"node:perf_hooks";import{runAdvisor as pr}from"@lunora/advisor";import{LunoraError as _}from"@lunora/errors";import{serializeSchemaSnapshot as mr}from"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{toAdvisorContext as hr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ut,ts as vr,VariableDeclarationKind as Er}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as w,bindingKeyName as ce,collectCallRows as C,findObjectProperty as V,collectSecurityCallRows as xr,propertyInitializer as R,listSecurityScanFiles as Ye,objectLiteralFromCallbackBody as On,limitNameOf as kn,optionsObjectLiteral as Rn,handlerOf as Sr,collectNodeRows as ne,chainRootOf as Qe,outermostValueWrapper as I,isWriteTarget as Xe,isSameNode as y,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as Wt,returningFunctionOf as wt,walkChain as Ar,RUN_METHODS as Fn,functionReferenceSegments as yr,isTestPath as br,isFunctionLike as re,functionKeyOf as Ln}from"./isTestPath-C3QumE88.mjs";import{b as Q,d as j,f as L,g as qt,c as x,a as jt,w as Ht,k as Nr,l as Pr,h as wr,m as Ir,j as It,i as Cr}from"./attribution-CG8-kUcl.mjs";import{a as Fs,r as vt,i as G,b as Tr,m as Dn,c as Je,e as Gt,E as Mn,C as _n,d as Or,f as kr,g as Rr}from"./context-root-CNR6TAsP.mjs";import{a as P,i as Fr,c as ee,d as Kn,e as Lr,f as Dr,g as zn}from"./classify-procedure-call-BkaeM9Ej.mjs";import{a as S,s as Mr}from"./property-name-7cBlgK_O.mjs";import{b as _r,a as Ze}from"./module-specifiers-BctA0m_p.mjs";import{r as et,s as Kr}from"./parse-validator-iVTounLK.mjs";import zr from"./discoverAuthApiCalls-CScPrUD-.mjs";import{i as z,r as $n}from"./database-calls-UPlhi3Ks.mjs";import $r from"./discoverHyperdriveCalls-CL-d0IVo.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Yt,a as Be,s as Bn,d as Br}from"./index-CN8FVvr-.mjs";import{MUTATORS_FILENAME as Vr,isDefineMutatorCallee as Ur,mutatorServerImplOf as Wr,discoverMutators as qr}from"./MUTATORS_FILENAME-Cy9h3EVW.mjs";import jr from"./discoverNondeterministicCalls-mFJNU8qY.mjs";import{discoverNotifyConfig as Hr,discoverNotifyCalls as Gr}from"./NOTIFY_FILENAME-9to_l_Kh.mjs";import Yr from"./discoverR2sqlCalls-B4oeTYEM.mjs";import Qr from"./discoverRlsProcedures-Cl6UKT7L.mjs";import{s as Qt,n as Xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Jr,redact as Zr,isHeuristicSecretKind as eo,isSecretishName as to}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Vn,readMergeDurableObjects as so}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Le,d as no,r as io}from"./modules-l-Db0C4S.mjs";import{WORKFLOWS_FILENAME as ro,discoverWorkflows as oo}from"./WORKFLOWS_FILENAME-kXq07aGl.mjs";import{r as ao}from"./json-data-Chfs2Cz5.mjs";import{a as co,I as lo,g as uo,G as Un,d as fo,i as go}from"./shared-8vTRkL2-.mjs";import{createCodegenProject as po}from"./createCodegenProject-ClPr_MXM.mjs";import{findTsconfig as wE,refreshCodegenProject as IE,tsconfigFingerprint as CE}from"./createCodegenProject-ClPr_MXM.mjs";import{CAPABILITIES as mo,usedCapabilities as ho}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Wn,isHyperdriveGlobalTable as qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as vo}from"./AGENTS_FILENAME-isdHqPIt.mjs";import{discoverContainers as Eo}from"./CONTAINERS_FILENAME-mK4cZpcz.mjs";import xo from"./discoverCrons-B1_NUt19.mjs";import{contextPropertiesRead as So,fileWiresRequestSecretTool as Ao,createTargetScope as yo,discoverFeatureUsage as bo}from"./capabilitiesUsedBy-DjRHg-Zk.mjs";import jn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as No,findProjectConfigFile as Po}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as wo}from"./QUEUES_FILENAME-Civ-7SiI.mjs";import{discoverSandboxUsage as Io}from"./discoverSandboxUsage--Z1vx7GM.mjs";import{resolveServiceBindings as Co}from"./readServiceBindings-BA49C6aN.mjs";import To from"./discoverStorageRulesMetadata-CitX6ziW.mjs";import{resolveCodegenTarget as Ct,gatePlatformFeatures as Oo,readTargetDiagnostics as ko,vectorizeDimensionDiagnostics as Ro,liveStreamsDeliveryAuthorizationDiagnostic as Fo,socketRoutesDeliveryAuthorizationDiagnostic as Lo,studioPlatformFor as Do,platformFeatureAvailable as Mo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as _o}from"./schema-BgM8A3XV.mjs";import{b as Hn,e as Ko}from"./shard-
|
|
1
|
+
import{existsSync as M,readFileSync as Ge,mkdirSync as Bt,writeFileSync as gr,rmSync as ye,readdirSync as Cn}from"node:fs";import{dirname as Vt,join as E,relative as Tn}from"node:path";import{performance as ht}from"node:perf_hooks";import{runAdvisor as pr}from"@lunora/advisor";import{LunoraError as _}from"@lunora/errors";import{serializeSchemaSnapshot as mr}from"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import{toAdvisorContext as hr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ut,ts as vr,VariableDeclarationKind as Er}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as w,bindingKeyName as ce,collectCallRows as C,findObjectProperty as V,collectSecurityCallRows as xr,propertyInitializer as R,listSecurityScanFiles as Ye,objectLiteralFromCallbackBody as On,limitNameOf as kn,optionsObjectLiteral as Rn,handlerOf as Sr,collectNodeRows as ne,chainRootOf as Qe,outermostValueWrapper as I,isWriteTarget as Xe,isSameNode as y,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as Wt,returningFunctionOf as wt,walkChain as Ar,RUN_METHODS as Fn,functionReferenceSegments as yr,isTestPath as br,isFunctionLike as re,functionKeyOf as Ln}from"./isTestPath-C3QumE88.mjs";import{b as Q,d as j,f as L,g as qt,c as x,a as jt,w as Ht,k as Nr,l as Pr,h as wr,m as Ir,j as It,i as Cr}from"./attribution-CG8-kUcl.mjs";import{a as Fs,r as vt,i as G,b as Tr,m as Dn,c as Je,e as Gt,E as Mn,C as _n,d as Or,f as kr,g as Rr}from"./context-root-CNR6TAsP.mjs";import{a as P,i as Fr,c as ee,d as Kn,e as Lr,f as Dr,g as zn}from"./classify-procedure-call-BkaeM9Ej.mjs";import{a as S,s as Mr}from"./property-name-7cBlgK_O.mjs";import{b as _r,a as Ze}from"./module-specifiers-BctA0m_p.mjs";import{r as et,s as Kr}from"./parse-validator-iVTounLK.mjs";import zr from"./discoverAuthApiCalls-CScPrUD-.mjs";import{i as z,r as $n}from"./database-calls-UPlhi3Ks.mjs";import $r from"./discoverHyperdriveCalls-CL-d0IVo.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Yt,a as Be,s as Bn,d as Br}from"./index-CN8FVvr-.mjs";import{MUTATORS_FILENAME as Vr,isDefineMutatorCallee as Ur,mutatorServerImplOf as Wr,discoverMutators as qr}from"./MUTATORS_FILENAME-Cy9h3EVW.mjs";import jr from"./discoverNondeterministicCalls-mFJNU8qY.mjs";import{discoverNotifyConfig as Hr,discoverNotifyCalls as Gr}from"./NOTIFY_FILENAME-9to_l_Kh.mjs";import Yr from"./discoverR2sqlCalls-B4oeTYEM.mjs";import Qr from"./discoverRlsProcedures-Cl6UKT7L.mjs";import{s as Qt,n as Xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Jr,redact as Zr,isHeuristicSecretKind as eo,isSecretishName as to}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Vn,readMergeDurableObjects as so}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Le,d as no,r as io}from"./modules-l-Db0C4S.mjs";import{WORKFLOWS_FILENAME as ro,discoverWorkflows as oo}from"./WORKFLOWS_FILENAME-kXq07aGl.mjs";import{r as ao}from"./json-data-Chfs2Cz5.mjs";import{a as co,I as lo,g as uo,G as Un,d as fo,i as go}from"./shared-8vTRkL2-.mjs";import{createCodegenProject as po}from"./createCodegenProject-ClPr_MXM.mjs";import{findTsconfig as wE,refreshCodegenProject as IE,tsconfigFingerprint as CE}from"./createCodegenProject-ClPr_MXM.mjs";import{CAPABILITIES as mo,usedCapabilities as ho}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Wn,isHyperdriveGlobalTable as qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as vo}from"./AGENTS_FILENAME-isdHqPIt.mjs";import{discoverContainers as Eo}from"./CONTAINERS_FILENAME-mK4cZpcz.mjs";import xo from"./discoverCrons-B1_NUt19.mjs";import{contextPropertiesRead as So,fileWiresRequestSecretTool as Ao,createTargetScope as yo,discoverFeatureUsage as bo}from"./capabilitiesUsedBy-DjRHg-Zk.mjs";import jn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as No,findProjectConfigFile as Po}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as wo}from"./QUEUES_FILENAME-Civ-7SiI.mjs";import{discoverSandboxUsage as Io}from"./discoverSandboxUsage--Z1vx7GM.mjs";import{resolveServiceBindings as Co}from"./readServiceBindings-BA49C6aN.mjs";import To from"./discoverStorageRulesMetadata-CitX6ziW.mjs";import{resolveCodegenTarget as Ct,gatePlatformFeatures as Oo,readTargetDiagnostics as ko,vectorizeDimensionDiagnostics as Ro,liveStreamsDeliveryAuthorizationDiagnostic as Fo,socketRoutesDeliveryAuthorizationDiagnostic as Lo,studioPlatformFor as Do,platformFeatureAvailable as Mo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as _o}from"./schema-BgM8A3XV.mjs";import{b as Hn,e as Ko}from"./shard-6Xk0XLNG.mjs";import{e as zo,a as $o}from"./server-DlEPJi5i.mjs";import{emitDataModel as Bo}from"./emitDataModel-CuFqq97x.mjs";import{i as Vo,a as Uo,e as Wo,b as qo,d as jo,c as Ho}from"./unwrap-handler-return-CGdJGvGh.mjs";import Go from"./discoverFunctions-CJG4S6CK.mjs";import Yo from"./discoverHttpRoutes-DCDgDIYv.mjs";import Qo from"./discoverInserts-BcoTjXqI.mjs";import{e as Gn}from"./exported-procedure-chains-D1WlRfqJ.mjs";import Xo from"./discoverMigrations-BWxx8Wv9.mjs";import Jo from"./discoverQueries-CxQRVuIV.mjs";import Zo from"./discoverRlsMetadata-D0B4nCmG.mjs";import ea from"./discoverSchema-Cwt-DQgh.mjs";import{discoverShapes as ta}from"./SHAPES_FILENAME-DVJbfDZ8.mjs";import{i as sa}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as na}from"./emitApp-BcLO2eih.mjs";import{readJsonSync as ia}from"@visulima/fs";import{buildSchemaSnapshot as ra}from"./SchemaSnapshotParseError-H9eQX4ui.mjs";import{buildOpenApiDocument as oa,emitOpenApiModule as aa}from"./buildOpenApiDocument-DWdj2jvW.mjs";import{buildOpenRpcDocument as ca,emitOpenRpcModule as la}from"./OPENRPC_VERSION-DfSmacMR.mjs";import{v as da,t as ua,u as fa,s as ga,w as pa}from"./shard-runtime-ByYXjCKY.mjs";import{emitCollections as ma,emitSeed as ha,emitApi as va,emitInternalApi as Ea}from"./emitApi-zynTVppI.mjs";import{emitCrons as xa,emitScheduler as Sa,emitShardRegistry as Aa,emitDurableObjects as ya,emitVectors as ba,emitWranglerCronTriggers as Na}from"./emitCrons-lc-hnJYn.mjs";import Pa from"./emitDrizzleSchema-bct1OuH5.mjs";import{LAZY_FUNCTION_DIRECTORY as Yn,emitFunctions as wa,emitLazyFunctionModules as Ia}from"./emitFunctions-D7mopPiT.mjs";const Ca=(e,t=!1)=>{if(e.length===0)return"";const s=fo(t),n=e.map(c=>{if(co(c.exportName,"live stream export name"),!lo.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{uo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map($=>`\${encodeURIComponent(key.${$})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
|
|
2
2
|
__lunoraLive: ${m},
|
|
3
3
|
topic: \`${u.name}:${v}\`,
|
|
4
4
|
}),`});return` ${c.exportName}: {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{Node as s,SyntaxKind as w}from"ts-morph";import{d as k}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as g,bindingKeyName as C,listLunoraSourceFiles as I,lunoraRelativePath as R}from"./isTestPath-C3QumE88.mjs";import{e as F,i as _}from"./attribution-CG8-kUcl.mjs";import{u as E,p as V,c as A,r as z}from"./unwrap-handler-return-CGdJGvGh.mjs";import{b as v,s as $,c as j}from"./classify-procedure-call-BkaeM9Ej.mjs";import{r as N,p as O,a as D}from"./parse-validator-iVTounLK.mjs";import{s as M}from"./dispatch-namespace-DwTjD7BU.mjs";const W=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const e=g(i,"handler");if(!e||!s.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":E(r)},H=t=>{const i=t.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":E(i)},B=t=>{let i={};for(const e of v(t)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],o=r!==void 0&&s.isExpression(r)?N(r):void 0;o!==void 0&&(i={...O(o),...i})}return i},K=t=>{const i=v(t).find(r=>r.name==="output");if(!i)return;const e=i.call.getArguments()[0];return e&&s.isExpression(e)?V(i.call,()=>D(e)):void 0},x=(t,i)=>{const e=g(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},P=(t,i)=>{const e=g(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},U=t=>{const i=g(t,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const e=i.getInitializer();if(e===void 0||!s.isObjectLiteralExpression(e))return;const r=x(e,"scope"),o=P(e,"maxAge"),n=P(e,"staleWhileRevalidate"),a=x(e,"tag"),l=x(e,"vary"),c={...o===void 0?{}:{maxAge:o},...r==="private"||r==="public"?{scope:r}:{},...n===void 0?{}:{staleWhileRevalidate:n},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},q=t=>{if(t===void 0||!s.isObjectLiteralExpression(t))return{};const i=U(t),e=g(t,"rest");return e!==void 0&&s.isPropertyAssignment(e)?{...i===void 0?{}:{cache:i},rest:e.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},J=t=>{const i=v(t).find(e=>e.name==="expose");return i?q(i.call.getArguments()[0]):void 0},X=t=>{const i=v(t).find(n=>n.name==="x402");if(!i)return;const e=i.call.getArguments()[0];if(e===void 0||!s.isObjectLiteralExpression(e))return{};const r=g(e,"price");if(r===void 0||!s.isPropertyAssignment(r))return{};const o=r.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},G=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const e=g(i,"args");if(!e||!s.isPropertyAssignment(e))return{};const r=e.getInitializer(),o=r===void 0?void 0:N(r);return o===void 0?{}:O(o)},p=(t,i)=>{throw new d("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${t.getSourceFile().getFilePath()}:${String(t.getStartLineNumber())}`)},b=(t,i,e)=>{if(!t||!s.isObjectLiteralExpression(t))return p(i,"metadata objects");const r=new Set;for(const o of t.getProperties()){if(!s.isPropertyAssignment(o))return p(o,"metadata fields without spreads, getters, or shorthand");const n=o.getNameNode(),a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(!s.isIdentifier(n)&&!s.isStringLiteral(n)||!e.includes(a)||r.has(a))return p(o,"supported, unique metadata fields");r.add(a)}return t},m=(t,i)=>{const e=t.getProperty(i);return e&&s.isPropertyAssignment(e)?e.getInitializer():void 0},Q=t=>{const i=b(t,t,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),e={};for(const n of["maxAge","staleWhileRevalidate"]){const a=m(i,n);if(!(a===void 0&&n!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(t,`cache.${n}`);e[n]=a.getLiteralValue()}}const r=m(i,"scope");if(!r||!s.isStringLiteral(r)||!["private","public"].includes(r.getLiteralValue()))return p(t,"cache.scope");e.scope=r.getLiteralValue();for(const n of["tag","vary"]){const a=m(i,n);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${n}`);e[n]=a.getLiteralValue()}}const o=m(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");e.credentialHeaders=o.getElements().map(n=>s.isStringLiteral(n)?n.getLiteralValue():p(n,"cache.credentialHeaders string entries"))}return e},Y=t=>{const i=b(t.getArguments()[0],t,["rest","cache"]),e=m(i,"rest"),r=m(i,"cache");return e!==void 0&&!s.isTrueLiteral(e)&&!s.isFalseLiteral(e)?p(e,".expose({ rest })"):{...e?{rest:s.isTrueLiteral(e)}:{},...r?{cache:Q(r)}:{}}},Z=t=>{const i=b(t.getArguments()[0],t,["price"]),e=m(i,"price");return!e||!s.isStringLiteral(e)&&!s.isNumericLiteral(e)?p(t,"`.x402({ price })` value"):{price:e.getLiteralValue()}},ee=t=>{const{factory:i,steps:e}=$(t);if(!i)return p(t,"metadata from a resolvable Lunora factory root");const r={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:o,name:n}of e){if(!["expose","input","meta","output","use","x402"].includes(n))return p(o,`known builder modifiers, got .${n}()`);n==="expose"&&r.expose===void 0&&(r.expose=Y(o)),n==="x402"&&r.x402===void 0&&(r.x402=Z(o))}return r},te=8,h=(t,i=0)=>{if(i>te)return;if(s.isCallExpression(t))return t;if(s.isParenthesizedExpression(t)||s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isNonNullExpression(t))return h(t.getExpression(),i+1);if(!s.isIdentifier(t)&&!s.isPropertyAccessExpression(t))return;const e=t.getSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0},L=(t,i)=>{if(s.isVariableDeclaration(t)||s.isPropertyAssignment(t)){const e=t.getInitializer();return e?h(e,i):void 0}if(s.isShorthandPropertyAssignment(t)){const e=t.getValueSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0}if(s.isBindingElement(t)){const e=C(t),n=t.getFirstAncestorByKind(w.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return n?L(n,i+1):void 0}},ie=(t,i=()=>!0)=>{const e=t.getNameNode();if(s.isObjectBindingPattern(e)){const n=[];for(const a of e.getElements().filter(l=>i(l.getName()))){const l=h(a.getNameNode());l&&n.push([a.getName(),l])}return n}if(!i(t.getName()))return[];const r=t.getInitializer(),o=r&&(s.isCallExpression(r)?r:h(r));return o?[[t.getName(),o]]:[]},re=t=>{const i=t.getArguments()[0],e=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return r.getLiteralValue()},ne=t=>t.startsWith("/")&&new URL(t,"https://lunora.invalid").pathname===t&&t!=="/_lunora"&&!t.startsWith("/_lunora/"),se=t=>{const i=t.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new d("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const e=i.getProperty("path"),r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=r.getLiteralValue();if(!ne(o))throw new d("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.getNameNode())))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(l),path:o}},oe=(t,i,e,r)=>{const o=r?ee(i):void 0,n=r?o?.expose:J(i),a=r?o?.x402:X(i),l=A(()=>K(i)),c=A(()=>H(t)),u=k({kind:e.kind,output:l.value});return z(u?l.erased:c.erased),{args:B(i),...n?{expose:n}:{},...a?{x402:a}:{},...e.adminOnly?{adminOnly:!0}:{},kind:e.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:o?.visibility==="internal"||e.visibility==="internal"?"internal":"public"}},ae=(t,i)=>{const e=j(t,i);if(!e)return;if(e.channel)return{args:{},channel:{kind:e.channel,name:re(t)},kind:e.kind,returnType:"void",visibility:e.visibility};const{receiver:r}=e;return r?oe(t,r,e,i):e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",...e.lifecycle==="socket"?{socket:{...se(t),origin:`${t.getSourceFile().getFilePath()}@${String(t.getStart())}`}}:{},visibility:e.visibility}:{args:G(t),kind:e.kind,returnType:W(t),visibility:e.visibility}},S=t=>{const i=t?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},ce=t=>S(t.getFirstAncestor(i=>s.isVariableStatement(i))),le=(t,i)=>S(t.getVariableStatements().find(e=>e.isExported()&&e.getDeclarations().some(r=>r.getName()===i))),T=(t,i,e,r,o)=>{const n=ae(t,r);if(!n)return;const a=o??ce(t);return{args:n.args,...a?{description:a}:{},exportName:i,filePath:e,kind:n.kind,returnType:n.returnType,...n.output?{output:n.output}:{},visibility:n.visibility,...n.adminOnly?{adminOnly:!0}:{},...n.expose?{expose:n.expose}:{},...n.x402?{x402:n.x402}:{},...n.lifecycle?{lifecycle:n.lifecycle}:{},...n.channel?{channel:n.channel}:{},...n.socket?{socket:n.socket}:{}}},ue=(t,i,e)=>{const r=[];for(const o of t.getExportAssignments()){if(o.isExportEquals())continue;const n=h(o.getExpression()),a=n?T(n,"default",i,e):void 0;n&&a&&r.push({call:n,entry:a})}return r},pe=(t,i,e)=>{const r=F(t),o=new Map,n=(c,u)=>{if(c?.channel?.kind!=="room")return;const f=o.get(c.channel.name);if(f!==void 0&&f!==u)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);o.set(c.channel.name,u)},a=t.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>ie(c,u=>r.has(u))).flatMap(([c,u])=>(r.get(c)??[]).filter(f=>_(f)).flatMap(f=>{const y=T(u,f,i,e,le(t,f));return n(y,u),y?[y]:[]})),l=new Set(a.map(c=>c.exportName));for(const{call:c,entry:u}of ue(t,i,e))l.has(u.exportName)||(n(u,c),a.push(u));return a},de=t=>{const i=new Map;for(const e of t){if(e.channel?.kind!=="room")continue;const r=i.get(e.channel.name);if(r!==void 0&&r.file!==e.filePath)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${e.channel.name}": defined in ${r.origin} and ${e.filePath}:${e.exportName}. Room names must be unique across the project.`);r===void 0&&i.set(e.channel.name,{file:e.filePath,origin:`${e.filePath}:${e.exportName}`})}},fe=t=>{const i=new Map;for(const e of t){const r=M(e.filePath),o=i.get(r);if(o&&o!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${e.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,e.filePath],status:500});i.set(r,e.filePath)}},Pe=(t,i,e={})=>{const r=I(i),o=[];for(const n of r){const a=t.getSourceFile(n)??t.addSourceFileAtPath(n),l=R(i,n);o.push(...pe(a,l,e.lazyFunctions===!0))}return o.sort((n,a)=>`${n.filePath}:${n.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),fe(o),de(o),o};export{Pe as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-6Xk0XLNG.mjs";import"./shard-runtime-ByYXjCKY.mjs";import"./shared-8vTRkL2-.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
const h=t=>t.methods.filter(e=>e["x-lunora-function-kind"]!=="stream"),b=/[^a-zA-Z0-9]+/gu,j=/([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(""),I=t=>t.replaceAll(j,"$1_$2").replaceAll(b,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),E=t=>t==="query"?"query":t==="action"?"action":"mutation",l=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>l(o,e+1));const n=t;if(n.format==="int64"&&(n.type===void 0||n.type==="string")||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(o=>l(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>l(n[o],e+1))},x=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),C=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),N=["$","{","'","$","'","}"].join(""),z=t=>C(t).split("$").join(N),H=(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 n=t;return n.type==="null"||Array.isArray(n.type)&&n.type.includes("null")?!0:["anyOf","oneOf"].some(r=>{const o=n[r];return Array.isArray(o)&&o.some(s=>A(s,e+1))})},P=(t,e,n)=>e.length===0?n===0?[]:[t]:e.map(r=>({properties:{...t.properties,...r.properties},required:new Set([...t.required,...r.required])})),k=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const n=t.required;return[{properties:e,required:new Set(Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}]},m=(t,e,n)=>{const r=t[e];return Array.isArray(r)?r.flatMap(o=>w(o,n+1)):[]},w=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[...k(n),...m(n,"allOf",e)],o={properties:Object.assign({},...r.map(a=>a.properties)),required:new Set(r.flatMap(a=>[...a.required]))},s=[...m(n,"anyOf",e),...m(n,"oneOf",e)];return P(o,s,r.length)},$=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[n];for(const o of["anyOf","oneOf","allOf"]){const s=n[o];if(Array.isArray(s))for(const a of s)r.push(...$(a,e+1))}return r},y=(t,e,n,r=0)=>{if(r>f||t===null||typeof t!="object")return;const o=w(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,c)=>a.localeCompare(c));for(const a of s){const c=[...e,a],u=o.every(i=>i.required.has(a)),g=o.map(i=>i.properties[a]).filter(i=>i!==void 0);u?g.some(i=>A(i))&&n.nullable.push(c):n.optional.push(c);for(const i of g)y(i,c,n,r+1)}for(const a of $(t))for(const c of["additionalProperties","items"]){const u=a[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],n,r+1)}},q=(t,e)=>t.join("\0").localeCompare(e.join("\0")),L=t=>{const e={nullable:[],optional:[]};y(t,[],e);const n=r=>[...new Map(r.map(o=>[o.join("\0"),o])).values()].toSorted(q);return{nullable:n(e.nullable),optional:n(e.optional)}},S=t=>{const[e="",n=""]=t.name.split(":"),r=`${p(e)}${p(n)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:L(o),argsType:d(o)&&!l(o)?`${r}Args`:void 0,takesArgs:d(o),functionName:n,functionPath:t.name,namespace:e,resultType:d(s)&&!l(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:E(t["x-lunora-function-kind"])}},U=t=>{const e=new Map;for(const n of h(t)){const r=S(n),o=e.get(r.namespace);o===void 0?e.set(r.namespace,[r]):o.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:n}))},W=t=>h(t).flatMap(e=>{const n=S(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),D=/^[A-Za-z][A-Za-z0-9]*$/u,M=t=>D.test(t),_=t=>{const e=new Map;for(const n of t.methods){const r=p(n.functionName);if(!M(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const o=n.verb==="query"?[r,`Subscribe${r}`,`Watch${r}`]:[r];for(const s of o){const a=e.get(s);if(a!==void 0){const c=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${n.functionPath}" both generate "${s}"${c} — rename one so the generated methods stay distinct.`)}e.set(s,n.functionPath)}}},Z=t=>{const e=new Map;for(const n of t){const r=p(n.name);if(!M(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const o=e.get(r);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),_(n)}},F=(t,e,n)=>{for(const r of t){const o=new Map;for(const s of r.methods)for(const a of n(s)){const c=o.get(a);if(c!==void 0&&c!==s.functionPath)throw new Error(`sdk: functions "${c}" and "${s.functionPath}" both generate the ${e} member "${a}" — rename one so the generated methods stay distinct.`);o.set(a,s.functionPath)}}},v=t=>t.flatMap(e=>e.methods),G=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],R=/^\s*(?:#|\/\/|\/\*|\*)/u,O=t=>t.split(`
|
|
3
|
+
`).filter(e=>!R.test(e)).join(`
|
|
4
|
+
`),T=(t,e)=>new RegExp(String.raw`\b${e}\b`,"u").test(t),B=(t,e)=>{const n=O(e),r=o=>o!==void 0&&T(n,o)?o:void 0;return t.map(o=>({methods:o.methods.map(s=>({...s,argsType:r(s.argsType),resultType:r(s.resultType)})),name:o.name}))},V=t=>h(t).filter(e=>l(e.params?.[0]?.schema)||l(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),K=(t,e)=>{const n=O(e);return[...new Set(v(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!T(n,r)))].toSorted((r,o)=>r.localeCompare(o))},X=t=>[...new Set(v(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{v as allMethods,H as argsChoice,F as assertDistinctMembers,Z as assertGeneratable,x as commentText,G as generatedHeaderLines,l as hasUnrepresentableWireType,d as isTypedSchema,z as kotlinLiteral,W as modelSources,L as nullPathsOf,S as parseMethod,U as parseSpec,X as referencedModels,C as stringLiteral,p as toPascalCase,I as toSnakeCase,K as undeclaredModels,V as unrepresentableFunctions,E as verbForKind,B as withDeclaredModels};
|
|
@@ -609,16 +609,16 @@ const dispatchRun = async (
|
|
|
609
609
|
callerKind?: "stream" | FunctionKind,
|
|
610
610
|
runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
|
|
611
611
|
): Promise<unknown> => {
|
|
612
|
-
// A query
|
|
613
|
-
// shape, built once), so the
|
|
614
|
-
// and a cast walks straight past it,
|
|
615
|
-
// execute many times per write. Checked
|
|
616
|
-
// lookup, so \`ctx.runMutation\` from a
|
|
617
|
-
// aimed at.
|
|
618
|
-
if (callerKind === "query" && expected !== "query") {
|
|
612
|
+
// A query and a stream are read-only: their declared ctx is the query ctx. The
|
|
613
|
+
// ctx object installs \`run*\` on every kind (one shape, built once), so the
|
|
614
|
+
// TYPE is all that stops them writing — and a cast walks straight past it,
|
|
615
|
+
// inside a subscription re-run that can execute many times per write. Checked
|
|
616
|
+
// on the CALLER, before the registry lookup, so \`ctx.runMutation\` from a
|
|
617
|
+
// query or stream fails identically whatever it aimed at.
|
|
618
|
+
if ((callerKind === "query" || callerKind === "stream") && expected !== "query") {
|
|
619
619
|
throw new LunoraError(
|
|
620
620
|
"RUN_KIND_FORBIDDEN",
|
|
621
|
-
\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a
|
|
621
|
+
\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a \${callerKind} may only compose other queries (tried to run "\${functionPath}")\`,
|
|
622
622
|
);
|
|
623
623
|
}
|
|
624
624
|
|
|
@@ -700,6 +700,13 @@ __PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath
|
|
|
700
700
|
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
701
701
|
}
|
|
702
702
|
|
|
703
|
+
// A stream yields chunks over its WebSocket procedure stream. Run here it
|
|
704
|
+
// would return an async iterator, which the wire encoder cannot carry as a
|
|
705
|
+
// single result, so refuse it before the handler runs.
|
|
706
|
+
if (registered.kind === "stream") {
|
|
707
|
+
throw new LunoraError("BAD_REQUEST", \`"\${functionPath}" is a stream: open it over the WebSocket, not RPC\`);
|
|
708
|
+
}
|
|
709
|
+
|
|
703
710
|
this.ensureServable();
|
|
704
711
|
|
|
705
712
|
// \`headroom\`, when the caller supplied one, is threaded straight
|
|
@@ -1087,7 +1094,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(f)}, (schema as
|
|
|
1087
1094
|
|
|
1088
1095
|
return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
|
|
1089
1096
|
}
|
|
1090
|
-
`:"",
|
|
1097
|
+
`:"",Kr=n=>({externalSourceOverride:n?`
|
|
1091
1098
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1092
1099
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1093
1100
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1240,7 +1247,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(f)}, (schema as
|
|
|
1240
1247
|
`:"",sourceClientCacheConst:n?`
|
|
1241
1248
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1242
1249
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1243
|
-
`:""}),
|
|
1250
|
+
`:""}),Hr=(n,t)=>{const e=t.length>0,r=n?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
|
|
1244
1251
|
`:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,h=n?`
|
|
1245
1252
|
const vectorSync = this.vectorSync(env);
|
|
1246
1253
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
@@ -1284,10 +1291,10 @@ ${o} const vectors = createContextVectors(lunora${f});
|
|
|
1284
1291
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1285
1292
|
});
|
|
1286
1293
|
}
|
|
1287
|
-
`:"",vectorsBuild:h,vectorsStub:r}},on=({advisories:n=[],advisorProcedures:t=[],agents:e=[],capabilities:a=new Set,containers:r=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasRooms:h=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:M=[],liveStreams:A=!1,maskMetadata:q,mutators:F=[],queues:R=[],rlsMetadata:U,schema:i,schemaSnapshot:v,shapes:E=[],storageRules:B,studioFeatures:I,services:C=[],topics:j=[],useUmbrella:W=!1,workflows:O=[]})=>{const l=Rr(W),
|
|
1294
|
+
`:"",vectorsBuild:h,vectorsStub:r}},on=({advisories:n=[],advisorProcedures:t=[],agents:e=[],capabilities:a=new Set,containers:r=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasRooms:h=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:M=[],liveStreams:A=!1,maskMetadata:q,mutators:F=[],queues:R=[],rlsMetadata:U,schema:i,schemaSnapshot:v,shapes:E=[],storageRules:B,studioFeatures:I,services:C=[],topics:j=[],useUmbrella:W=!1,workflows:O=[]})=>{const l=Rr(W),K=F.length>0,p=E.length>0,D=E.some(s=>yr(s.args).length>0),H=S||D,fe=v===void 0?"":Jt(v),ge=v===void 0?"":`
|
|
1288
1295
|
/** 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. */
|
|
1289
1296
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Yt(v))}, json: ${JSON.stringify(fe)} };
|
|
1290
|
-
`,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(a),L=tr(m,l.flags),V=rr(d,m,l.flags),G=gr(f),Q=nr(o),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(j,R),J=or(C,l.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(r,i.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(a.has("payments")),We=n,{advisoryRules:
|
|
1297
|
+
`,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(a),L=tr(m,l.flags),V=rr(d,m,l.flags),G=gr(f),Q=nr(o),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(j,R),J=or(C,l.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(r,i.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(a.has("payments")),We=n,{advisoryRules:Ke,advisoryRows:He}=Or(We),Ve=t,ne=U??{policies:[],roles:[]},Ge=q??{columns:[]},Qe=B??{rules:[]},Je=I??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ye,override:ze}=ur(O),{constant:Xe,override:Ze}=hr(R),b=w&&i.vectorIndexes.length>0,Y=new Set(i.tables.filter(s=>Ar(s)).map(s=>s.name)),ae=b&&i.vectorIndexes.some(s=>Y.has(s.table)),T=i.tables.some(s=>s.shardMode==="global"),z=pr(Y),X=i.tables.some(s=>zt(s)),se=i.tables.some(s=>Xt(s)),P=i.tables.some(s=>s.externalSource!==void 0),oe=i.tables.some(s=>s.memory===!0),Z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&X)throw new he("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ee=i.tables.length>0,et=Nr(i),tt=Mr(i),rt=Br(i),nt=$r(i),ie=qr(i),te=mr(b,O.length>0,R.length>0,m,Z);p&&te.push("WhereInput"),D&&te.push("SensitiveScope");const de=fr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=jr({hasMutators:K,hasSensitiveShapes:D,hasShapes:p,rlsData:ne}),_=A?M:[];for(const s of _)if(wr(s.exportName,"live stream export name"),!vr.test(s.filePath))throw new he("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ct=c?[]:_.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),lt=` protected override liveStreams() {
|
|
1291
1298
|
return { ${_.map(s=>`${kr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
|
|
1292
1299
|
}
|
|
1293
1300
|
`,ut=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
|
|
@@ -1312,11 +1319,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1312
1319
|
protected override liveStreams() {
|
|
1313
1320
|
return Object.fromEntries(this.loadedLiveStreams);
|
|
1314
1321
|
}
|
|
1315
|
-
`;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${te.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${Z?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],p?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];ee&&N.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...G.importLines,...Q.importLines,...Te,...Ce,...ve,...xe,...J.importLines,...$e,...Be,...
|
|
1322
|
+
`;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${te.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${Z?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],p?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];ee&&N.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...G.importLines,...Q.importLines,...Te,...Ce,...ve,...xe,...J.importLines,...$e,...Be,...H?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ct,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...K?["LUNORA_MUTATOR_PATHS"]:[],...h?["LUNORA_ROOMS"]:[],...g?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
|
|
1316
1323
|
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",pt=se?`
|
|
1317
1324
|
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",mt=X?`
|
|
1318
1325
|
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ft=P?`
|
|
1319
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=
|
|
1326
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=Hr(b,ae?i.vectorIndexes.filter(s=>Y.has(s.table)).map(s=>s.name):[]),Rt=`{
|
|
1320
1327
|
...this.ctxDbTuning(),
|
|
1321
1328
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1322
1329
|
broadcast: (delta) => {
|
|
@@ -1388,7 +1395,7 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1388
1395
|
`:"",_t=g?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
|
|
1389
1396
|
return LUNORA_SOCKETS[path];
|
|
1390
1397
|
}
|
|
1391
|
-
`:"",{externalSourceOverride:Et,sourceBootstrap:It,sourceClientCacheConst:Ct}=
|
|
1398
|
+
`:"",{externalSourceOverride:Et,sourceBootstrap:It,sourceClientCacheConst:Ct}=Kr(P),Lt=`
|
|
1392
1399
|
private shardInitDeferred = false;
|
|
1393
1400
|
private deferredShardInit?: Promise<void>;
|
|
1394
1401
|
|
|
@@ -1497,7 +1504,7 @@ ${It}${Pt} }
|
|
|
1497
1504
|
`:"",$t=ue===""?`
|
|
1498
1505
|
|
|
1499
1506
|
`:`${ue}
|
|
1500
|
-
`,Mt=
|
|
1507
|
+
`,Mt=H?`
|
|
1501
1508
|
protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
|
|
1502
1509
|
const registered = LUNORA_FUNCTIONS[functionPath];${D?`
|
|
1503
1510
|
const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
|
|
@@ -1518,8 +1525,8 @@ ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFaca
|
|
|
1518
1525
|
`)}
|
|
1519
1526
|
`:"",Wt=`${k.everyBuild}${L.build}${Q.build}
|
|
1520
1527
|
const secrets = createSecrets(env);
|
|
1521
|
-
`,
|
|
1522
|
-
secrets,`,
|
|
1528
|
+
`,Kt=`${k.everyFields}${L.contextField}${G.contextField}${Q.contextField}
|
|
1529
|
+
secrets,`,Ht=G.build,Vt=A?`
|
|
1523
1530
|
const live = {
|
|
1524
1531
|
publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
|
|
1525
1532
|
await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
|
|
@@ -1564,10 +1571,10 @@ const LUNORA_STORAGE_COLUMNS = ${u(nt,"Record<string, string[]>")};
|
|
|
1564
1571
|
const LUNORA_TTL_SWEEPS = ${Zt(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1565
1572
|
|
|
1566
1573
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1567
|
-
const LUNORA_ADVISORY_RULES = ${u(
|
|
1574
|
+
const LUNORA_ADVISORY_RULES = ${u(Ke,"Record<string, Partial<AdvisoryFinding>>")};
|
|
1568
1575
|
|
|
1569
1576
|
/** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
|
|
1570
|
-
const LUNORA_ADVISORY_ROWS = ${u(
|
|
1577
|
+
const LUNORA_ADVISORY_ROWS = ${u(He,"Array<Partial<AdvisoryFinding> & { name: string }>")};
|
|
1571
1578
|
|
|
1572
1579
|
const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
1573
1580
|
let cached: AdvisoryFinding[] | undefined;
|
|
@@ -1783,6 +1790,6 @@ ${Z?`
|
|
|
1783
1790
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1784
1791
|
}
|
|
1785
1792
|
`:""}${vt}
|
|
1786
|
-
${_r({hasSensitiveArgs:
|
|
1793
|
+
${_r({hasSensitiveArgs:H,lazyFunctions:c,actionOnlyFields:Gt,agentsBuild:Pe,agentsContextField:Ne,containersBuild:Oe,containersContextField:De,databaseOptions:Rt,everyContextBuild:Wt,everyContextField:Kt,facadeBlock:jt,globalDatabaseLine:Ot,notifyBuild:Ht,ormContextField:At,paymentsBuild:qe,paymentsContextField:Ue,queuesBuild:ye,queuesContextField:we,topicsBuild:Se,topicsContextField:Re,vectorsBuild:kt,vectorsContextField:xt,workflowsBuild:Ee,workflowsContextField:Ie,actionOnlyBuild:Qt})}
|
|
1787
1794
|
};
|
|
1788
1795
|
`};export{$r as b,on as e};
|
package/dist/sdk/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{modelSources as pe,assertDistinctMembers as T,toPascalCase as l,referencedModels as W,generatedHeaderLines as f,commentText as p,argsChoice as $,stringLiteral as m,kotlinLiteral as w,allMethods as x,toSnakeCase as E,parseSpec as Oe,assertGeneratable as Ne,withDeclaredModels as Ce,unrepresentableFunctions as Le,undeclaredModels as Re}from"../packem_shared/isTypedSchema-
|
|
1
|
+
import{modelSources as pe,assertDistinctMembers as T,toPascalCase as l,referencedModels as W,generatedHeaderLines as f,commentText as p,argsChoice as $,stringLiteral as m,kotlinLiteral as w,allMethods as x,toSnakeCase as E,parseSpec as Oe,assertGeneratable as Ne,withDeclaredModels as Ce,unrepresentableFunctions as Le,undeclaredModels as Re}from"../packem_shared/isTypedSchema-CDv3pJB6.mjs";import{isTypedSchema as St}from"../packem_shared/isTypedSchema-CDv3pJB6.mjs";const We=async(e,n)=>{if(n.quicktype===void 0)return"";const t=pe(e);if(t.length===0)return"";const{InputData:r,JSONSchemaInput:a,JSONSchemaStore:i,quicktype:o}=await import("quicktype-core");class s extends i{fetch(){return Promise.resolve(void 0)}}const d=new a(new s);for(const g of t)await d.addSource({name:g.name,schema:JSON.stringify(g.schema)});const c=new r;c.addInput(d);const{lines:u}=await o({inputData:c,lang:n.quicktype.lang,rendererOptions:n.quicktype.rendererOptions??{}});return u.join(`
|
|
2
2
|
`)},D=`${f("dart").map(e=>`// ${e}`).join(`
|
|
3
3
|
`)}
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.350",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,15 +50,15 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
54
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
55
|
-
"@lunora/container": "1.0.0-alpha.
|
|
53
|
+
"@lunora/advisor": "1.0.0-alpha.254",
|
|
54
|
+
"@lunora/agent": "1.0.0-alpha.244",
|
|
55
|
+
"@lunora/container": "1.0.0-alpha.90",
|
|
56
56
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
57
57
|
"@lunora/platform": "1.0.0-alpha.74",
|
|
58
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
59
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
60
|
-
"@lunora/values": "1.0.0-alpha.
|
|
61
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
58
|
+
"@lunora/queue": "1.0.0-alpha.125",
|
|
59
|
+
"@lunora/scheduler": "1.0.0-alpha.148",
|
|
60
|
+
"@lunora/values": "1.0.0-alpha.79",
|
|
61
|
+
"@lunora/workflow": "1.0.0-alpha.93",
|
|
62
62
|
"@visulima/fs": "6.0.29",
|
|
63
63
|
"jiti": "^2.7.0",
|
|
64
64
|
"quicktype-core": "^26.0.0",
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{m}from"./modules-l-Db0C4S.mjs";import{r as u}from"./json-data-Chfs2Cz5.mjs";import{validatorIrToJsonSchema as p,objectSchema as l,LUNORA_ERROR_CODES as d}from"./LUNORA_ERROR_CODES-CIAJQeKB.mjs";import{G as i}from"./shared-8vTRkL2-.mjs";import{s as R}from"./dispatch-namespace-DwTjD7BU.mjs";const h="1.3.2",g={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},f=(e,n)=>{const t=`${R(e.filePath)}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:d.map((r,a)=>({code:-32e3-a,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:l(e.args)}],result:{name:"result",schema:e.output?p(e.output):g},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},O=e=>{const n=e.version??"0.0.0",s=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream"),t=e.modules??[],r=s.map(o=>f(o,m(t,o.filePath))).toSorted((o,c)=>o.name.localeCompare(c.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:h}},E=e=>`${JSON.stringify(O(e),void 0,2)}
|
|
2
|
-
`,b=e=>`${i}export const openRpcSpec = ${u(e,"Record<string, unknown>")};
|
|
3
|
-
`;export{h as OPENRPC_VERSION,O as buildOpenRpcDocument,E as emitOpenRpc,b as emitOpenRpcModule};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{Node as s,SyntaxKind as T}from"ts-morph";import{d as w}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as m,bindingKeyName as k,listLunoraSourceFiles as C,lunoraRelativePath as I}from"./isTestPath-C3QumE88.mjs";import{e as R,i as F}from"./attribution-CG8-kUcl.mjs";import{u as E,p as _,c as A,r as z}from"./unwrap-handler-return-CGdJGvGh.mjs";import{b as v,s as V,c as $}from"./classify-procedure-call-BkaeM9Ej.mjs";import{r as N,p as O,a as j}from"./parse-validator-iVTounLK.mjs";import{s as M}from"./dispatch-namespace-DwTjD7BU.mjs";const D=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const e=m(i,"handler");if(!e||!s.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":E(r)},W=t=>{const i=t.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":E(i)},H=t=>{let i={};for(const e of v(t)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],n=r!==void 0&&s.isExpression(r)?N(r):void 0;n!==void 0&&(i={...O(n),...i})}return i},B=t=>{const i=v(t).find(r=>r.name==="output");if(!i)return;const e=i.call.getArguments()[0];return e&&s.isExpression(e)?_(i.call,()=>j(e)):void 0},L=(t,i)=>{const e=m(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},P=(t,i)=>{const e=m(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},K=t=>{const i=m(t,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const e=i.getInitializer();if(e===void 0||!s.isObjectLiteralExpression(e))return;const r=L(e,"scope"),n=P(e,"maxAge"),o=P(e,"staleWhileRevalidate"),a=L(e,"tag"),l=L(e,"vary"),c={...n===void 0?{}:{maxAge:n},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},U=t=>{if(t===void 0||!s.isObjectLiteralExpression(t))return{};const i=K(t),e=m(t,"rest");return e!==void 0&&s.isPropertyAssignment(e)?{...i===void 0?{}:{cache:i},rest:e.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},q=t=>{const i=v(t).find(e=>e.name==="expose");return i?U(i.call.getArguments()[0]):void 0},J=t=>{const i=v(t).find(o=>o.name==="x402");if(!i)return;const e=i.call.getArguments()[0];if(e===void 0||!s.isObjectLiteralExpression(e))return{};const r=m(e,"price");if(r===void 0||!s.isPropertyAssignment(r))return{};const n=r.getInitializer();return n===void 0?{}:s.isStringLiteral(n)?{price:n.getLiteralValue()}:s.isNumericLiteral(n)?{price:n.getLiteralValue()}:{}},X=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const e=m(i,"args");if(!e||!s.isPropertyAssignment(e))return{};const r=e.getInitializer(),n=r===void 0?void 0:N(r);return n===void 0?{}:O(n)},p=(t,i)=>{throw new d("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${t.getSourceFile().getFilePath()}:${String(t.getStartLineNumber())}`)},b=(t,i,e)=>{if(!t||!s.isObjectLiteralExpression(t))return p(i,"metadata objects");const r=new Set;for(const n of t.getProperties()){if(!s.isPropertyAssignment(n))return p(n,"metadata fields without spreads, getters, or shorthand");const o=n.getNameNode(),a=s.isStringLiteral(o)?o.getLiteralValue():o.getText();if(!s.isIdentifier(o)&&!s.isStringLiteral(o)||!e.includes(a)||r.has(a))return p(n,"supported, unique metadata fields");r.add(a)}return t},f=(t,i)=>{const e=t.getProperty(i);return e&&s.isPropertyAssignment(e)?e.getInitializer():void 0},G=t=>{const i=b(t,t,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),e={};for(const o of["maxAge","staleWhileRevalidate"]){const a=f(i,o);if(!(a===void 0&&o!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(t,`cache.${o}`);e[o]=a.getLiteralValue()}}const r=f(i,"scope");if(!r||!s.isStringLiteral(r)||!["private","public"].includes(r.getLiteralValue()))return p(t,"cache.scope");e.scope=r.getLiteralValue();for(const o of["tag","vary"]){const a=f(i,o);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${o}`);e[o]=a.getLiteralValue()}}const n=f(i,"credentialHeaders");if(n!==void 0){if(!s.isArrayLiteralExpression(n))return p(n,"cache.credentialHeaders");e.credentialHeaders=n.getElements().map(o=>s.isStringLiteral(o)?o.getLiteralValue():p(o,"cache.credentialHeaders string entries"))}return e},Q=t=>{const i=b(t.getArguments()[0],t,["rest","cache"]),e=f(i,"rest"),r=f(i,"cache");return e!==void 0&&!s.isTrueLiteral(e)&&!s.isFalseLiteral(e)?p(e,".expose({ rest })"):{...e?{rest:s.isTrueLiteral(e)}:{},...r?{cache:G(r)}:{}}},Y=t=>{const i=b(t.getArguments()[0],t,["price"]),e=f(i,"price");return!e||!s.isStringLiteral(e)&&!s.isNumericLiteral(e)?p(t,"`.x402({ price })` value"):{price:e.getLiteralValue()}},Z=t=>{const{factory:i,steps:e}=V(t);if(!i)return p(t,"metadata from a resolvable Lunora factory root");const r={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:n,name:o}of e){if(!["expose","input","meta","output","use","x402"].includes(o))return p(n,`known builder modifiers, got .${o}()`);o==="expose"&&r.expose===void 0&&(r.expose=Q(n)),o==="x402"&&r.x402===void 0&&(r.x402=Y(n))}return r},ee=8,h=(t,i=0)=>{if(i>ee)return;if(s.isCallExpression(t))return t;if(s.isParenthesizedExpression(t)||s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isNonNullExpression(t))return h(t.getExpression(),i+1);if(!s.isIdentifier(t)&&!s.isPropertyAccessExpression(t))return;const e=t.getSymbol()?.getValueDeclaration();return e?x(e,i+1):void 0},x=(t,i)=>{if(s.isVariableDeclaration(t)||s.isPropertyAssignment(t)){const e=t.getInitializer();return e?h(e,i):void 0}if(s.isShorthandPropertyAssignment(t)){const e=t.getValueSymbol()?.getValueDeclaration();return e?x(e,i+1):void 0}if(s.isBindingElement(t)){const e=k(t),o=t.getFirstAncestorByKind(T.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return o?x(o,i+1):void 0}},te=(t,i=()=>!0)=>{const e=t.getNameNode();if(s.isObjectBindingPattern(e)){const o=[];for(const a of e.getElements().filter(l=>i(l.getName()))){const l=h(a.getNameNode());l&&o.push([a.getName(),l])}return o}if(!i(t.getName()))return[];const r=t.getInitializer(),n=r&&(s.isCallExpression(r)?r:h(r));return n?[[t.getName(),n]]:[]},ie=t=>{const i=t.getArguments()[0],e=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return r.getLiteralValue()},re=t=>t.startsWith("/")&&new URL(t,"https://lunora.invalid").pathname===t&&t!=="/_lunora"&&!t.startsWith("/_lunora/"),ne=t=>{const i=t.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new d("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const e=i.getProperty("path"),r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const n=r.getLiteralValue();if(!re(n))throw new d("SOCKET_PATH_INVALID",`defineWebSocket path "${n}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.getNameNode())))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:n};const l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(l),path:n}},se=(t,i,e,r)=>{const n=r?Z(i):void 0,o=r?n?.expose:q(i),a=r?n?.x402:J(i),l=A(()=>B(i)),c=A(()=>W(t)),u=w({kind:e.kind,output:l.value});return z(u?l.erased:c.erased),{args:H(i),...o?{expose:o}:{},...a?{x402:a}:{},...e.adminOnly?{adminOnly:!0}:{},kind:e.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:n?.visibility==="internal"||e.visibility==="internal"?"internal":"public"}},oe=(t,i)=>{const e=$(t,i);if(!e)return;if(e.channel)return{args:{},channel:{kind:e.channel,name:ie(t)},kind:e.kind,returnType:"void",visibility:e.visibility};const{receiver:r}=e;return r?se(t,r,e,i):e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",...e.lifecycle==="socket"?{socket:{...ne(t),origin:`${t.getSourceFile().getFilePath()}@${String(t.getStart())}`}}:{},visibility:e.visibility}:{args:X(t),kind:e.kind,returnType:D(t),visibility:e.visibility}},S=(t,i,e,r)=>{const n=oe(t,r);if(n)return{args:n.args,exportName:i,filePath:e,kind:n.kind,returnType:n.returnType,...n.output?{output:n.output}:{},visibility:n.visibility,...n.adminOnly?{adminOnly:!0}:{},...n.expose?{expose:n.expose}:{},...n.x402?{x402:n.x402}:{},...n.lifecycle?{lifecycle:n.lifecycle}:{},...n.channel?{channel:n.channel}:{},...n.socket?{socket:n.socket}:{}}},ae=(t,i,e)=>{const r=[];for(const n of t.getExportAssignments()){if(n.isExportEquals())continue;const o=h(n.getExpression()),a=o?S(o,"default",i,e):void 0;o&&a&&r.push({call:o,entry:a})}return r},ce=(t,i,e)=>{const r=R(t),n=new Map,o=(c,u)=>{if(c?.channel?.kind!=="room")return;const g=n.get(c.channel.name);if(g!==void 0&&g!==u)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);n.set(c.channel.name,u)},a=t.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>te(c,u=>r.has(u))).flatMap(([c,u])=>(r.get(c)??[]).filter(g=>F(g)).flatMap(g=>{const y=S(u,g,i,e);return o(y,u),y?[y]:[]})),l=new Set(a.map(c=>c.exportName));for(const{call:c,entry:u}of ae(t,i,e))l.has(u.exportName)||(o(u,c),a.push(u));return a},le=t=>{const i=new Map;for(const e of t){if(e.channel?.kind!=="room")continue;const r=i.get(e.channel.name);if(r!==void 0&&r.file!==e.filePath)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${e.channel.name}": defined in ${r.origin} and ${e.filePath}:${e.exportName}. Room names must be unique across the project.`);r===void 0&&i.set(e.channel.name,{file:e.filePath,origin:`${e.filePath}:${e.exportName}`})}},ue=t=>{const i=new Map;for(const e of t){const r=M(e.filePath),n=i.get(r);if(n&&n!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${e.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[n,e.filePath],status:500});i.set(r,e.filePath)}},xe=(t,i,e={})=>{const r=C(i),n=[];for(const o of r){const a=t.getSourceFile(o)??t.addSourceFileAtPath(o),l=I(i,o);n.push(...ce(a,l,e.lazyFunctions===!0))}return n.sort((o,a)=>`${o.filePath}:${o.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),ue(n),le(n),n};export{xe as default};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
const g=/[^a-zA-Z0-9]+/gu,T=/([a-z0-9])([A-Z])/gu,p=t=>t.split(g).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),R=t=>t.replaceAll(T,"$1_$2").replaceAll(g,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),j=t=>t==="query"?"query":t==="action"?"action":"mutation",l=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>l(o,e+1));const n=t;if(n.format==="int64"&&(n.type===void 0||n.type==="string")||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(o=>l(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>l(n[o],e+1))},I=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),E=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
-
`,"\\n").replaceAll("\r","\\r"),C=["$","{","'","$","'","}"].join(""),x=t=>E(t).split("$").join(C),z=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,b=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const n=t;return n.type==="null"||Array.isArray(n.type)&&n.type.includes("null")?!0:["anyOf","oneOf"].some(r=>{const o=n[r];return Array.isArray(o)&&o.some(s=>b(s,e+1))})},N=(t,e,n)=>e.length===0?n===0?[]:[t]:e.map(r=>({properties:{...t.properties,...r.properties},required:new Set([...t.required,...r.required])})),P=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const n=t.required;return[{properties:e,required:new Set(Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}]},m=(t,e,n)=>{const r=t[e];return Array.isArray(r)?r.flatMap(o=>A(o,n+1)):[]},A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[...P(n),...m(n,"allOf",e)],o={properties:Object.assign({},...r.map(a=>a.properties)),required:new Set(r.flatMap(a=>[...a.required]))},s=[...m(n,"anyOf",e),...m(n,"oneOf",e)];return N(o,s,r.length)},w=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[n];for(const o of["anyOf","oneOf","allOf"]){const s=n[o];if(Array.isArray(s))for(const a of s)r.push(...w(a,e+1))}return r},y=(t,e,n,r=0)=>{if(r>f||t===null||typeof t!="object")return;const o=A(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,c)=>a.localeCompare(c));for(const a of s){const c=[...e,a],u=o.every(i=>i.required.has(a)),h=o.map(i=>i.properties[a]).filter(i=>i!==void 0);u?h.some(i=>b(i))&&n.nullable.push(c):n.optional.push(c);for(const i of h)y(i,c,n,r+1)}for(const a of w(t))for(const c of["additionalProperties","items"]){const u=a[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],n,r+1)}},k=(t,e)=>t.join("\0").localeCompare(e.join("\0")),q=t=>{const e={nullable:[],optional:[]};y(t,[],e);const n=r=>[...new Map(r.map(o=>[o.join("\0"),o])).values()].toSorted(k);return{nullable:n(e.nullable),optional:n(e.optional)}},$=t=>{const[e="",n=""]=t.name.split(":"),r=`${p(e)}${p(n)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:q(o),argsType:d(o)&&!l(o)?`${r}Args`:void 0,takesArgs:d(o),functionName:n,functionPath:t.name,namespace:e,resultType:d(s)&&!l(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:j(t["x-lunora-function-kind"])}},H=t=>{const e=new Map;for(const n of t.methods){const r=$(n),o=e.get(r.namespace);o===void 0?e.set(r.namespace,[r]):o.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:n}))},U=t=>t.methods.flatMap(e=>{const n=$(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),L=/^[A-Za-z][A-Za-z0-9]*$/u,S=t=>L.test(t),D=t=>{const e=new Map;for(const n of t.methods){const r=p(n.functionName);if(!S(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const o=n.verb==="query"?[r,`Subscribe${r}`,`Watch${r}`]:[r];for(const s of o){const a=e.get(s);if(a!==void 0){const c=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${n.functionPath}" both generate "${s}"${c} — rename one so the generated methods stay distinct.`)}e.set(s,n.functionPath)}}},W=t=>{const e=new Map;for(const n of t){const r=p(n.name);if(!S(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const o=e.get(r);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),D(n)}},Z=(t,e,n)=>{for(const r of t){const o=new Map;for(const s of r.methods)for(const a of n(s)){const c=o.get(a);if(c!==void 0&&c!==s.functionPath)throw new Error(`sdk: functions "${c}" and "${s.functionPath}" both generate the ${e} member "${a}" — rename one so the generated methods stay distinct.`);o.set(a,s.functionPath)}}},M=t=>t.flatMap(e=>e.methods),F=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],_=/^\s*(?:#|\/\/|\/\*|\*)/u,v=t=>t.split(`
|
|
3
|
-
`).filter(e=>!_.test(e)).join(`
|
|
4
|
-
`),O=(t,e)=>new RegExp(String.raw`\b${e}\b`,"u").test(t),G=(t,e)=>{const n=v(e),r=o=>o!==void 0&&O(n,o)?o:void 0;return t.map(o=>({methods:o.methods.map(s=>({...s,argsType:r(s.argsType),resultType:r(s.resultType)})),name:o.name}))},B=t=>t.methods.filter(e=>l(e.params?.[0]?.schema)||l(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),V=(t,e)=>{const n=v(e);return[...new Set(M(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!O(n,r)))].toSorted((r,o)=>r.localeCompare(o))},K=t=>[...new Set(M(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{M as allMethods,z as argsChoice,Z as assertDistinctMembers,W as assertGeneratable,I as commentText,F as generatedHeaderLines,l as hasUnrepresentableWireType,d as isTypedSchema,x as kotlinLiteral,U as modelSources,q as nullPathsOf,$ as parseMethod,H as parseSpec,K as referencedModels,E as stringLiteral,p as toPascalCase,R as toSnakeCase,V as undeclaredModels,B as unrepresentableFunctions,j as verbForKind,G as withDeclaredModels};
|