@lunora/codegen 1.0.0-alpha.25 → 1.0.0-alpha.251

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 (113) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3734 -1247
  4. package/dist/index.d.ts +3734 -1247
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-D8SgT3OR.mjs +1 -0
  7. package/dist/packem_shared/CAPABILITY_PROBES-BbW-W0N2.mjs +22 -0
  8. package/dist/packem_shared/CONTAINERS_FILENAME-C13yKxas.mjs +1 -0
  9. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_TARGET-vMWzRzRF.mjs +1 -0
  11. package/dist/packem_shared/FLAGS_FILENAME-W5XQz_Po.mjs +1 -0
  12. package/dist/packem_shared/GENERATED_HEADER-DSXl0YM2.mjs +1 -0
  13. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  14. package/dist/packem_shared/MUTATORS_FILENAME-DqWOgC5Z.mjs +1 -0
  15. package/dist/packem_shared/NOTIFY_FILENAME-C1J_47et.mjs +1 -0
  16. package/dist/packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs +3 -0
  17. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  18. package/dist/packem_shared/QUEUES_FILENAME-RGwht3Xu.mjs +1 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-qrQnFo7L.mjs +11 -0
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  21. package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
  22. package/dist/packem_shared/SHAPES_FILENAME-DRUFomCj.mjs +1 -0
  23. package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
  24. package/dist/packem_shared/WORKFLOWS_FILENAME-4-ib4HH-.mjs +1 -0
  25. package/dist/packem_shared/buildOpenApiDocument-SxfElVzK.mjs +3 -0
  26. package/dist/packem_shared/chain-mte5djRJ.mjs +1 -0
  27. package/dist/packem_shared/classify-procedure-call-CmcShAze.mjs +1 -0
  28. package/dist/packem_shared/context-property-calls-CWf9-6G5.mjs +1 -0
  29. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  30. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  31. package/dist/packem_shared/discoverAuthApiCalls-DoSN_yc3.mjs +1 -0
  32. package/dist/packem_shared/discoverCrons-BEALHx1S.mjs +1 -0
  33. package/dist/packem_shared/discoverFunctions-BcBzcG5x.mjs +1 -0
  34. package/dist/packem_shared/discoverHttpRoutes-CJHS4llq.mjs +1 -0
  35. package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +1 -0
  36. package/dist/packem_shared/discoverInserts-DpuLYPPd.mjs +1 -0
  37. package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +1 -0
  38. package/dist/packem_shared/discoverMigrations-Dt7ywfZv.mjs +1 -0
  39. package/dist/packem_shared/discoverNondeterministicCalls-CNJV2BiP.mjs +1 -0
  40. package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +1 -0
  41. package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +1 -0
  42. package/dist/packem_shared/discoverRlsMetadata-mXBmPOGj.mjs +1 -0
  43. package/dist/packem_shared/discoverRlsProcedures-F4Cy-kSi.mjs +1 -0
  44. package/dist/packem_shared/discoverSandboxUsage-BnsPld5I.mjs +1 -0
  45. package/dist/packem_shared/discoverSchema-D5R60b4F.mjs +1 -0
  46. package/dist/packem_shared/discoverStorageRulesMetadata-D3Ot9g5f.mjs +1 -0
  47. package/dist/packem_shared/emitAgents-DtZrevpx.mjs +1 -0
  48. package/dist/packem_shared/emitApi-DdW9RyGG.mjs +154 -0
  49. package/dist/packem_shared/emitApp-Cp0kB4-N.mjs +860 -0
  50. package/dist/packem_shared/emitCrons-BRKXFGFu.mjs +83 -0
  51. package/dist/packem_shared/emitDataModel-D3WuEZ4b.mjs +113 -0
  52. package/dist/packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs +15 -0
  53. package/dist/packem_shared/emitFunctions-BgNeOZt_.mjs +249 -0
  54. package/dist/packem_shared/emitServer-BOpHpi8r.mjs +370 -0
  55. package/dist/packem_shared/emitShard-HB5NPFdO.mjs +1 -0
  56. package/dist/packem_shared/exported-procedure-chains-D48EXUVQ.mjs +1 -0
  57. package/dist/packem_shared/fingerprintSchemaSources-Cl1CJFeh.mjs +1 -0
  58. package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
  59. package/dist/packem_shared/index-D7dKfGPh.mjs +1 -0
  60. package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
  61. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  62. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  63. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  64. package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +1 -0
  65. package/dist/packem_shared/loadProjectConfig-nNIDOrlR.mjs +1 -0
  66. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  67. package/dist/packem_shared/modules-DyCocr1e.mjs +1 -0
  68. package/dist/packem_shared/parse-validator-C6fHL7OS.mjs +1 -0
  69. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  70. package/dist/packem_shared/qualifiers-BhOL15WZ.mjs +1 -0
  71. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  72. package/dist/packem_shared/readServiceBindings-CeQvSswr.mjs +1 -0
  73. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  74. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  75. package/dist/packem_shared/shard-CyNCZP7J.mjs +1435 -0
  76. package/dist/packem_shared/shard-runtime-DMN3MgIM.mjs +321 -0
  77. package/dist/packem_shared/shared-DjUziztz.mjs +9 -0
  78. package/dist/packem_shared/sourceCapabilitySignals-oZFprILA.mjs +1 -0
  79. package/dist/packem_shared/unwrap-handler-return-DVY_kFF7.mjs +1 -0
  80. package/package.json +16 -7
  81. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  82. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  83. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  84. package/dist/packem_shared/GENERATED_HEADER-BullHnLo.mjs +0 -3265
  85. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  86. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  87. package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
  88. package/dist/packem_shared/OPENRPC_VERSION-D7MAVX3K.mjs +0 -60
  89. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  90. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BAcxxSdB.mjs +0 -1130
  91. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  92. package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
  93. package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
  94. package/dist/packem_shared/buildOpenApiDocument-Bm56LsBb.mjs +0 -183
  95. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  96. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  97. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  98. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  99. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  100. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  101. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  102. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  103. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  104. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  105. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  106. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  107. package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
  108. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  109. package/dist/packem_shared/emitApp-BUN7hhlY.mjs +0 -666
  110. package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
  111. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  112. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  113. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{c as f}from"./classify-procedure-call-CmcShAze.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of c(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,l(t,i)))}return n};export{w as default};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as u,Node as i}from"ts-morph";import{listLunoraSourceFiles as d,lunoraRelativePath as g,enclosingExportName as p,isDatabaseAccessor as h}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const m=new Set(["withGeoIndex","withIndex","withSearchIndex"]),x=new Set(["collect","collectWithScores","first","paginate","take","unique"]),E=r=>{const e=r.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const s=e.getExpression();return h(s)},P=r=>{const e=[];let s=r;for(;;){const t=s.getParent();if(!t||!i.isPropertyAccessExpression(t))break;const n=t.getParent();if(!n||!i.isCallExpression(n))break;e.push(t.getName()),s=n}return e},S=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,A=r=>{let e=r;for(;;){const s=e.getParent();if(!s||!i.isPropertyAccessExpression(s))return!1;const t=s.getParent();if(!t||!i.isCallExpression(t))return!1;if(s.getName()==="filter"){const n=t.getArguments()[0];if(n&&S.test(n.getText()))return!0}e=t}},y=r=>{const e=r.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},I=(r,e)=>{const s=[];for(const t of d(e)){const n=r.getSourceFile(t)??r.addSourceFileAtPath(t),f=g(e,t);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!E(a))continue;const o=P(a),l=o.includes("filter");s.push({exportName:p(a),file:f,filtersPrimaryKey:l&&A(a),hasFilter:l,hasIndex:o.some(c=>m.has(c)),line:a.getStartLineNumber(),table:y(a),terminal:o.findLast(c=>x.has(c))})}}return s};export{I as default};
