@lunora/codegen 1.0.0-alpha.32 → 1.0.0-alpha.321

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 (125) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +4230 -2183
  4. package/dist/index.d.ts +4230 -2183
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs +1 -0
  7. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  8. package/dist/packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs +1 -0
  9. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_TARGET-B0FkdiZq.mjs +1 -0
  11. package/dist/packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs +1 -0
  12. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
  13. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  14. package/dist/packem_shared/MUTATORS_FILENAME-Jkk8Zgkb.mjs +1 -0
  15. package/dist/packem_shared/NOTIFY_FILENAME-bAt7J3cs.mjs +1 -0
  16. package/dist/packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs +3 -0
  17. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  18. package/dist/packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs +1 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-B6NxV9VM.mjs +11 -0
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  21. package/dist/packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs +1 -0
  22. package/dist/packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs +18 -0
  23. package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
  24. package/dist/packem_shared/attribution-hVBriwzy.mjs +1 -0
  25. package/dist/packem_shared/buildOpenApiDocument-DFv-RYZU.mjs +3 -0
  26. package/dist/packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs +1 -0
  27. package/dist/packem_shared/chain-Cm6BMT8g.mjs +1 -0
  28. package/dist/packem_shared/classify-procedure-call-DVxdUhZt.mjs +1 -0
  29. package/dist/packem_shared/context-property-calls-Cn3upNgZ.mjs +1 -0
  30. package/dist/packem_shared/context-root-BdxINX-T.mjs +1 -0
  31. package/dist/packem_shared/createCodegenProject-V51_yBw3.mjs +1 -0
  32. package/dist/packem_shared/database-calls-BKozZUEW.mjs +1 -0
  33. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  34. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  35. package/dist/packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs +1 -0
  36. package/dist/packem_shared/discoverCrons-DBnCama4.mjs +1 -0
  37. package/dist/packem_shared/discoverFunctions-CZgLhsMn.mjs +1 -0
  38. package/dist/packem_shared/discoverHttpRoutes-WBAqBcfK.mjs +1 -0
  39. package/dist/packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs +1 -0
  40. package/dist/packem_shared/discoverInserts-BjxXCACZ.mjs +1 -0
  41. package/dist/packem_shared/discoverMaskProcedures-DE-8CDen.mjs +1 -0
  42. package/dist/packem_shared/discoverMigrations-C9mLIhGZ.mjs +1 -0
  43. package/dist/packem_shared/discoverNondeterministicCalls-DvhyKM-f.mjs +1 -0
  44. package/dist/packem_shared/discoverQueries-C8E7TeRT.mjs +1 -0
  45. package/dist/packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsMetadata-QRsWRQbM.mjs +1 -0
  47. package/dist/packem_shared/discoverRlsProcedures-Du7ITNTQ.mjs +1 -0
  48. package/dist/packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs +1 -0
  49. package/dist/packem_shared/discoverSchema-BtsX-CN9.mjs +1 -0
  50. package/dist/packem_shared/discoverStorageRulesMetadata-ClzKLdCV.mjs +1 -0
  51. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  52. package/dist/packem_shared/emitAgents-CR2_X_ov.mjs +1 -0
  53. package/dist/packem_shared/emitApi-CDgIPAG2.mjs +147 -0
  54. package/dist/packem_shared/emitApp-K6otnCNZ.mjs +986 -0
  55. package/dist/packem_shared/emitCrons-BQW2lviZ.mjs +96 -0
  56. package/dist/packem_shared/emitDataModel-BskFt9Wv.mjs +114 -0
  57. package/dist/packem_shared/emitDrizzleSchema-DitcRZ1a.mjs +15 -0
  58. package/dist/packem_shared/emitFunctions-CuZzKaU4.mjs +419 -0
  59. package/dist/packem_shared/emitServer-D1vA5_X1.mjs +1 -0
  60. package/dist/packem_shared/emitShard-C1aUZPCr.mjs +1 -0
  61. package/dist/packem_shared/exported-procedure-chains-BNBUkXui.mjs +1 -0
  62. package/dist/packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs +1 -0
  63. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  64. package/dist/packem_shared/handler-reference-vIeqkhV_.mjs +1 -0
  65. package/dist/packem_shared/index-JnqBWRYO.mjs +1 -0
  66. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  67. package/dist/packem_shared/isTestPath-B81lOULB.mjs +1 -0
  68. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  69. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  70. package/dist/packem_shared/loadProjectConfig-NO0dVJSl.mjs +1 -0
  71. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  72. package/dist/packem_shared/modules-CjOcuQnK.mjs +1 -0
  73. package/dist/packem_shared/parse-validator-IDBKIT7M.mjs +1 -0
  74. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  75. package/dist/packem_shared/project-config-file-BV7RR-l6.mjs +1 -0
  76. package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
  77. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  78. package/dist/packem_shared/readServiceBindings-DvqIThzd.mjs +1 -0
  79. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  80. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  81. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  82. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  83. package/dist/packem_shared/server-DAvi_bv_.mjs +368 -0
  84. package/dist/packem_shared/shard-CtYnaXAX.mjs +1601 -0
  85. package/dist/packem_shared/shard-runtime-BpoCV-aM.mjs +331 -0
  86. package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
  87. package/dist/packem_shared/unwrap-handler-return-CeaOifqX.mjs +1 -0
  88. package/dist/sdk/index.d.mts +288 -0
  89. package/dist/sdk/index.d.ts +288 -0
  90. package/dist/sdk/index.mjs +372 -0
  91. package/package.json +21 -8
  92. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  93. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  94. package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
  95. package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
  96. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  97. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  98. package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
  99. package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
  100. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-OBXQBJV0.mjs +0 -3520
  101. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  102. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  103. package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
  104. package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
  105. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  106. package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
  107. package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
  108. package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
  109. package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
  110. package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
  111. package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
  112. package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
  113. package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
  114. package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
  115. package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
  116. package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
  117. package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
  118. package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
  119. package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
  120. package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
  121. package/dist/packem_shared/formatAdvisories-C9wNBNvL.mjs +0 -113
  122. package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
  123. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  124. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  125. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1 @@
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CtYnaXAX.mjs";import"./shard-runtime-BpoCV-aM.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -0,0 +1 @@
1
+ import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-hVBriwzy.mjs";import{c as n}from"./classify-procedure-call-DVxdUhZt.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
@@ -0,0 +1 @@
1
+ import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-B81lOULB.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
@@ -0,0 +1,2 @@
1
+ import{runAdvisor as i}from"@lunora/advisor";const d=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],l=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},m=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:l(e),fields:Object.keys(e.shape),indexes:d(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>r.through!==void 0?{kind:"many",name:r.name,table:r.table,through:{...r.through}}:{field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table}),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),u=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),f=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:t,shapes:o,...a}=n;return{...a,argValidators:e,mutators:r===void 0?void 0:u(r),queries:s??[],schema:m(t),shapes:o===void 0?void 0:c(o)}},p=n=>i(f(n),{source:"static"}),v=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
2
+ `)};export{v as formatAdvisories,p as lintSchema,f as toAdvisorContext};
@@ -0,0 +1 @@
1
+ import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-B81lOULB.mjs";import{r as v,d as b}from"./attribution-hVBriwzy.mjs";const h=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:h(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=b(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
@@ -0,0 +1 @@
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B81lOULB.mjs";import{b as m,d as p}from"./attribution-hVBriwzy.mjs";import{t as d}from"./database-calls-BKozZUEW.mjs";import{w as g,c as h}from"./classify-procedure-call-DVxdUhZt.mjs";import{a as k}from"./project-config-file-BV7RR-l6.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
@@ -0,0 +1 @@
1
+ const e=l=>l.shardMode==="global"&&l.globalBackend!=="hyperdrive",o=l=>l.shardMode==="global"&&l.globalBackend==="hyperdrive";export{e as isD1GlobalTable,o as isHyperdriveGlobalTable};
@@ -0,0 +1 @@
1
+ import{existsSync as h,statSync as P,readdirSync as A,realpathSync as D,lstatSync as C}from"node:fs";import{dirname as f,join as g,relative as F,sep as w,resolve as k,extname as O,basename as j}from"node:path";import{findUpSync as z,FIND_UP_STOP as V,matcher as K}from"@visulima/fs";import{SyntaxKind as p,Node as i,VariableDeclarationKind as $}from"ts-morph";import{diagnosticAt as M}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{p as U,a as B,r as W}from"./project-config-file-BV7RR-l6.mjs";import{findProjectConfigFile as N}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const X=/\.ts$/u,d=(e,t)=>F(e,t).split(w).join("/").replace(X,""),G=new Set(["_generated","node_modules"]),_=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),L=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,Se=e=>{const t=e.split("/");return L.test(t.at(-1)??"")||t.slice(0,-1).some(s=>_.has(s))},E=(e,t,s)=>t?G.has(e)||!s&&_.has(e):!s&&L.test(e),v=new Map,m=()=>!1,H=e=>{const t=z(a=>N(a)??(h(g(a,"package.json"))||h(g(a,".git"))?V:void 0),{cwd:f(k(e))}),s=t===void 0?void 0:P(t,{throwIfNoEntry:!1});if(t===void 0||s===void 0)return m;const n=`${String(s.mtimeMs)}:${String(s.size)}`,r=v.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=W(f(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?K(o.exclude):m;return v.set(t,{isExcluded:c,key:n}),c},Y=(e,t,s)=>e==="schema.ts"&&t===s,q=e=>{try{return P(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},R=(e,t,s,n,r)=>{let o,c;try{o=A(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const a of o){const u=g(e,a),l=q(u);l===void 0||r(a,F(s,u).split(w).join("/"),l.isDirectory())||(l.isDirectory()?R(u,t,s,n,r):l.isFile()&&O(a)===".ts"&&!Y(a,e,s)&&t.push(u))}return t},T=(e,t={})=>{const s=t.includeSkipped??!1,n=s?m:H(e);return R(e,[],e,new Set,(r,o,c)=>E(r,c,s)||n(o))},Q=["src/server","src/index.ts","src/worker.ts"],J=new Set([".ts",".tsx"]),b=(e,t=[])=>{let s;try{s=C(e)}catch{return t}if(s.isFile())return J.has(O(e))&&!E(j(e),!1,!1)&&t.push(e),t;if(!s.isDirectory())return t;for(const n of A(e))E(n,!0,!1)||b(g(e,n),t);return t},Z=e=>{const t=f(e),s=T(e).map(o=>({displayPath:d(e,o),filePath:o})),n=new Set(s.map(o=>o.filePath)),r=N(t);for(const o of[...Q.flatMap(c=>b(g(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),s.push({displayPath:d(t,o),filePath:o}));return s},ee=e=>Array.isArray(e),I=(e,t,s,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const a=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of a.getDescendantsOfKind(s)){const l=n(u,o);ee(l)?r.push(...l):l!==void 0&&r.push(l)}}return r},te=e=>T(e).map(t=>({displayPath:d(e,t),filePath:t})),se=(e,t,s,n)=>I(e,te(t),s,n),he=(e,t,s)=>se(e,t,p.CallExpression,s),ve=(e,t,s)=>I(e,Z(t),p.CallExpression,s),ye=e=>U(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(s=>!i.isSpreadAssignment(s)&&B(s)===t),Pe=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:void 0}const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const n=S(s,"handler");if(!n||!i.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:void 0},Ae=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=S(e,t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},ie=e=>{const t=e?.getParent();return i.isVariableDeclaration(e)&&i.isVariableDeclarationList(t)&&t.getDeclarationKind()===$.Const},ne=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isParenthesizedExpression(s)||i.isAsExpression(s)||i.isSatisfiesExpression(s)||i.isTypeAssertion(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();return t},y=e=>{const t=ne(e),s=t.getParent();if(s===void 0)return!1;if(i.isBinaryExpression(s)){const r=s.getOperatorToken().getKind();return s.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(i.isPrefixUnaryExpression(s)||i.isPostfixUnaryExpression(s)){const r=s.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return i.isDeleteExpression(s)?!0:i.isForOfStatement(s)||i.isForInStatement(s)?s.getInitializer()===t:i.isPropertyAssignment(s)?s.getInitializer()===t&&y(s):(i.isShorthandPropertyAssignment(s)||i.isSpreadAssignment(s)||i.isSpreadElement(s)||i.isObjectLiteralExpression(s)||i.isArrayLiteralExpression(s))&&y(s)},re=e=>{const t=e?.getDeclarations().find(n=>i.isVariableDeclaration(n));if(!ie(t))return;const s=t.getParent().getParent();return i.isVariableStatement(s)&&i.isSourceFile(s.getParent())?t.getInitializer():void 0},oe=e=>re(e.getSymbol()),Fe=e=>{if(!e)return;if(i.isObjectLiteralExpression(e))return e;if(!i.isIdentifier(e))return;const t=oe(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},x=e=>{let t=e;for(;t&&(i.isAsExpression(t)||i.isSatisfiesExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t));)t=t.getExpression();return t},ce=(e,t)=>{let s=x(e);for(;i.isAwaitExpression(s)||i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s)||i.isCallExpression(s);){const n=i.isCallExpression(s)?t?.(s):void 0;if(n!==void 0)return{verdict:n};s=x(s.getExpression())}return{root:s}},we=e=>ce(e).root,Oe=e=>i.isArrowFunction(e)||i.isConstructorDeclaration(e)||i.isFunctionDeclaration(e)||i.isFunctionExpression(e)||i.isGetAccessorDeclaration(e)||i.isMethodDeclaration(e)||i.isSetAccessorDeclaration(e),Ne=(e,t)=>e?.compilerNode===t.compilerNode,_e=e=>{if(i.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=i.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return i.isElementAccessExpression(e)&&i.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Le=e=>{const t=e.getParent();return i.isReturnStatement(t)||i.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>i.isFunctionLikeDeclaration(n)||i.isArrowFunction(n)):void 0},Re=e=>{const t=x(e);return t&&i.isCallExpression(t)?t:void 0},Te=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const s=t.getExpression();if(!i.isIdentifier(s))return s;const n=s.getSymbol()?.getValueDeclaration();return n&&i.isVariableDeclaration(n)?n.getInitializer():s},be=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Ie=(e,t)=>{if(!i.isObjectLiteralExpression(e))return;const s=S(e,t);if(!s||!i.isPropertyAssignment(s))return;const n=s.getInitializer();return n&&i.isStringLiteral(n)?n.getLiteralText():void 0},ae=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&i.isObjectLiteralExpression(n)?n:void 0},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?ae(e):void 0},Ce=e=>(t,s,n)=>{if(i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw M(t,`${e} "${s}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},le=new Set(["api","internal"]),ke=new Set(["run","runAction","runMutation","runQuery"]),ue=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();return i.isIdentifier(s)&&le.has(s.getText())&&t.length>=2?t:void 0},je=e=>{const t=ue(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{ke as RUN_METHODS,X as TS_EXTENSION_RE,ye as bindingKeyName,we as chainRootOf,he as collectCallRows,se as collectNodeRows,ve as collectSecurityCallRows,Te as defaultExportExpression,S as findObjectProperty,je as functionKeyOf,ue as functionReferenceSegments,Pe as handlerOf,ie as isConstDeclaration,Oe as isFunctionLike,Ne as isSameNode,Se as isTestPath,y as isWriteTarget,be as limitNameOf,T as listLunoraSourceFiles,Z as listSecurityScanFiles,d as lunoraRelativePath,_e as memberAccessOf,De as objectLiteralFromCallbackBody,Fe as optionsObjectLiteral,ne as outermostValueWrapper,Ae as propertyInitializer,B as propertyKeyName,U as propertyNameText,Le as returningFunctionOf,Ce as stringPropertyFor,Ie as stringPropertyOf,re as symbolConstInitializer,x as unwrapExpression,Re as unwrapToCallExpression,ce as walkChain};
@@ -0,0 +1,4 @@
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};
@@ -0,0 +1 @@
1
+ const a=(r,s)=>`JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${s}`;export{a as r};
@@ -0,0 +1 @@
1
+ import{l as o,b as a,r as t}from"./project-config-file-BV7RR-l6.mjs";import{PROJECT_CONFIG_FILENAMES as i,findProjectConfigFile as l}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";export{i as PROJECT_CONFIG_FILENAMES,l as findProjectConfigFile,o as loadProjectConfig,a as readMergeDurableObjects,t as readProjectConfigLiterals};
@@ -0,0 +1 @@
1
+ const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{t as a,o as b,E as i};
@@ -0,0 +1 @@
1
+ import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-B81lOULB.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{Node as i,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as b}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as E}from"./project-config-file-BV7RR-l6.mjs";let f;const z=e=>{f=e},A=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),k=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},N=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),T=new Set(["strip"]),l=new Set,g=new Set,S=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&i.isShorthandPropertyAssignment(r)){const n=r.getValueSymbol();r=(n?.getAliasedSymbol()??n)?.getValueDeclaration()}if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},L=e=>{const t=e.getParent();return!i.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===h.Const},u=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return u(e.getExpression());if(i.isObjectLiteralExpression(e))return e;if(i.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),n=r!==void 0&&i.isPropertyAssignment(r)?r.getInitializer():void 0;return n===void 0?void 0:u(n)}if(!i.isIdentifier(e)||l.has(e))return;const t=S(e);if(!(t===void 0||!L(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},w="v",D=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===w},c=e=>{if(i.isIdentifier(e)&&!l.has(e)){const t=S(e);if(t!==void 0&&D(t)){l.add(e);try{return c(t)}finally{l.delete(e)}}}return i.isCallExpression(e)?$(e):{kind:"any",sourceText:e.getText()}},R=e=>{const t=u(e.getExpression());if(t===void 0||g.has(t))return{};g.add(t);try{return v(t)}finally{g.delete(t)}},V=e=>{throw b(e,`computed property name ${e.getText()} must be a string literal — codegen resolves object keys statically.`)},v=e=>{const t={};for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){Object.assign(t,R(r));continue}const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const s=n?r.getNameNode():r.getInitializer();if(!s)continue;const a=r.getNameNode(),o=E(a)??V(a);if(!A.test(o))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(o)}`);t[o]=c(s)}return t},d=(e,t)=>e&&i.isExpression(e)?c(e):t,x=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),O=e=>{const t=e&&f?f(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},M=(e,t,r)=>{if(N.has(e))return{kind:e};const[n,s]=t;switch(e){case"array":return{inner:d(n,{kind:"any"}),kind:"array"};case"from":return O(n);case"id":{if(!n||!i.isStringLiteral(n))throw b(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:x(n)};case"object":return n&&i.isObjectLiteralExpression(n)?{kind:"object",shape:v(n)}:{kind:"object",shape:{}};case"optional":return{inner:d(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:d(n,{kind:"string"}),kind:"record",valueType:d(s,{kind:"any"})};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>i.isExpression(a)).map(a=>c(a))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},P=e=>{const[t]=e;if(e.length!==1||t===void 0||!i.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},$=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||T.has(r)){const s=t.getExpression(),a=i.isExpression(s)?c(s):{kind:"any"};if(p.has(r))return k(a,r);if(!m.has(r))return a;const o=r==="max"&&a.kind==="string"?P(n):void 0;return o!==void 0?{...a,hasRefinement:!0,stringMaxLength:Math.min(a.stringMaxLength??o,o)}:{...a,hasRefinement:!0,unmodelledRefinement:!0}}return M(r,n,e)};export{c as a,v as p,u as r,z as s};
@@ -0,0 +1 @@
1
+ const o=s=>s.filter(i=>i.topic===void 0),p=(s,i)=>s.filter(t=>t.topic===i);export{o as p,p as s};
@@ -0,0 +1 @@
1
+ import{statSync as x,readFileSync as y}from"node:fs";import{basename as E}from"node:path";import{createJiti as P}from"jiti";import{Node as i,Project as S}from"ts-morph";import{findProjectConfigFile as v}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const j=r=>{if(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r)||i.isNumericLiteral(r))return r.getLiteralText();if(i.isComputedPropertyName(r)){const t=r.getExpression();return i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)?t.getLiteralText():void 0}return r.getText()},A=r=>j(r)??r.getText(),d=r=>A(r.getNameNode()),f=new Map,$=async r=>{const t=v(r);if(t===void 0)return{};let e;try{const a=x(t);e=`${String(a.mtimeMs)}:${String(a.size)}`}catch{return{}}const n=f.get(t);if(n?.key===e)return n.value;const s=(async()=>{try{const o=(await P(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(a){return{error:a instanceof Error?a.message:String(a)}}})();return f.set(t,{key:e,value:s}),s},h=r=>{let e=r.getExportAssignments().find(n=>!n.isExportEquals())?.getExpression();for(;e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&i.isIdentifier(e))for(e=r.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e));)e=e.getExpression();return e!==void 0&&i.isObjectLiteralExpression(e)?e:void 0},g=(r,t)=>i.isPropertyAssignment(r)?r.getInitializer():t.getVariableDeclaration(d(r))?.getInitializer(),b=r=>{let t=r;for(;t!==void 0&&(i.isSatisfiesExpression(t)||i.isAsExpression(t)||i.isParenthesizedExpression(t));)t=t.getExpression();return t},p=(r,t,e)=>{const n=b(r);if(n===void 0||!i.isObjectLiteralExpression(n))return{unreadable:!0};const s=n.getProperties(),a=s.filter(u=>i.isPropertyAssignment(u)&&!i.isComputedPropertyName(u.getNameNode())||i.isShorthandPropertyAssignment(u));if(a.length!==s.length)return{unreadable:!0};const o=a.find(u=>d(u)===e);if(o===void 0)return{absent:!0};const l=g(o,t);return l===void 0?{unreadable:!0}:{literal:l}},O=["exportName","file","reason","rule"],N=r=>{const t=b(r);if(t===void 0||!i.isObjectLiteralExpression(t))return;const e={};for(const l of t.getProperties()){if(!i.isPropertyAssignment(l)||i.isComputedPropertyName(l.getNameNode()))return;const u=d(l),c=b(l.getInitializer());if(!O.includes(u)||c===void 0||!i.isStringLiteral(c)&&!i.isNoSubstitutionTemplateLiteral(c))return;e[u]=c.getLiteralValue()}const{exportName:n,file:s,reason:a,rule:o}=e;return n?.trim()&&s?.trim()&&a?.trim()&&o?.trim()?{exportName:n,file:s,reason:a,rule:o}:void 0},T=(r,t)=>{const e=p(r,t,"accept");if("absent"in e)return{};const n="literal"in e?b(e.literal):void 0;if(n===void 0||!i.isArrayLiteralExpression(n))return{acceptUnreadable:!0};const s=[];for(const a of n.getElements()){const o=N(a);if(o===void 0)return{acceptUnreadable:!0};s.push(o)}return{accept:s}},C=(r,t)=>{const e=p(r,t,"minSeverity"),n=T(r,t);return"absent"in e?{advisor:n}:"literal"in e&&i.isStringLiteral(e.literal)?{advisor:{...n,minSeverity:e.literal.getLiteralValue()}}:{advisor:{...n,unreadable:!0}}},z=(r,t)=>{const e=p(r,t,"exclude");if("absent"in e)return{codegen:{}};if(!("literal"in e)||!i.isArrayLiteralExpression(e.literal))return{codegen:{unreadable:!0}};const n=[];for(const s of e.literal.getElements()){if(!i.isStringLiteral(s)&&!i.isNoSubstitutionTemplateLiteral(s)||s.getLiteralValue().startsWith("!"))return{codegen:{unreadable:!0}};n.push(s.getLiteralValue())}return{codegen:{exclude:n}}},w=(r,t)=>{const e=p(r,t,"merge");return"absent"in e?{durableObjects:{}}:"literal"in e&&(i.isTrueLiteral(e.literal)||i.isFalseLiteral(e.literal))?{durableObjects:{merge:e.literal.getLiteralValue()}}:{durableObjects:{unreadable:!0}}},D=new Map([["advisor",{advisor:{unreadable:!0}}],["codegen",{codegen:{unreadable:!0}}],["durableObjects",{durableObjects:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),L=(r,t)=>{const e=r.getProperty(t);if(e!==void 0)return(i.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},m=(r,t)=>{const e=L(r,t);if(e!==void 0)return e!=="unreadable"&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},V=r=>{const t=L(r,"rpc");if(t!==void 0)return t!=="unreadable"&&i.isFalseLiteral(t)?!1:"unreadable"},I=r=>{const t=b(r);if(t===void 0||!i.isObjectLiteralExpression(t))return{services:{unreadable:!0}};const e={};for(const n of t.getProperties()){if(!i.isPropertyAssignment(n)||i.isComputedPropertyName(n.getNameNode()))return{services:{unreadable:!0}};const s=b(n.getInitializer());if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperties().some(u=>!i.isPropertyAssignment(u)))return{services:{unreadable:!0}};const a=m(s,"dir"),o=m(s,"entrypoint"),l=V(s);if(typeof a!="string"||o===!1||l==="unreadable")return{services:{unreadable:!0}};e[d(n)]={dir:a,...o===void 0?{}:{entrypoint:o},...l===void 0?{}:{rpc:l}}}return{services:{declared:e}}},M=(r,t)=>{if(i.isGetAccessorDeclaration(r)||i.isMethodDeclaration(r))return D.get(d(r))??{};if(!i.isPropertyAssignment(r)&&!i.isShorthandPropertyAssignment(r))return{};const e=d(r);if(e==="advisor")return C(g(r,t),t);if(e==="services")return I(g(r,t));if(e==="codegen")return z(g(r,t),t);if(e==="durableObjects")return w(g(r,t),t);if(e!=="target"&&e!=="remote")return{};const n=g(r,t);return n===void 0?{unreadable:!0}:e==="target"?i.isStringLiteral(n)?{target:n.getLiteralValue()}:{unreadable:!0}:i.isTrueLiteral(n)||i.isFalseLiteral(n)?{remote:n.getLiteralValue()}:i.isObjectLiteralExpression(n)?{remote:!0}:{unreadable:!0}},k=r=>{const t=v(r);if(t===void 0)return{};let e;try{e=y(t,"utf8")}catch{return{unreadable:!0}}const s=new S({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(E(t),e,{overwrite:!0}),a=h(s);if(a===void 0)return{unreadable:!0};if(a.getProperties().some(l=>i.isSpreadAssignment(l))){const l=u=>a.getProperties().some(c=>!i.isSpreadAssignment(c)&&d(c)===u);return{...l("advisor")?{advisor:{unreadable:!0}}:{},...l("codegen")?{codegen:{unreadable:!0}}:{},...l("durableObjects")?{durableObjects:{unreadable:!0}}:{},...l("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let o={};for(const l of a.getProperties())o={...o,...M(l,s)};return o},q=r=>{const{durableObjects:t}=k(r);return t?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),t?.merge===!0};export{d as a,q as b,$ as l,A as p,k as r,j as s};
@@ -0,0 +1 @@
1
+ import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-DnCokNcE.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
@@ -0,0 +1 @@
1
+ import{join as r}from"node:path";import{readJsonSync as a}from"@visulima/fs";const p=o=>{try{const t=a(r(o,"package.json")),n=new Set;for(const c of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=t[c];if(e!==null&&typeof e=="object")for(const s of Object.keys(e))n.add(s)}return n}catch{return}};export{p as default};
@@ -0,0 +1 @@
1
+ import{existsSync as g,readFileSync as p}from"node:fs";import{isAbsolute as w,resolve as m,join as u}from"node:path";import{ts as h}from"ts-morph";import{r as E}from"./project-config-file-BV7RR-l6.mjs";const f=/^[A-Za-z_$][\w$]*$/u,$=["wrangler.jsonc","wrangler.json"],b=t=>`SERVICE_${t.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,y=(t,e)=>{const r=$.map(n=>u(e,n)).find(n=>g(n));if(r===void 0){const n=g(u(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${t}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=h.parseConfigFileTextToJson(r,p(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${t}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},v=(t,e)=>{const r=t.route??e.route,o=t.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(t.workers_dev??e.workers_dev)!==!1},S=(t,e,r)=>{if(!f.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!f.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=w(r.dir)?r.dir:m(t,r.dir),{config:n,path:s}=y(e,o),{main:c,name:l}=n;if(typeof l!="string"||l==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no Worker "name"`);if(typeof c!="string"||c==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no "main" entry module`);const d=Object.entries(n.env??{}).map(([i,a])=>[i,a??{}]);return{binding:b(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(d.flatMap(([i,a])=>typeof a.name=="string"&&a.name!==""?[[i,a.name]]:[])),main:m(o,c),name:e,publicScopes:[...v(n,n)?[""]:[],...d.filter(([,i])=>v(i,n)).map(([i])=>i)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:l,wranglerPath:s}},j=t=>{const{services:e}=E(t);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>S(t,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const s=r.slice(o+1).find(c=>c.binding===n.binding);if(s!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${s.name}" both map to the binding ${n.binding} — rename one`)}return r},A=t=>{try{return{services:j(t)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}};export{A as readServiceBindings,j as resolveServiceBindings};
@@ -0,0 +1 @@
1
+ const s=/[\w+/=-]{40,}/u,n=/[a-z]/u,E=/[A-Z]/u,_=/\d/u,c=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,o=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:n.test(e)&&E.test(e)&&_.test(e)},i=t=>c.test(t),r=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,a=/\bAKIA[\dA-Z]{16}\b/u,R=/\bgh[posru]_[\dA-Za-z]{36,}/u,d=/\bsk-[\dA-Za-z]{32,}/u,A=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,k=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,S=[{kind:"stripe_live_key",test:t=>r.test(t)},{kind:"aws_access_key",test:t=>a.test(t)},{kind:"github_token",test:t=>R.test(t)},{kind:"openai_key",test:t=>d.test(t)},{kind:"slack_token",test:t=>A.test(t)},{kind:"private_key",test:t=>k.test(t)},{kind:"high_entropy",test:o},{kind:"hex_secret",test:i}],u=new Set(["hex_secret","high_entropy"]),h=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),p=/([a-z\d])([A-Z])/gu,T=/[^A-Za-z\d]+/u,I=t=>t.replaceAll(p,"$1 $2").split(T).filter(Boolean).map(e=>e.toLowerCase()),l=t=>t!==void 0&&I(t).some(e=>h.has(e)),K=t=>S.find(e=>e.test(t))?.kind,b=t=>u.has(t),g=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{S as SECRET_RULES,b as isHeuristicSecretKind,l as isSecretishName,g as redact,K as secretKindOf};
@@ -0,0 +1 @@
1
+ const t=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),i=/^[$A-Z_a-z][\w$]*$/u,a=e=>i.test(e)&&!t.has(e);export{t as R,a as i};
@@ -0,0 +1 @@
1
+ const o=d=>typeof d.shardMode=="object"&&d.shardMode.kind==="shardBy";export{o as i};
@@ -0,0 +1 @@
1
+ const s=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=s(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{shape:Object.fromEntries(Object.entries(a.shape).map(([l,o])=>[l,n(o)]))}]))});export{m as schemaFromIr};
@@ -0,0 +1,368 @@
1
+ import{CAPABILITIES as Re}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{join as q,relative as m,dirname as Q,isAbsolute as Se,sep as De}from"node:path";import{ts as i,Project as Me}from"ts-morph";import{G as Z,a as $,u as Ce,d as Ne}from"./shared-DnCokNcE.mjs";import{p as Ae}from"./platform-8oj7iXQy.mjs";const ee=/(?:\.d)?\.([cm]?)tsx?$/u,Fe=t=>t.replace(ee,".d.$1ts"),te=(t,n)=>{const a=m(t,n).split(De).join("/").replace(ee,".$1js");return a.startsWith(".")?a:`./${a}`},ae=t=>t.replaceAll("\\","/"),E=(t,n,a)=>ae(q(t,Fe(m(n,a)))),Pe=t=>te(".",q("services",t.name,m(Q(t.wranglerPath),t.main))),We=t=>{const n=[],a=r=>{(i.isImportDeclaration(r)||i.isExportDeclaration(r))&&r.moduleSpecifier!==void 0&&i.isStringLiteral(r.moduleSpecifier)?n.push(r.moduleSpecifier):i.isImportTypeNode(r)&&i.isLiteralTypeNode(r.argument)&&i.isStringLiteral(r.argument.literal)&&n.push(r.argument.literal),i.forEachChild(r,a)};return a(t),n},Ge=(t,n)=>{const a=Q(t.wranglerPath),r=m(a,t.main);if(r.startsWith("..")||Se(r))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const d=q(n,"services",t.name),c=i.findConfigFile(a,o=>i.sys.fileExists(o)),p=new Me({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:d,rootDir:a},skipAddingFilesFromTsConfig:!0,...c===void 0?{}:{tsConfigFilePath:c}});p.addSourceFileAtPath(t.main),p.resolveSourceFileDependencies();const u={...p.getCompilerOptions(),preserveSymlinks:!0},x=new Map(p.getSourceFiles().map(o=>o.getFilePath()).filter(o=>!o.endsWith(".d.ts")&&!m(a,o).startsWith("..")).map(o=>[E(d,a,o),o])),y={};for(const o of p.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const g=x.get(ae(o.filePath));if(g===void 0)continue;const h=i.createSourceFile(o.filePath,o.text,i.ScriptTarget.Latest,!1);let{text:f}=o;for(const b of We(h).toReversed()){const s=i.resolveModuleName(b.text,g,u,i.sys).resolvedModule?.resolvedFileName;if(s===void 0)continue;const T=E(d,a,s),v=x.has(T)?T:s;f=`${f.slice(0,b.getStart(h))}${JSON.stringify(te(Q(o.filePath),v))}${f.slice(b.getEnd())}`}y[m(n,o.filePath)]=`${Z}${f}`}if(y[m(n,E(d,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return y},je=(t,n=[])=>{const a=new Set;for(const r of t.tables)for(const d of Object.values(r.shape)){const c=Ce(d);c.kind==="storage"&&typeof c.bucket=="string"&&c.bucket!==""&&a.add(c.bucket)}for(const r of n)r!==""&&r!=="default"&&a.add(r);return["default",...[...a].toSorted((r,d)=>r.localeCompare(d))]},He=({agents:t=[],capabilities:n=new Set,containers:a=[],env:r,hasVectors:d=!0,hasFlags:c=!1,hasNotify:p=!1,identity:u,queues:x=[],schema:y,services:o=[],storageRuleBuckets:g=[],topics:h=[],useUmbrella:f=!1,workflows:b=[]}={})=>{const s=Ne(f),T=je(y??{tables:[]},g).map(e=>JSON.stringify(e)).join(" | "),v=e=>e.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",re=[...new Set(a.map(e=>v(e)))].toSorted((e,l)=>e.localeCompare(l)),oe=a.length>0?`import type { ${re.join(", ")} } from "@lunora/container";
2
+ `:"",ne=a.length>0?`
3
+ readonly containers: {${a.map(e=>`
4
+ readonly ${e.exportName}: ${v(e)};`).join("")}
5
+ };`:"",L=[...n.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...a.map(e=>($(e.bindingName,`container binding "${e.bindingName}"`),` /** Durable Object namespace for the \`${e.exportName}\` container. */
6
+ readonly ${e.bindingName}?: unknown;`)),...x.map(e=>($(e.bindingName,`queue binding "${e.bindingName}"`),` /** Queue producer binding for the \`${e.exportName}\` queue. */
7
+ readonly ${e.bindingName}?: unknown;`))].join(`
8
+ `),se=`
9
+
10
+ /**
11
+ * This project's Cloudflare bindings, as far as codegen can discover them from
12
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
13
+ * conventional Workers AI binding. Bindings the config layer reconciles from
14
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
15
+ * visible here, so the open index signature keeps them reachable (cast at the
16
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
17
+ * under this signature too — Lunora can't type a third-party worker's RPC
18
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
19
+ */
20
+ export interface CloudflareBindings {
21
+ readonly [binding: string]: unknown;${L?`
22
+ ${L}`:""}
23
+ }
24
+
25
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
26
+ export type Env = CloudflareBindings;`,V=e=>Re.map(l=>l.tier!==void 0&&e.includes(l.tier)&&n.has(l.key)?l.serverCtxField:"").join(""),_=V(["every"]),ie=V(["every","action"]),k=d&&(y?.vectorIndexes.length??0)>0,I=k?' | "vectors"':"",G=k?`
27
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",le=k?`
28
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",de=k?`import type { VectorSearch, VectorSearchReader } from "${s.server}";
29
+ import type { VectorIndexName } from "./dataModel.js";
30
+ `:"",O=c?`
31
+ /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
32
+ readonly flags: import("${s.flags}").LunoraFlags;`:"",B=p?`
33
+ /** 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. */
34
+ readonly notify: import("@lunora/notify").LunoraNotify;
35
+ /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
36
+ readonly push: import("@lunora/notify").LunoraPush;`:"",w=b.length>0,ce=w?`import type { WorkflowHandle } from "@lunora/workflow";
37
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
38
+ `:"",ue=w?`
39
+
40
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
41
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
42
+ ? unknown extends Params
43
+ ? Record<string, unknown>
44
+ : NonNullable<Params>
45
+ : Record<string, unknown>;
46
+
47
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
48
+ export interface LunoraWorkflows {
49
+ ${b.map(e=>` get(name: ${JSON.stringify(e.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${e.exportName}>>;`).join(`
50
+ `)}
51
+ }`:"",H=w?' | "workflows"':"",U=w?`
52
+ readonly workflows: LunoraWorkflows;`:"",R=Ae(x),S=R.length>0,D=h.length>0,M=[...S?["QueueProducer"]:[],...D?["TopicPublisher"]:[]],z=[...new Set([...R,...h].map(e=>e.filePath))].toSorted((e,l)=>+(l==="queues")-+(e==="queues")||e.localeCompare(l)),C=e=>e==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(z.indexOf(e))}`,pe=M.length>0?`import type { ${M.join(", ")} } from "@lunora/queue";
53
+ ${z.map(e=>`import type * as ${C(e)} from "../${e}.js";
54
+ `).join("")}`:"",me=M.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;":"",ye=S?`
55
+
56
+ /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
57
+ export interface LunoraQueues {
58
+ ${R.map(e=>` readonly ${e.exportName}: QueueProducer<QueueBodyOf<typeof ${C(e.filePath)}.${e.exportName}>>;`).join(`
59
+ `)}
60
+ }`:"",he=D?`
61
+
62
+ /** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
63
+ export interface LunoraTopics {
64
+ ${h.map(e=>` readonly ${e.exportName}: TopicPublisher<QueueBodyOf<typeof ${C(e.filePath)}.${e.exportName}>>;`).join(`
65
+ `)}
66
+ }`:"",fe=`${me}${ye}${he}`,J=S?`
67
+ readonly queues: LunoraQueues;`:"",K=D?`
68
+ readonly topics: LunoraTopics;`:"",N=o.length>0,Y=o.filter(e=>e.rpcEntrypoint!==void 0),be=Y.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",xe=N?`import type { ${be} } from "${s.server}";
69
+ ${Y.map(e=>`import type * as lunoraService_${e.name} from ${JSON.stringify(Pe(e))};
70
+ `).join("")}`:"",ge=N?`
71
+
72
+ /** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
73
+ export interface LunoraServices {
74
+ ${o.map(e=>{$(e.name,`service "${e.name}"`);const l=e.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${e.name}.${e.rpcEntrypoint}>`;return` readonly ${e.name}: ${l};`}).join(`
75
+ `)}
76
+ }`:"",Te=N?`
77
+ readonly services: LunoraServices;`:"",A=t.length>0,ve=A?`import type { AgentHandle } from "@lunora/agent";
78
+ `:"",ke=A?`
79
+
80
+ /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
81
+ export interface LunoraAgents {
82
+ ${t.map(e=>($(e.exportName,`agent export "${e.exportName}"`),` readonly ${e.exportName}: AgentHandle;`)).join(`
83
+ `)}
84
+ }`:"",X=A?`
85
+ readonly agents: LunoraAgents;`:"",we=u?`import type { InferIdentity } from "${s.server}";
86
+ import type * as lunoraIdentityContract from "../identity.js";
87
+ `:"",$e=u?`
88
+
89
+ /** 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. */
90
+ export type Identity = InferIdentity<typeof lunoraIdentityContract.${u.exportName}>;
91
+
92
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
93
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",F=u?' | "auth"':"",P=u?`
94
+ readonly auth: NarrowedAuth;`:"",Ie=u?", Identity":"",Oe=r?`import type * as lunoraEnvContract from "../env.js";
95
+ `:"",Be=r?`
96
+
97
+ /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
98
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${r.exportName}>;`:"",W=r?' | "env"':"",j=r?"\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`${Z}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${s.server}";
99
+ import type {
100
+ ActionBuilder,
101
+ ActionCtx as ActionCtxBase,
102
+ ColumnValidator,
103
+ DatabaseReader,
104
+ DatabaseWriter,
105
+ EmptyArgs,
106
+ InternalActionBuilder,
107
+ InternalMutationBuilder,
108
+ InternalQueryBuilder,
109
+ MutationBuilder,
110
+ MutationCtx as MutationCtxBase,
111
+ MutationStorage,
112
+ MutatorDefinition,
113
+ QueryBuilder,
114
+ QueryCtx as QueryCtxBase,
115
+ ReadOnlyStorage,
116
+ RegisteredMutator,
117
+ Storage as StorageBase,
118
+ TableReader,
119
+ Validator,
120
+ } from "${s.server}";
121
+
122
+ import type {
123
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
124
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
125
+ LoadWith as LoadWithOf,
126
+ TableReaderFacade as TableReaderFacadeOf,
127
+ TableWriterFacade as TableWriterFacadeOf,
128
+ WithArg as WithArgOf,
129
+ } from "${s.serverDataModel}";
130
+
131
+ export type {
132
+ AggregateOp,
133
+ GroupByEntry,
134
+ OrderBy,
135
+ QueryArgs,
136
+ QueryPage,
137
+ RankPage,
138
+ RankResult,
139
+ RestrictableQueryOptions,
140
+ RestrictableQueryOptionsOf,
141
+ SearchFilterBuilder,
142
+ SearchReader,
143
+ TableAggregateOptions,
144
+ TableAggregateOptionsOf,
145
+ TableGroupByOptions,
146
+ TableGroupByOptionsOf,
147
+ TableRankOptions,
148
+ TableRankPageOptions,
149
+ Where,
150
+ WhereOf,
151
+ WhereOperators,
152
+ } from "${s.serverDataModel}";
153
+
154
+ import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
155
+ ${de}${oe}${ce}${pe}${xe}${ve}${we}${Oe}
156
+ export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
157
+
158
+ /**
159
+ * The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
160
+ * over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
161
+ *
162
+ * They live here rather than in \`dataModel.ts\` because they are the half that
163
+ * needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
164
+ * package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
165
+ * types without installing a server dependency to do it.
166
+ */
167
+
168
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
169
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
170
+
171
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
172
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
173
+
174
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
175
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
176
+
177
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
178
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
179
+
180
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
181
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
182
+
183
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
184
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
185
+
186
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
187
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
188
+ values: (values: Insert<T>) => Promise<IdOfTable<T>>;
189
+ }
190
+
191
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
192
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
193
+ with: (values: Insert<T>) => Promise<void>;
194
+ }
195
+
196
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
197
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
198
+ set: (values: Partial<Insert<T>>) => Promise<void>;
199
+ }
200
+
201
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
202
+ export interface OrmReader {
203
+ query: DatabaseReaderFacade;
204
+ }
205
+
206
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
207
+ export interface OrmWriter extends OrmReader {
208
+ delete: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => Promise<void>;
209
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
210
+ replace: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmReplaceBuilder<T>;
211
+ update: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmUpdateBuilder<T>;
212
+ }
213
+
214
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
215
+ export type StorageBucketName = ${T};${se}${ue}${fe}${ge}${ke}${$e}${Be}
216
+
217
+ /**
218
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
219
+ * untyped against the schema; here \`db\` is widened to the generated per-table
220
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
221
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
222
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
223
+ */
224
+ /**
225
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
226
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
227
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
228
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
229
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
230
+ *
231
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
232
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
233
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
234
+ *
235
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
236
+ * error: each resolves to the table's declared names, or \`never\` when it
237
+ * declares none of that kind. Without them a renamed or dropped index left
238
+ * every call site typechecking, and the query either threw at runtime or
239
+ * degraded silently to a full table scan.
240
+ */
241
+ type TypedTableQuery = (<T extends TableName>(
242
+ table: T,
243
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
244
+ ((table: string) => TableReader);
245
+
246
+ /**
247
+ * The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
248
+ * carries its table name, so the resolved document is typed \`Doc<table>\` (or
249
+ * \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
250
+ */
251
+ type TypedTableGet = <T extends TableName>(id: IdOfTable<T>) => Promise<Doc<T> | null>;
252
+
253
+ /**
254
+ * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
255
+ * genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
256
+ * collapses to \`never\` so it fails to typecheck.
257
+ *
258
+ * The \`string extends T\` arm is what distinguishes "the caller passed a computed
259
+ * string" from "the caller passed a misspelled literal" — only the wide \`string\` type
260
+ * is a supertype of \`string\`.
261
+ */
262
+ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
263
+
264
+ /**
265
+ * The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
266
+ * table literal is a compile error rather than a call that hands back a confidently-
267
+ * branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
268
+ * {@link TypedTableGet}.
269
+ *
270
+ * Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
271
+ * overload resolution would fall through to it for a bad literal, silently restoring
272
+ * the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
273
+ * computed table name working — and keeps \`ctx.db\` structurally assignable to
274
+ * schema-agnostic consumers — without accepting an invalid literal.
275
+ */
276
+ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
277
+
278
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${I}${F}${W}> {
279
+ readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
280
+ readonly orm: OrmReader;
281
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${le}${_}${O}${B}${j}${P}
282
+ }
283
+
284
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${I}${H}${F}${W}> {
285
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
286
+ readonly orm: OrmWriter;
287
+ readonly storage: MutationStorage<StorageBucketName>;${G}${_}${O}${B}${j}${U}${J}${K}${X}${P}
288
+ }
289
+
290
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${I}${H}${F}${W}> {
291
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
292
+ readonly orm: OrmWriter;
293
+ readonly storage: StorageBase<StorageBucketName>;${G}${ie}${ne}${O}${B}${Te}${j}${U}${J}${K}${X}${P}
294
+ }
295
+
296
+ /**
297
+ * Procedure builders bound to this project's typed contexts. Chain
298
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
299
+ * masking (each middleware may refine \`ctx\`), then the terminal
300
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
301
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
302
+ */
303
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
304
+
305
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
306
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
307
+
308
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
309
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
310
+
311
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
312
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
313
+
314
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
315
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
316
+
317
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
318
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
319
+
320
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
321
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
322
+
323
+ /**
324
+ * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
325
+ * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
326
+ * \`${s.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
327
+ * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
328
+ * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
329
+ * no \`as unknown as\` cast. Runtime-identical to the package export; only the
330
+ * context type narrows, so discovery finds a mutator authored either way.
331
+ * @example
332
+ * export const setText = defineMutator({
333
+ * args: { id: v.id("nodes"), text: v.string() },
334
+ * server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); },
335
+ * });
336
+ */
337
+ export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
338
+ definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
339
+ ) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
340
+
341
+ /**
342
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
343
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
344
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
345
+ * name and the \`when\` predicate type-checks against the table's columns **and**
346
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
347
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
348
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
349
+ * so the \`rls()\` chain discovers a policy authored either way the same.
350
+ */
351
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Ie}>();
352
+
353
+ /**
354
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
355
+ * table names — so the argument autocompletes and returns a precise
356
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
357
+ * difference is the tightened \`id\` type.
358
+ *
359
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
360
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
361
+ * file that defines the table names, so they aren't known yet there; pass the
362
+ * names as string literals and the generated \`Id<"table">\` types still catch a
363
+ * typo wherever the id is used.
364
+ */
365
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
366
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
367
+ };
368
+ `};export{Ge as a,He as e};