@lunora/codegen 1.0.0-alpha.42 → 1.0.0-alpha.421

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.
Files changed (130) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +4 -4
  3. package/dist/index.d.mts +4583 -2045
  4. package/dist/index.d.ts +4583 -2045
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs +1 -0
  7. package/dist/packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs +1 -0
  8. package/dist/packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs +25 -0
  9. package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
  10. package/dist/packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs +1 -0
  11. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  12. package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
  13. package/dist/packem_shared/ENV_FILENAME-DJ11PXN5.mjs +1 -0
  14. package/dist/packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs +1 -0
  15. package/dist/packem_shared/GENERATED_HEADER-DgrhC3Iv.mjs +1 -0
  16. package/dist/packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs +1 -0
  17. package/dist/packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs +1 -0
  18. package/dist/packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs +3 -0
  19. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
  20. package/dist/packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs +1 -0
  21. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CvXFQ6RH.mjs +57 -0
  22. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
  23. package/dist/packem_shared/SHAPES_FILENAME-BxRvP1ab.mjs +1 -0
  24. package/dist/packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs +17 -0
  25. package/dist/packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs +1 -0
  26. package/dist/packem_shared/attribution-Cwt30DDJ.mjs +1 -0
  27. package/dist/packem_shared/buildOpenApiDocument-DmV_PBFv.mjs +3 -0
  28. package/dist/packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs +1 -0
  29. package/dist/packem_shared/classify-procedure-call-BmEirzc_.mjs +1 -0
  30. package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
  31. package/dist/packem_shared/context-property-calls-BT1J7BqY.mjs +1 -0
  32. package/dist/packem_shared/context-root-BpDEhvNE.mjs +1 -0
  33. package/dist/packem_shared/createCodegenProject-dC6oJh5H.mjs +1 -0
  34. package/dist/packem_shared/database-calls-d-Sssc-3.mjs +1 -0
  35. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  36. package/dist/packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs +1 -0
  37. package/dist/packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs +1 -0
  38. package/dist/packem_shared/discoverCrons-bT8F5GyL.mjs +1 -0
  39. package/dist/packem_shared/discoverFunctions-BNqI2S6a.mjs +1 -0
  40. package/dist/packem_shared/discoverHttpRoutes-CesuhqW1.mjs +1 -0
  41. package/dist/packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs +1 -0
  42. package/dist/packem_shared/discoverInserts-DIarYU2P.mjs +1 -0
  43. package/dist/packem_shared/discoverMaskProcedures-jkRrWS86.mjs +1 -0
  44. package/dist/packem_shared/discoverMigrations-C9AlZYFi.mjs +1 -0
  45. package/dist/packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs +1 -0
  46. package/dist/packem_shared/discoverQueries-DLZHcDzB.mjs +1 -0
  47. package/dist/packem_shared/discoverR2sqlCalls-D_HWbbky.mjs +1 -0
  48. package/dist/packem_shared/discoverRlsMetadata-C0UkQkWd.mjs +1 -0
  49. package/dist/packem_shared/discoverRlsProcedures-BbSdCvmA.mjs +1 -0
  50. package/dist/packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs +1 -0
  51. package/dist/packem_shared/discoverSchema-BLTROO8Z.mjs +1 -0
  52. package/dist/packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs +1 -0
  53. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  54. package/dist/packem_shared/emitAgents-vWoT8-Yb.mjs +1 -0
  55. package/dist/packem_shared/emitApi-lwadq5G7.mjs +147 -0
  56. package/dist/packem_shared/emitApp-LFKtDRYu.mjs +1162 -0
  57. package/dist/packem_shared/emitCrons-CCRKs482.mjs +138 -0
  58. package/dist/packem_shared/emitDataModel-BvCZS4Yq.mjs +114 -0
  59. package/dist/packem_shared/emitDrizzleSchema-BzOChEYW.mjs +15 -0
  60. package/dist/packem_shared/emitFunctions-ppMX7E3X.mjs +528 -0
  61. package/dist/packem_shared/emitServer-CGRV_uIq.mjs +1 -0
  62. package/dist/packem_shared/emitShard-CDWgekIG.mjs +1 -0
  63. package/dist/packem_shared/exported-procedure-chains-CfH5jrzD.mjs +1 -0
  64. package/dist/packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs +1 -0
  65. package/dist/packem_shared/formatAdvisories-Bue5tbp6.mjs +2 -0
  66. package/dist/packem_shared/handler-reference-BkOkxxg8.mjs +1 -0
  67. package/dist/packem_shared/index-CfSmiylg.mjs +1 -0
  68. package/dist/packem_shared/index-DFMCX2vk.mjs +1 -0
  69. package/dist/packem_shared/ip-reads-D4nRZgML.mjs +1 -0
  70. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  71. package/dist/packem_shared/isTestPath-Uwb5a6Kq.mjs +1 -0
  72. package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
  73. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  74. package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
  75. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  76. package/dist/packem_shared/modules-DdOd-7Wp.mjs +1 -0
  77. package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
  78. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  79. package/dist/packem_shared/policies-Dn_tuTZd.mjs +1 -0
  80. package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
  81. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  82. package/dist/packem_shared/qualifiers-qqH8fRTo.mjs +1 -0
  83. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  84. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  85. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  86. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  87. package/dist/packem_shared/schemaFromIr-CByOxuZb.mjs +1 -0
  88. package/dist/packem_shared/server-Dfxmm5Zw.mjs +377 -0
  89. package/dist/packem_shared/shard-CWAD5mYy.mjs +1897 -0
  90. package/dist/packem_shared/shard-runtime-G5mZQjY0.mjs +351 -0
  91. package/dist/packem_shared/shared-Cn7dMQ_u.mjs +13 -0
  92. package/dist/packem_shared/unwrap-handler-return-DvbyiLjc.mjs +1 -0
  93. package/dist/sdk/index.d.mts +288 -0
  94. package/dist/sdk/index.d.ts +288 -0
  95. package/dist/sdk/index.mjs +394 -0
  96. package/package.json +22 -9
  97. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  98. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  99. package/dist/packem_shared/FLAGS_FILENAME-fEZtzWXi.mjs +0 -139
  100. package/dist/packem_shared/GENERATED_HEADER-D6RK1WF1.mjs +0 -3
  101. package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
  102. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  103. package/dist/packem_shared/OPENRPC_VERSION-CzhfvCIQ.mjs +0 -60
  104. package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
  105. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cl1EBMdR.mjs +0 -3438
  106. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  107. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  108. package/dist/packem_shared/WORKFLOWS_FILENAME-B2By8S4s.mjs +0 -152
  109. package/dist/packem_shared/buildOpenApiDocument-bg-NnLka.mjs +0 -183
  110. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  111. package/dist/packem_shared/discoverAuthApiCalls-WMx8L2FG.mjs +0 -62
  112. package/dist/packem_shared/discoverCrons-D-jrpm97.mjs +0 -256
  113. package/dist/packem_shared/discoverFunctions-CZ91aenA.mjs +0 -518
  114. package/dist/packem_shared/discoverHttpRoutes-DNZLDCmm.mjs +0 -131
  115. package/dist/packem_shared/discoverInserts-DFRJhmCv.mjs +0 -61
  116. package/dist/packem_shared/discoverMaskProcedures-B5iFnZ-X.mjs +0 -273
  117. package/dist/packem_shared/discoverMigrations-CdKtMlBc.mjs +0 -97
  118. package/dist/packem_shared/discoverNondeterministicCalls-C_PrQPkA.mjs +0 -122
  119. package/dist/packem_shared/discoverQueries-B8W9UPrt.mjs +0 -62
  120. package/dist/packem_shared/discoverR2sqlCalls-Bm7Rfnf4.mjs +0 -80
  121. package/dist/packem_shared/discoverRlsMetadata-B4GL4ZKm.mjs +0 -280
  122. package/dist/packem_shared/discoverSchema-DFWVgU5o.mjs +0 -874
  123. package/dist/packem_shared/discoverStorageRulesMetadata-nosjYcvN.mjs +0 -97
  124. package/dist/packem_shared/emit-31Yg1Ee5.mjs +0 -3474
  125. package/dist/packem_shared/emitApp-DCP7Pr6M.mjs +0 -668
  126. package/dist/packem_shared/formatAdvisories-DRhEiJUz.mjs +0 -114
  127. package/dist/packem_shared/parse-validator-BSJo1HGP.mjs +0 -144
  128. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  129. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  130. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,377 @@