@@ -0,0 +1 @@
1
+ import{d as r}from"./context-property-calls-CWf9-6G5.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
@@ -0,0 +1 @@
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{e as A}from"./exported-procedure-chains-D48EXUVQ.mjs";import{r as L}from"./chain-mte5djRJ.mjs";const E=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!E.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},v=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{I as default};
@@ -0,0 +1 @@
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d,findObjectProperty as p}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{c as m}from"./classify-procedure-call-CmcShAze.mjs";import{r as b}from"./chain-mte5djRJ.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const s=[];for(const r of t.getElements()){if(!o.isObjectLiteralExpression(r))continue;const i=p(r,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&s.push(n.getLiteralText())}return s},h=e=>{const t=b(e);return{rlsTables:t.flatMap(s=>g(s)),usesRls:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),v=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=m(s);if(!r)return;const i=r.receiver?h(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:l}=d(e,y,v);return{exportName:e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:l,usesRls:i.usesRls,visibility:r.visibility}},x=(e,t)=>{const s=[];for(const r of f(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=u(t,r);for(const l of i.getVariableStatements())if(l.isExported())for(const c of l.getDeclarations()){const a=P(c,n);a&&s.push(a)}}return s};export{x as default};
@@ -0,0 +1 @@
1
+ import{listLunoraSourceFiles as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const f=new Set(["@lunora/agent","@lunora/agent/sandbox"]),t={browserTool:"usesSandboxBrowser",containerFsTool:"usesSandboxContainer",containerTool:"usesSandboxContainer",fsTool:"usesSandboxFs",jsCodeTool:"usesSandboxLoader"},u=()=>({usesSandboxBrowser:!1,usesSandboxContainer:!1,usesSandboxFs:!1,usesSandboxLoader:!1}),i=o=>{const s=u();if(!f.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=t[e.getNameNode().getText()];n!==void 0&&(s[n]=!0)}return s},b=(o,s)=>{const e=u();for(const n of d(s)){const c=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const a of c.getImportDeclarations()){const l=i(a);for(const r of Object.values(t))e[r]||=l[r]}if(Object.values(t).every(a=>e[a]))break}return e};export{b as discoverSandboxUsage};
@@ -0,0 +1 @@
1
+ import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as F}from"node:module";import{join as C}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{r as B,p as V}from"./parse-validator-C6fHL7OS.mjs";const q=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:U(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=J(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>G(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},H=e=>{const t=X(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},Q=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},Y=(e,t)=>{const n=H(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Q(o,n);return typeof a!="object"||a===null?void 0:W(a)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},L=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},A=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=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"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,t)=>{if(ae.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(le.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ie(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?ce(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ue=e=>{const t=de(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=fe(s);r&&n.push(r)}return n},pe=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},me=e=>{const[t,n,s]=e,r=ge(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},be=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=L(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},xe=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},he=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},ve=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Ee=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ie=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Se=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:te(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},ke=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(n));break}case"global":{e.shardMode="global",e.globalBackend=Ie(n);break}case"index":{e.indexes.push(me(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Se(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(n);break}case"vectorize":{const r=Ee(n,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of _){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ne(t))},P=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))ke(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,t,n.searchIndexes),_e(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=B(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(w(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(P(o,a))}}return t},Le=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:o,table:Le(s)}},$=e=>{const t=[];for(const n of e.getProperties()){const s=Oe(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Ae=(e,t)=>{if(!N.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?S(t,e):e,Ne=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,t)=>{const n=Pe(e);if(n){if(i.isPropertyAccessExpression(t)){const s=De(n);return s?b(s,t.getName()):void 0}return n}},Me=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,je(t))return t;const s=$e(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ze(a,t)}},Re=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Fe=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);w(a,r.getNameNode()),s.push(P(o,a))}return s},Ce=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:$(n)},D=(e,t,n,s,r)=>{Ae(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>Ne(c,e,o,r)),l=n.map(c=>({...c,name:S(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Be=(e,t,n)=>D(e,Fe(n),Ce(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ve=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Me(n);if(!s){if(t!==void 0){const o=Y(n,t);if(o){for(const a of o.bareTables)w(a.name,n);return D(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Je=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of qe(e)){const a=Ve(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}t=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,a,n),k=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:k}};export{rt as default};
@@ -0,0 +1 @@
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{w as d}from"./classify-procedure-call-CmcShAze.mjs";import{e as m}from"./exported-procedure-chains-D48EXUVQ.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
@@ -0,0 +1 @@
1
+ import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as o,h as n,t as g,k as F,d as u,v as p,m as f,g as l,f as d,i as k,u as w,l as Q}from"./shard-runtime-DMN3MgIM.mjs";import"./shared-DjUziztz.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,o as emitAgents,n as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,f as emitQueuesMetadataFragments,l as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,Q as emitWorkflowsMetadataFragments};
@@ -0,0 +1,154 @@
1
+ import{agentComponent as T}from"@lunora/agent/component";import{LunoraError as P}from"@lunora/errors";import{s as u}from"./paths-C-9fwEgQ.mjs";import{r as j,a as K,b as h,c as E}from"./qualifiers-BhOL15WZ.mjs";import{G as w,a as B,r as g,p as $,b as x,c as y,d as v}from"./shared-DjUziztz.mjs";const A=t=>{const r=new Map;for(const o of t){const e=r.get(o.filePath)??[];e.push(o),r.set(o.filePath,e)}return[...r.entries()].toSorted(([o],[e])=>o.localeCompare(e))},C=t=>{const r=([o,e])=>{const c=e.toSorted((a,i)=>a.exportName.localeCompare(i.exportName)).map(a=>{const i=h(g(a.args),a.filePath),n=h(E(a),a.filePath);return` ${a.exportName}: FunctionReference<"${a.kind}", ${i}, ${n}>;`}).join(`
2
+ `);return` ${x(u(o))}: {
3
+ ${c}
4
+ };`};return A(t).map(o=>r(o)).join(`
5
+ `)},W=(t,r)=>{if(t.length===0&&r.length===0)return{block:"",importLine:""};const o=[];let e="";if(t.length>0&&(e+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),e+=`
6
+ /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
7
+ export interface WorkflowReference<Params = Record<string, unknown>> {
8
+ readonly isLunoraWorkflow: true;
9
+ readonly __params?: Params;
10
+ readonly className: string;
11
+ readonly name: string;
12
+ }
13
+ `,t.length>0){const c=[...t].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),a=c.map(n=>` ${n.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${n.exportName}>>;`).join(`
14
+ `),i=c.map(n=>` ${y(n.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(n.className)}, name: ${JSON.stringify(n.exportName)} },`).join(`
15
+ `);e+=`
16
+ /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
17
+ export interface WorkflowsRef {
18
+ ${a}
19
+ }
20
+
21
+ export const workflows: WorkflowsRef = {
22
+ ${i}
23
+ };
24
+ `,o.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
25
+ `)}if(r.length>0){const c=[...r].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),a=c.map(n=>` ${n.exportName}: WorkflowReference<AgentRunInput>;`).join(`
26
+ `),i=c.map(n=>` ${y(n.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(n.className)}, name: ${JSON.stringify(n.name)} },`).join(`
27
+ `);e+=`
28
+ /** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
29
+ export interface AgentsRef {
30
+ ${a}
31
+ }
32
+
33
+ export const agents: AgentsRef = {
34
+ ${i}
35
+ };
36
+ `,o.push(`import type { AgentRunInput } from "@lunora/agent";
37
+ `)}return{block:e,importLine:o.join("")}},D=()=>Object.keys(T().functions).toSorted((t,r)=>t.localeCompare(r)),O=t=>new Set(t.filter(r=>u(r.filePath)==="agents").map(r=>r.exportName)),J=()=>new Set(Object.entries(T().functions).filter(([,t])=>t.visibility==="internal").map(([t])=>t)),X=(t,r)=>{const o={importLine:"",lines:"",prelude:""};if(t.length===0)return o;const e=O(r),c=J(),a=r.find(n=>u(n.filePath)==="agents"&&c.has(n.exportName));if(a)throw new P("INTERNAL",`@lunora/codegen: "agents:${a.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${a.exportName}" export in ${a.filePath}`);const i=D().filter(n=>!e.has(n));return i.length===0?o:{importLine:`import { agentComponent } from "@lunora/agent/component";
38
+ `,lines:i.map(n=>` "agents:${n}": lunoraAgentRuntimeFunctions.${n} as unknown as RegisteredLunoraFunction,`).join(`
39
+ `),prelude:`
40
+ /**
41
+ * The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
42
+ * declares agents. The durable loop dispatches the internal mutations; clients
43
+ * subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
44
+ */
45
+ const lunoraAgentRuntimeFunctions = agentComponent().functions;
46
+ `}},Y=(t,r)=>{if(!t)return{importLine:"",lines:"",prelude:""};const o=r.find(e=>u(e.filePath)==="sandbox"&&e.exportName==="invoke");if(o)throw new P("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${o.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
47
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},H=(t,r)=>{if(t.length===0)return[];const o=O(r),e=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const c of t)c.voice&&e.push({args:{threadKey:{kind:"string"}},exportName:`${c.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return e.filter(c=>!o.has(c.exportName))},_=(t,r)=>{if(t.length===0)return[];const o=new Set(r.filter(e=>u(e.filePath)==="mutators").map(e=>e.exportName));return t.filter(e=>!o.has(e.exportName)).map(e=>({args:e.args,exportName:e.exportName,filePath:e.filePath,kind:"mutation",returnType:e.returnType}))},q=t=>{const r=t.filter(i=>i.stream);if(r.length===0)return{block:"",body:""};const o=A(r),e=o.map(([i,n])=>{const s=n.map(l=>{const p=h(l.chunkType??"unknown",l.filePath),d=h(g(l.searchParams),l.filePath),m=h(g(l.params),l.filePath);return` ${x(l.exportName)}: HttpStreamRef<${p}, ${d}, ${m}>;`}).join(`
48
+ `);return` ${x(u(i))}: {
49
+ ${s}
50
+ };`}).join(`
51
+ `),c=o.map(([i,n])=>{const s=n.map(l=>` ${y(l.exportName)}: { method: ${JSON.stringify(l.method)}, path: ${JSON.stringify(l.path)} },`).join(`
52
+ `);return` ${y(u(i))}: {
53
+ ${s}
54
+ },`}).join(`
55
+ `);return{block:`
56
+ /** This project's HTTP-SSE stream routes (\`httpRoute.<verb>(path).stream()\`), addressable as typed references for \`client.httpStream\` / \`useHttpStream\`. */
57
+ export interface HttpStreamsRef {
58
+ ${e}
59
+ }
60
+
61
+ export const httpStreams: HttpStreamsRef = {
62
+ ${c}
63
+ };
64
+ `,body:e}},Z=t=>{const{agents:r=[],functions:o,httpRoutes:e=[],mutators:c=[],useUmbrella:a=!1,workflows:i=[]}=t,n=v(a),s=[...o.filter(k=>k.visibility!=="internal"),...H(r,o),..._(c,o)],l=o.filter(k=>k.visibility==="internal"),p=C(s),d=C(l),m=q(e),b=`${p}
65
+ ${d}
66
+ ${m.body}`,f=j(b),L=f.length>0?`
67
+ import type { ${f.join(", ")} } from "./dataModel.js";
68
+ `:"",I=p?`
69
+ ${p}
70
+ `:"",M=d?`
71
+ ${d}
72
+ `:"",N=W(i,r),R=`export interface ApiTypes {${I}}
73
+
74
+ export const api = anyApi as unknown as ApiTypes;
75
+
76
+ /** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
77
+ export interface InternalApiTypes {${M}}
78
+
79
+ export const internal = anyApi as unknown as InternalApiTypes;
80
+ ${N.block}${m.block}`,S=[...R.includes("FunctionReference<")?["FunctionReference"]:[],...m.block===""?[]:["HttpStreamRef"]],F=S.length>0?`import type { ${S.join(", ")} } from "${n.client}";
81
+ `:"";return K(`${w}import { anyApi } from "${n.client}";
82
+ ${F}${N.importLine}${L}
83
+ ${R}`,a)},ee=t=>t?`${w}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
84
+ import type { SeedClient, SeedClientOptions } from "@lunora/seed";
85
+
86
+ import schema from "../schema.js";
87
+ import type { InsertModel } from "./dataModel.js";
88
+
89
+ /**
90
+ * Schema-aware seed client with this project's \`InsertModel\` and runtime schema
91
+ * pre-bound. Each table is a method; call it with a count, a range, explicit
92
+ * partial rows, or per-field overrides. Foreign keys connect to rows seeded
93
+ * earlier in the run, and FK-parent tables are seeded automatically.
94
+ * @example
95
+ * const seed = createSeedClient({ seed: 1 });
96
+ * const { users } = await seed.users(5);
97
+ * const { posts } = await seed.posts((x) => x([10, 20]));
98
+ */
99
+ export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
100
+ `:"",te=(t,r,o=!1)=>{if(t.length===0||!r)return"";const e=v(o),c=s=>s.table===void 0?"Row":`Doc<${JSON.stringify(s.table)}> & Row`,a=t.map(s=>{B(s.exportName,"shape export name");const l=c(s),p=h(g(s.args),s.filePath),d=Object.keys(s.args).length>0,m=d?` args: ${p};`:` args?: ${p};`,b=d?`(args: ${p}) => void`:`(args?: ${p}) => void`,f=`${s.exportName}CollectionOptions`;return`/** Options for the \`${s.exportName}\` shape binding. */
101
+ export interface ${$(f)} {
102
+ ${m}
103
+ /**
104
+ * Share the optimistic-overlay gate with other collections + mutators on this
105
+ * shard. Defaults to the shared per-shard registry, which is almost always what
106
+ * you want — pass one only to isolate this collection's gate.
107
+ */
108
+ checkpoints?: CheckpointRegistry;
109
+ /** The Lunora client to subscribe through. */
110
+ client: LunoraClient;
111
+ /** Row key extractor — defaults to \`row._id\`. Override when the app keys rows by a natural column. */
112
+ getKey?: (row: ${l}) => string;
113
+ /** \`"eager"\` starts syncing at creation; \`"lazy"\` (default) on the first subscriber. */
114
+ load?: "eager" | "lazy";
115
+ /** Notified when the underlying subscription errors; the collection always leaves \`loading\`. */
116
+ onError?: (error: SubscriptionError) => void;
117
+ /** Routes the subscription to a shard's DO. **Required for a \`.shardBy()\` table** — without it the watermark lands in the default bucket. */
118
+ shardKey?: string;
119
+ }
120
+
121
+ /**
122
+ * Collection options for the \`${s.exportName}\` replication shape: \`config\` for
123
+ * \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
124
+ * \`scope\` to re-point the subscription.
125
+ */
126
+ export const ${s.exportName}CollectionOptions = (options: ${$(f)}): LunoraCollectionOptions<${l}> =>
127
+ lunoraCollectionOptions<${l}>({
128
+ client: options.client,
129
+ ...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
130
+ ...(options.getKey === undefined ? {} : { getKey: options.getKey }),
131
+ ...(options.load === undefined ? {} : { load: options.load }),
132
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
133
+ ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }),
134
+ shape: { args: options.args, name: ${JSON.stringify(s.exportName)}, ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }) },
135
+ });
136
+
137
+ /** Live collection for the \`${s.exportName}\` shape, with its sync controls. */
138
+ export const ${s.exportName}Collection = (
139
+ options: ${$(f)},
140
+ ): { checkpoints: CheckpointRegistry; collection: Collection<${l}, string>; scope: ${b} } => {
141
+ const { checkpoints, config, scope } = ${s.exportName}CollectionOptions(options);
142
+
143
+ return { checkpoints, collection: createCollection(config), scope };
144
+ };`}).join(`
145
+
146
+ `),i=j(a),n=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
147
+ `:"";return`${w}import type { LunoraClient, SubscriptionError } from "${e.client}";
148
+ import { lunoraCollectionOptions } from "@lunora/db/collections";
149
+ import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
150
+ import type { Collection } from "@tanstack/db";
151
+ import { createCollection } from "@tanstack/db";
152
+ ${n}
153
+ ${a}
154
+ `};export{Z as emitApi,te as emitCollections,ee as emitSeed,A as groupByFileSorted,X as renderAgentFunctionRegistry,Y as renderSandboxFunctionRegistry};