1
+ import{CAPABILITIES as ze}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{existsSync as W,readdirSync as ue,readlinkSync as pe,lstatSync as Ke,statSync as Ue}from"node:fs";import{join as h,relative as y,dirname as l,sep as me,isAbsolute as Je,resolve as Ye,basename as Xe}from"node:path";import{ts as c,Project as Ze}from"ts-morph";import{G as ye,a as F,u as et,d as tt}from"./shared-Cn7dMQ_u.mjs";import{p as at}from"./platform-8oj7iXQy.mjs";const he=/(?:\.d)?\.([cm]?)tsx?$/u,rt=t=>t.replace(he,".d.$1ts"),fe=(t,o)=>{const a=y(t,o).split(me).join("/").replace(he,".$1js");return a.startsWith(".")?a:`./${a}`},be=t=>t.replaceAll("\\","/"),Z=(t,o,a)=>be(h(t,rt(y(o,a)))),ot=t=>fe(".",h("services",t.name,y(l(t.wranglerPath),t.main))),nt=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},x=t=>{const{ctimeMs:o,mtimeMs:a,size:e}=Ue(t);return`${String(a)}:${String(o)}:${String(e)}`},st=new Set([".git",".wrangler","dist","node_modules","target"]),ge=t=>ue(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${pe(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${x(a)}`,...ge(a)]:[]}),xe=t=>[`${t}:${x(t)}`,...ge(t)],Te=t=>{const o=h(t,"node_modules"),a=W(o)?xe(o):[],e=l(t);return e===t?a:[...a,...Te(e)]},it=(t,o)=>{const a=[];try{const e=n=>{for(const s of ue(n,{withFileTypes:!0})){const d=h(n,s.name);if(d!==o)if(s.isSymbolicLink())a.push(`${d}->${pe(d)}`);else if(s.isDirectory()){if(s.name==="node_modules")a.push(...xe(d));else if(!st.has(s.name)){if(!Ke(d).isDirectory())throw new Error(`${d} changed during the scan`);e(d)}}else a.push(`${d}:${x(d)}`)}};e(t),a.push(...Te(t))}catch{return}return[...new Set(a)].toSorted((e,n)=>e.localeCompare(n)).join(`
2
+ `)},dt=t=>Xe(l(t)).startsWith("@")?l(l(t)):l(t),de=(t,o)=>!y(o,t).startsWith("..")&&!t.split(me).includes("node_modules"),le=(t,o)=>{const a=[];let e=t;for(;e!==l(e)&&!W(h(e,"package.json"));)a.push(e),e=l(e);if(W(h(e,"package.json"))){for(const n of[...a,e,h(e,"package.json")])o.add(n);return e}},lt=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==l(e);)a.add(e),e=l(e);a.add(e)},ct=(t,o)=>{const a=new Set;t.some(e=>de(e,o))&&le(o,a);for(const e of t){if(de(e,o)){for(let s=l(e);s!==o&&s!==l(s);s=l(s))a.add(s);continue}const n=le(l(e),a);n===void 0?lt(l(e),o,a):a.add(dt(n))}return[...a].map(e=>[e,x(e)])},ve=new Map,ce=([t,o])=>{try{return x(t)===o}catch{return!1}},ut=(t,o,a)=>{const e=ve.get(t);return e?.optionsKey===o&&e.stamps.every(s=>ce(s))&&e.directories.every(s=>ce(s))&&a!==void 0&&e.tree===a?e.files:void 0},pt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,n])=>Math.floor(Number.parseFloat(n))<=a);o.tree!==void 0&&e&&ve.set(t,{...o,tree:o.tree})},mt=(t,o)=>({directories:ct(o,t),stamps:o.map(a=>[a,x(a)])}),wt=(t,o)=>{const a=l(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||Je(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const n=h(o,"services",t.name),s=c.findConfigFile(a,i=>c.sys.fileExists(i)),d=new Ze({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:n,rootDir:a},skipAddingFilesFromTsConfig:!0,...s===void 0?{}:{tsConfigFilePath:s}}),S=JSON.stringify([t.name,t.main,t.wranglerPath,o]),m=JSON.stringify(d.getCompilerOptions()),T=it(a,Ye(o)),v=ut(S,m,T);if(v!==void 0)return v;const w=Date.now();d.addSourceFileAtPath(t.main),d.resolveSourceFileDependencies();const P=d.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>W(i)),{directories:$,stamps:j}=mt(a,P),O={...d.getCompilerOptions(),preserveSymlinks:!0},u=new Map(d.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Z(n,a,i),i])),f={};for(const i of d.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const R=u.get(be(i.filePath));if(R===void 0)continue;const B=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const g of nt(B).toReversed()){const I=c.resolveModuleName(g.text,R,O,c.sys).resolvedModule?.resolvedFileName;if(I===void 0)continue;const k=Z(n,a,I),N=u.has(k)?k:I;b=`${b.slice(0,g.getStart(B))}${JSON.stringify(fe(l(i.filePath),N))}${b.slice(g.getEnd())}`}f[y(o,i.filePath)]=`${ye}${b}`}if(f[y(o,Z(n,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return pt(S,{files:f,optionsKey:m,directories:$,stamps:j,tree:T},w),f},yt=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const n of Object.values(e.shape)){const s=et(n);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&a.add(s.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,n)=>e.localeCompare(n))]},$t=({agents:t=[],authClaims:o=[],capabilities:a=new Set,containers:e=[],env:n,hasVectors:s=!0,hasFlags:d=!1,hasNotify:S=!1,identity:m,queues:T=[],schema:v,services:w=[],storageRuleBuckets:P=[],topics:$=[],useUmbrella:j=!1,workflows:O=[]}={})=>{const u=tt(j),f=yt(v??{tables:[]},P).map(r=>JSON.stringify(r)).join(" | "),i=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",R=[...new Set(e.map(r=>i(r)))].toSorted((r,p)=>r.localeCompare(p)),B=e.length>0?`import type { ${R.join(", ")} } from "@lunora/container";
3
+ `:"",b=e.length>0?`
4
+ readonly containers: {${e.map(r=>`
5
+ readonly ${r.exportName}: ${i(r)};`).join("")}
6
+ };`:"",g=[...a.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...e.map(r=>(F(r.bindingName,`container binding "${r.bindingName}"`),` /** Durable Object namespace for the \`${r.exportName}\` container. */
7
+ readonly ${r.bindingName}?: unknown;`)),...T.map(r=>(F(r.bindingName,`queue binding "${r.bindingName}"`),` /** Queue producer binding for the \`${r.exportName}\` queue. */
8
+ readonly ${r.bindingName}?: unknown;`))].join(`
9
+ `),I=`
10
+
11
+ /**
12
+ * This project's Cloudflare bindings, as far as codegen can discover them from
13
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
14
+ * conventional Workers AI binding. Bindings the config layer reconciles from
15
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
16
+ * visible here, so the open index signature keeps them reachable (cast at the
17
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
18
+ * under this signature too — Lunora can't type a third-party worker's RPC
19
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
20
+ */
21
+ export interface CloudflareBindings {
22
+ readonly [binding: string]: unknown;${g?`
23
+ ${g}`:""}
24
+ }
25
+
26
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
27
+ export type Env = CloudflareBindings;`,k=r=>ze.map(p=>p.tier!==void 0&&r.includes(p.tier)&&a.has(p.key)?p.serverCtxField:"").join(""),N=k(["every"]),we=k(["every","action"]),D=s&&(v?.vectorIndexes.length??0)>0,E=D?' | "vectors"':"",ee=D?`
28
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",$e=D?`
29
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",Ie=D?`import type { VectorSearch, VectorSearchReader } from "${u.server}";
30
+ import type { VectorIndexName } from "./dataModel.js";
31
+ `:"",Q=d?`
32
+ /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
33
+ readonly flags: import("${u.flags}").LunoraFlags;`:"",q=S?`
34
+ /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
35
+ readonly notify: import("@lunora/notify").LunoraNotify;
36
+ /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
37
+ readonly push: import("@lunora/notify").LunoraPush;`:"",M=O.length>0,ke=M?`import type { WorkflowHandle } from "@lunora/workflow";
38
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
39
+ `:"",Se=M?`
40
+
41
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
42
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
43
+ ? unknown extends Params
44
+ ? Record<string, unknown>
45
+ : NonNullable<Params>
46
+ : Record<string, unknown>;
47
+
48
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
49
+ export interface LunoraWorkflows {
50
+ ${O.map(r=>` get(name: ${JSON.stringify(r.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${r.exportName}>>;`).join(`
51
+ `)}
52
+ }`:"",te=M?' | "workflows"':"",ae=M?`
53
+ readonly workflows: LunoraWorkflows;`:"",L=at(T),_=L.length>0,V=$.length>0,G=[..._?["QueueProducer"]:[],...V?["TopicPublisher"]:[]],re=[...new Set([...L,...$].map(r=>r.filePath))].toSorted((r,p)=>+(p==="queues")-+(r==="queues")||r.localeCompare(p)),H=r=>r==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(re.indexOf(r))}`,Oe=G.length>0?`import type { ${G.join(", ")} } from "@lunora/queue";
54
+ ${re.map(r=>`import type * as ${H(r)} from "../${r}.js";
55
+ `).join("")}`:"",Re=G.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",Be=_?`
56
+
57
+ /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
58
+ export interface LunoraQueues {
59
+ ${L.map(r=>` readonly ${r.exportName}: QueueProducer<QueueBodyOf<typeof ${H(r.filePath)}.${r.exportName}>>;`).join(`
60
+ `)}
61
+ }`:"",Ne=V?`
62
+
63
+ /** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
64
+ export interface LunoraTopics {
65
+ ${$.map(r=>` readonly ${r.exportName}: TopicPublisher<QueueBodyOf<typeof ${H(r.filePath)}.${r.exportName}>>;`).join(`
66
+ `)}
67
+ }`:"",De=`${Re}${Be}${Ne}`,oe=_?`
68
+ readonly queues: LunoraQueues;`:"",ne=V?`
69
+ readonly topics: LunoraTopics;`:"",z=w.length>0,se=w.filter(r=>r.rpcEntrypoint!==void 0),Me=se.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Ce=z?`import type { ${Me} } from "${u.server}";
70
+ ${se.map(r=>`import type * as lunoraService_${r.name} from ${JSON.stringify(ot(r))};
71
+ `).join("")}`:"",Ae=z?`
72
+
73
+ /** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
74
+ export interface LunoraServices {
75
+ ${w.map(r=>{F(r.name,`service "${r.name}"`);const p=r.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${r.name}.${r.rpcEntrypoint}>`;return` readonly ${r.name}: ${p};`}).join(`
76
+ `)}
77
+ }`:"",Fe=z?`
78
+ readonly services: LunoraServices;`:"",K=t.length>0,We=K?`import type { AgentHandle } from "@lunora/agent/core";
79
+ `:"",Pe=K?`
80
+
81
+ /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
82
+ export interface LunoraAgents {
83
+ ${t.map(r=>(F(r.exportName,`agent export "${r.exportName}"`),` readonly ${r.exportName}: AgentHandle;`)).join(`
84
+ `)}
85
+ }`:"",ie=K?`
86
+ readonly agents: LunoraAgents;`:"",C=m!==void 0||o.length>0,je=m?`import type { InferIdentity } from "${u.server}";
87
+ import type * as lunoraIdentityContract from "../identity.js";
88
+ `:"",Ee=m===void 0&&o.length>0?`import type { SessionIdentity } from "@lunora/auth";
89
+ `:"",Qe=je+Ee,qe=o.length===0?"":`
90
+
91
+ /** App-declared user columns the session forwards as claims (\`user.additionalFields\` of \`.auth()\`). Optional: a user whose column is unset never carries it. */
92
+ export type AuthClaims = {
93
+ ${o.map(r=>` ${r.name}?: ${r.type};`).join(`
94
+ `)}
95
+ };`;let A;m===void 0?A="export type Identity = SessionIdentity & AuthClaims & Record<string, unknown>;":o.length===0?A=`export type Identity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;`:A=`type DeclaredIdentity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;
96
+ export type Identity = DeclaredIdentity & Omit<AuthClaims, keyof DeclaredIdentity>;`;const Le=o.length===0?"/** This app's declared identity claim contract (\\`defineIdentity\\` in \\`lunora/identity.ts\\`) — the typed shape of \\`ctx.auth.getIdentity()\\`, the RLS policy \\`ctx.auth.identity\\`, and the \\`authorizeShard\\`/\\`authorizeFanOut\\` identity argument. */":"/** This app's identity: the declared claim contract (\\`defineIdentity\\` in \\`lunora/identity.ts\\`) and the user-column claims, the typed shape of \\`ctx.auth.getIdentity()\\`, the RLS policy \\`ctx.auth.identity\\`, and the \\`authorizeShard\\`/\\`authorizeFanOut\\` identity argument. */",_e=C?`${qe}
97
+
98
+ ${Le}
99
+ ${A}
100
+
101
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} instead of the untyped claim bag. */
102
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",U=C?' | "auth"':"",J=C?`
103
+ readonly auth: NarrowedAuth;`:"",Ve=C?", Identity":"",Ge=n?`import type * as lunoraEnvContract from "../env.js";
104
+ `:"",He=n?`
105
+
106
+ /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
107
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",Y=n?' | "env"':"",X=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${ye}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${u.server}";
108
+ import type {
109
+ ActionBuilder,
110
+ ActionCtx as ActionCtxBase,
111
+ ColumnValidator,
112
+ DatabaseReader,
113
+ DatabaseWriter,
114
+ EmptyArgs,
115
+ InternalActionBuilder,
116
+ InternalMutationBuilder,
117
+ InternalQueryBuilder,
118
+ MutationBuilder,
119
+ MutationCtx as MutationCtxBase,
120
+ MutationStorage,
121
+ MutatorDefinition,
122
+ QueryBuilder,
123
+ QueryCtx as QueryCtxBase,
124
+ ReadOnlyStorage,
125
+ RegisteredMutator,
126
+ Storage as StorageBase,
127
+ TableReader,
128
+ Validator,
129
+ } from "${u.server}";
130
+
131
+ import type {
132
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
133
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
134
+ LoadWith as LoadWithOf,
135
+ TableReaderFacade as TableReaderFacadeOf,
136
+ TableWriterFacade as TableWriterFacadeOf,
137
+ WithArg as WithArgOf,
138
+ } from "${u.serverDataModel}";
139
+
140
+ export type {
141
+ AggregateOp,
142
+ GroupByEntry,
143
+ OrderBy,
144
+ QueryArgs,
145
+ QueryPage,
146
+ RankPage,
147
+ RankResult,
148
+ RestrictableQueryOptions,
149
+ RestrictableQueryOptionsOf,
150
+ SearchFilterBuilder,
151
+ SearchReader,
152
+ TableAggregateOptions,
153
+ TableAggregateOptionsOf,
154
+ TableGroupByOptions,
155
+ TableGroupByOptionsOf,
156
+ TableRankOptions,
157
+ TableRankPageOptions,
158
+ Where,
159
+ WhereOf,
160
+ WhereOperators,
161
+ } from "${u.serverDataModel}";
162
+
163
+ import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
164
+ ${Ie}${B}${ke}${Oe}${Ce}${We}${Qe}${Ge}
165
+ export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
166
+
167
+ /**
168
+ * The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
169
+ * over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
170
+ *
171
+ * They live here rather than in \`dataModel.ts\` because they are the half that
172
+ * needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
173
+ * package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
174
+ * types without installing a server dependency to do it.
175
+ */
176
+
177
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
178
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
179
+
180
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
181
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
182
+
183
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
184
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
185
+
186
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
187
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
188
+
189
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
190
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
191
+
192
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
193
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
194
+
195
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
196
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
197
+ values: (values: Insert<T>) => Promise<IdOfTable<T>>;
198
+ }
199
+
200
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
201
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
202
+ with: (values: Insert<T>) => Promise<void>;
203
+ }
204
+
205
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
206
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
207
+ set: (values: Partial<Insert<T>>) => Promise<void>;
208
+ }
209
+
210
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
211
+ export interface OrmReader {
212
+ query: DatabaseReaderFacade;
213
+ }
214
+
215
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
216
+ export interface OrmWriter extends OrmReader {
217
+ delete: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => Promise<void>;
218
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
219
+ replace: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => OrmReplaceBuilder<T>;
220
+ update: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => OrmUpdateBuilder<T>;
221
+ }
222
+
223
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
224
+ export type StorageBucketName = ${f};${I}${Se}${De}${Ae}${Pe}${_e}${He}
225
+
226
+ /**
227
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
228
+ * untyped against the schema; here \`db\` is widened to the generated per-table
229
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
230
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
231
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
232
+ */
233
+ /**
234
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
235
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
236
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
237
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
238
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
239
+ *
240
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
241
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
242
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
243
+ *
244
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
245
+ * error: each resolves to the table's declared names, or \`never\` when it
246
+ * declares none of that kind. Without them a renamed or dropped index left
247
+ * every call site typechecking, and the query either threw at runtime or
248
+ * degraded silently to a full table scan.
249
+ */
250
+ type TypedTableQuery = (<T extends TableName>(
251
+ table: T,
252
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
253
+ ((table: string) => TableReader);
254
+
255
+ /**
256
+ * The point read \`ctx.db.get(table, id)\`, bound to this schema: the table literal
257
+ * fixes \`T\`, so the id must be an \`Id<T>\` and the resolved document is typed
258
+ * \`Doc<T>\` (or \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
259
+ */
260
+ type TypedTableGet = <T extends TableName>(table: T, id: NoInfer<IdOfTable<T>>) => Promise<Doc<T> | null>;
261
+
262
+ /**
263
+ * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
264
+ * genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
265
+ * collapses to \`never\` so it fails to typecheck.
266
+ *
267
+ * The \`string extends T\` arm is what distinguishes "the caller passed a computed
268
+ * string" from "the caller passed a misspelled literal" — only the wide \`string\` type
269
+ * is a supertype of \`string\`.
270
+ */
271
+ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
272
+
273
+ /**
274
+ * The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
275
+ * table literal is a compile error rather than a call that hands back a confidently-
276
+ * branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
277
+ * {@link TypedTableGet}.
278
+ *
279
+ * Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
280
+ * overload resolution would fall through to it for a bad literal, silently restoring
281
+ * the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
282
+ * computed table name working — and keeps \`ctx.db\` structurally assignable to
283
+ * schema-agnostic consumers — without accepting an invalid literal.
284
+ */
285
+ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
286
+
287
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${E}${U}${Y}> {
288
+ readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
289
+ readonly orm: OrmReader;
290
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${$e}${N}${Q}${q}${X}${J}
291
+ }
292
+
293
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${E}${te}${U}${Y}> {
294
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
295
+ readonly orm: OrmWriter;
296
+ readonly storage: MutationStorage<StorageBucketName>;${ee}${N}${Q}${q}${X}${ae}${oe}${ne}${ie}${J}
297
+ }
298
+
299
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${E}${te}${U}${Y}> {
300
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
301
+ readonly orm: OrmWriter;
302
+ readonly storage: StorageBase<StorageBucketName>;${ee}${we}${b}${Q}${q}${Fe}${X}${ae}${oe}${ne}${ie}${J}
303
+ }
304
+
305
+ /**
306
+ * Procedure builders bound to this project's typed contexts. Chain
307
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
308
+ * masking (each middleware may refine \`ctx\`), then the terminal
309
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
310
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
311
+ */
312
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
313
+
314
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
315
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
316
+
317
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
318
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
319
+
320
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
321
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
322
+
323
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
324
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
325
+
326
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
327
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
328
+
329
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
330
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
331
+
332
+ /**
333
+ * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
334
+ * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
335
+ * \`${u.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
336
+ * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
337
+ * \`ctx.db.patch("nodes", id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
338
+ * no \`as unknown as\` cast. Runtime-identical to the package export; only the
339
+ * context type narrows, so discovery finds a mutator authored either way.
340
+ * @example
341
+ * export const setText = defineMutator({
342
+ * args: { id: v.id("nodes"), text: v.string() },
343
+ * server: async (ctx, args) => { await ctx.db.patch("nodes", args.id, { text: args.text }); },
344
+ * });
345
+ */
346
+ export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
347
+ definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
348
+ ) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
349
+
350
+ /**
351
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
352
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
353
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
354
+ * name and the \`when\` predicate type-checks against the table's columns **and**
355
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
356
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
357
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
358
+ * so the \`rls()\` chain discovers a policy authored either way the same.
359
+ */
360
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Ve}>();
361
+
362
+ /**
363
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
364
+ * table names — so the argument autocompletes and returns a precise
365
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
366
+ * difference is the tightened \`id\` type.
367
+ *
368
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
369
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
370
+ * file that defines the table names, so they aren't known yet there; pass the
371
+ * names as string literals and the generated \`Id<"table">\` types still catch a
372
+ * typo wherever the id is used.
373
+ */
374
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
375
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
376
+ };
377
+ `};export{wt as a,$t as e};