@lunora/codegen 1.0.0-alpha.265 → 1.0.0-alpha.266

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 (94) hide show
  1. package/dist/index.d.mts +38 -10
  2. package/dist/index.d.ts +38 -10
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/AGENTS_FILENAME-DwlmRvXo.mjs +1 -0
  5. package/dist/packem_shared/CONTAINERS_FILENAME-D8YLxYhQ.mjs +1 -0
  6. package/dist/packem_shared/DEFAULT_TARGET-CaXPORLo.mjs +1 -0
  7. package/dist/packem_shared/FLAGS_FILENAME-BGFPEEjc.mjs +1 -0
  8. package/dist/packem_shared/MUTATORS_FILENAME-DwAZEI6d.mjs +1 -0
  9. package/dist/packem_shared/NOTIFY_FILENAME-DrBbzi0l.mjs +1 -0
  10. package/dist/packem_shared/{OPENRPC_VERSION-CGu1_YK7.mjs → OPENRPC_VERSION-BqeEI2Dn.mjs} +1 -1
  11. package/dist/packem_shared/QUEUES_FILENAME-D0AeAQz-.mjs +1 -0
  12. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-YwnhjnM-.mjs +11 -0
  13. package/dist/packem_shared/SHAPES_FILENAME-C-CUVhR6.mjs +1 -0
  14. package/dist/packem_shared/WORKFLOWS_FILENAME-d1r1GnQd.mjs +1 -0
  15. package/dist/packem_shared/attribution-B7i322L0.mjs +1 -0
  16. package/dist/packem_shared/{buildOpenApiDocument-DOsv1HEF.mjs → buildOpenApiDocument-BYtXD9iB.mjs} +1 -1
  17. package/dist/packem_shared/capabilitiesUsedBy-_kfPZ5wC.mjs +1 -0
  18. package/dist/packem_shared/chain-C17a7v59.mjs +1 -0
  19. package/dist/packem_shared/classify-procedure-call-DC_O3oNQ.mjs +1 -0
  20. package/dist/packem_shared/context-property-calls-BvE4YxG6.mjs +1 -0
  21. package/dist/packem_shared/context-root-C4hjiCTo.mjs +1 -0
  22. package/dist/packem_shared/{database-calls-Br5z7dZL.mjs → database-calls-B6ylmcGA.mjs} +1 -1
  23. package/dist/packem_shared/discoverAuthApiCalls-CUM8XgDc.mjs +1 -0
  24. package/dist/packem_shared/discoverCrons-DI1xHRei.mjs +1 -0
  25. package/dist/packem_shared/discoverFunctions-B-7117i2.mjs +1 -0
  26. package/dist/packem_shared/discoverHttpRoutes-BT2HmWD_.mjs +1 -0
  27. package/dist/packem_shared/discoverHyperdriveCalls-Bir4M-bD.mjs +1 -0
  28. package/dist/packem_shared/discoverInserts-BHxWlrW0.mjs +1 -0
  29. package/dist/packem_shared/discoverMaskProcedures-DHqunTJ7.mjs +1 -0
  30. package/dist/packem_shared/discoverMigrations-DdeNFu0j.mjs +1 -0
  31. package/dist/packem_shared/discoverNondeterministicCalls-Deg23AAc.mjs +1 -0
  32. package/dist/packem_shared/discoverQueries-yKWWoX-Z.mjs +1 -0
  33. package/dist/packem_shared/discoverR2sqlCalls-C48f9S0b.mjs +1 -0
  34. package/dist/packem_shared/discoverRlsMetadata-DwG8EMHQ.mjs +1 -0
  35. package/dist/packem_shared/discoverRlsProcedures-D3UFRjOI.mjs +1 -0
  36. package/dist/packem_shared/discoverSandboxUsage-C-ntjbjl.mjs +1 -0
  37. package/dist/packem_shared/discoverSchema-DFN2L811.mjs +1 -0
  38. package/dist/packem_shared/discoverStorageRulesMetadata-B-f9lVjJ.mjs +1 -0
  39. package/dist/packem_shared/{emitApp-RNU41dtm.mjs → emitApp-Dec8sEI0.mjs} +2 -0
  40. package/dist/packem_shared/{exported-procedure-chains-CKLvyjfX.mjs → exported-procedure-chains-CmwqreGv.mjs} +1 -1
  41. package/dist/packem_shared/fingerprintSchemaSources-4S1x40Bs.mjs +1 -0
  42. package/dist/packem_shared/handler-reference-DaXlBYJx.mjs +1 -0
  43. package/dist/packem_shared/index-B5G7NWDW.mjs +1 -0
  44. package/dist/packem_shared/isTestPath-5ruOnRVA.mjs +1 -0
  45. package/dist/packem_shared/loadProjectConfig-D-yD5eRd.mjs +1 -0
  46. package/dist/packem_shared/modules-DQv8-RtF.mjs +1 -0
  47. package/dist/packem_shared/parse-validator-C2Osg6gv.mjs +1 -0
  48. package/dist/packem_shared/project-config-file-Cb5ouVEK.mjs +1 -0
  49. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  50. package/dist/packem_shared/readServiceBindings-BcN87FPt.mjs +1 -0
  51. package/dist/packem_shared/unwrap-handler-return-CM6v2E3A.mjs +1 -0
  52. package/package.json +2 -1
  53. package/dist/packem_shared/AGENTS_FILENAME-C-halsN9.mjs +0 -1
  54. package/dist/packem_shared/CONTAINERS_FILENAME-DY4sWZYx.mjs +0 -1
  55. package/dist/packem_shared/DEFAULT_TARGET-7sHexLjO.mjs +0 -1
  56. package/dist/packem_shared/FLAGS_FILENAME-BINQ51Zq.mjs +0 -1
  57. package/dist/packem_shared/MUTATORS_FILENAME-CuG6xLJ1.mjs +0 -1
  58. package/dist/packem_shared/NOTIFY_FILENAME-C70ZrThq.mjs +0 -1
  59. package/dist/packem_shared/QUEUES_FILENAME-16xcVWpo.mjs +0 -1
  60. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BMzr0ydt.mjs +0 -11
  61. package/dist/packem_shared/SHAPES_FILENAME-e82UBLBE.mjs +0 -1
  62. package/dist/packem_shared/WORKFLOWS_FILENAME-Bcfd76Wf.mjs +0 -1
  63. package/dist/packem_shared/attribution-JcwxPpyK.mjs +0 -1
  64. package/dist/packem_shared/capabilitiesUsedBy-CzqyN9dX.mjs +0 -1
  65. package/dist/packem_shared/chain-BTbLDrrU.mjs +0 -1
  66. package/dist/packem_shared/classify-procedure-call-OnJoKgqu.mjs +0 -1
  67. package/dist/packem_shared/context-property-calls-BqKN1GyT.mjs +0 -1
  68. package/dist/packem_shared/context-root-Dlht00NP.mjs +0 -1
  69. package/dist/packem_shared/discoverAuthApiCalls-0t3X09mV.mjs +0 -1
  70. package/dist/packem_shared/discoverCrons-BqTY53L5.mjs +0 -1
  71. package/dist/packem_shared/discoverFunctions-B-hkqNPG.mjs +0 -1
  72. package/dist/packem_shared/discoverHttpRoutes-8f8UnwQk.mjs +0 -1
  73. package/dist/packem_shared/discoverHyperdriveCalls-BRbwJcK7.mjs +0 -1
  74. package/dist/packem_shared/discoverInserts-6RcjS-YR.mjs +0 -1
  75. package/dist/packem_shared/discoverMaskProcedures-B8LgCQ2X.mjs +0 -1
  76. package/dist/packem_shared/discoverMigrations-De3uDJi0.mjs +0 -1
  77. package/dist/packem_shared/discoverNondeterministicCalls-XHRCA4rr.mjs +0 -1
  78. package/dist/packem_shared/discoverQueries-B0vvHwFI.mjs +0 -1
  79. package/dist/packem_shared/discoverR2sqlCalls-BQ90jfu3.mjs +0 -1
  80. package/dist/packem_shared/discoverRlsMetadata-BuGLdQWs.mjs +0 -1
  81. package/dist/packem_shared/discoverRlsProcedures-Cy8-Q0AP.mjs +0 -1
  82. package/dist/packem_shared/discoverSandboxUsage-Bjl8A_hj.mjs +0 -1
  83. package/dist/packem_shared/discoverSchema-Cd3iH6q5.mjs +0 -1
  84. package/dist/packem_shared/discoverStorageRulesMetadata-C6sTEVS5.mjs +0 -1
  85. package/dist/packem_shared/fingerprintSchemaSources-BzFVnBfa.mjs +0 -1
  86. package/dist/packem_shared/handler-reference-Dzp5GZ5p.mjs +0 -1
  87. package/dist/packem_shared/index-BxGykPbL.mjs +0 -1
  88. package/dist/packem_shared/listLunoraSourceFiles-DRes9d5p.mjs +0 -1
  89. package/dist/packem_shared/loadProjectConfig-CuGQsqYS.mjs +0 -1
  90. package/dist/packem_shared/modules-CsA-QVJ6.mjs +0 -1
  91. package/dist/packem_shared/parse-validator-B4mFs19C.mjs +0 -1
  92. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +0 -1
  93. package/dist/packem_shared/readServiceBindings-CnvEGOir.mjs +0 -1
  94. package/dist/packem_shared/unwrap-handler-return-D7E2TKkS.mjs +0 -1
@@ -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}from"./isTestPath-5ruOnRVA.mjs";import{r as B,p as V}from"./parse-validator-C2Osg6gv.mjs";import{R as q}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-Cb5ouVEK.mjs";const J=(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.`,U=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}},K=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:K(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=U(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},Z=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",G=(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.`)},W=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return G(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:Z(e.shardMode),vectorIndexes:[]}},X=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])=>W(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}},H=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},Q=e=>{const t=H(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:[]}}},Y=(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},ee=(e,t)=>{const n=Q(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Y(o,n);return typeof a!="object"||a===null?void 0:X(a)}catch{return}},te=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&&te.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ne=(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}},re=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.`,se=/^(?:sqlite_|_cf_|__)/u,ie=/__(?:agg|rank|geo|fts)_/u,oe=e=>se.test(e)||ie.test(e),ae=new Set(["cascade","restrict","set null"]),le=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"]),N=/^[A-Za-z_$][\w$]*$/u,S=(e,t)=>{if(le.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(q.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(oe(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&&ae.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"},Se=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"},ke=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ne(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")}},we=(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:Se(n[0])};break}case"source":{e.externalSource=ke(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,re(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))we(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(S(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},k=(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)?k(t,e):e,Ne=(e,t,n,s)=>{const r=k(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);S(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:k(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=ee(n,t);if(o){for(const a of o.bareTables)S(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"'),it=(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),w=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=w.find(p=>z.has(p.table));if(v)throw d(r,J(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:w}};export{it as default};
@@ -0,0 +1 @@
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-5ruOnRVA.mjs";import{w as d}from"./classify-procedure-call-DC_O3oNQ.mjs";import{e as m}from"./exported-procedure-chains-CmwqreGv.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};
@@ -835,6 +835,8 @@ interface LunoraConfig<Env extends object = object> {
835
835
  advisor?: { minSeverity?: "error" | "info" | "warn" };
836
836
  /** Receives this project's \`defineApp()\` builder and returns it — where a Vite-first app makes the builder calls its generated entry cannot derive. */
837
837
  app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
838
+ /** Codegen's source walk. \`exclude\` adds globs (relative to \`lunora/\`, e.g. \`"seed/**"\`) to skip on top of the built-in test-file patterns. A literal array of strings, for the same reason as \`target\`. */
839
+ codegen?: { exclude?: string[] };
838
840
  /** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
839
841
  remote?: boolean;
840
842
  /** Sibling Workers the app calls through service bindings — key → its folder and, for RPC, the exported \`WorkerEntrypoint\` class (\`rpc: false\` binds that class but calls it with plain \`fetch\`, without importing the service's sources). Becomes \`ctx.services.<key>\` in actions, a wrangler \`services[]\` entry, one \`lunora dev\` session and a services-first \`lunora deploy\`. Literals, for the same reason as \`target\`. */
@@ -1 +1 @@
1
- import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-JcwxPpyK.mjs";import{c as n}from"./classify-procedure-call-OnJoKgqu.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};
1
+ import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-B7i322L0.mjs";import{c as n}from"./classify-procedure-call-DC_O3oNQ.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-5ruOnRVA.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 @@
1
+ import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-5ruOnRVA.mjs";import{r as v,d as b}from"./attribution-B7i322L0.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 i}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-5ruOnRVA.mjs";import{b as m,d as p}from"./attribution-B7i322L0.mjs";import{t as d}from"./database-calls-B6ylmcGA.mjs";import{w as g,c as h}from"./classify-procedure-call-DC_O3oNQ.mjs";import{a as k}from"./project-config-file-Cb5ouVEK.mjs";const l=e=>{if(!(!i.isPropertyAssignment(e)&&!i.isShorthandPropertyAssignment(e)&&!i.isMethodDeclaration(e)&&!i.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=l(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.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(["findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=h(t);if(!r)return;const o=r.receiver?y(r.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:r.visibility}},E=(e,s)=>{const t=[];for(const r of u(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=f(s,r);for(const a of m(o)){const c=b(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
+ import{existsSync as h,statSync as P,readdirSync as A,realpathSync as C,lstatSync as k}from"node:fs";import{dirname as d,join as g,relative as w,sep as F,resolve as D,extname as N,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-Cb5ouVEK.mjs";import{findProjectConfigFile as O}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const X=/\.ts$/u,f=(e,t)=>w(e,t).split(F).join("/").replace(X,""),H=new Set(["_generated","node_modules"]),_=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),L=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,xe=e=>{const t=e.split("/");return L.test(t.at(-1)??"")||t.slice(0,-1).some(s=>_.has(s))},E=(e,t,s)=>t?H.has(e)||!s&&_.has(e):!s&&L.test(e),v=new Map,m=()=>!1,Y=e=>{const t=z(c=>O(c)??(h(g(c,"package.json"))||h(g(c,".git"))?V:void 0),{cwd:d(D(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(d(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const a=o?.exclude?.length?K(o.exclude):m;return v.set(t,{isExcluded:a,key:n}),a},q=(e,t,s)=>e==="schema.ts"&&t===s,G=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,a;try{o=A(e),a=C(e)}catch{return t}if(n.has(a))return t;n.add(a);for(const c of o){const u=g(e,c),l=G(u);l===void 0||r(c,w(s,u).split(F).join("/"),l.isDirectory())||(l.isDirectory()?R(u,t,s,n,r):l.isFile()&&N(c)===".ts"&&!q(c,e,s)&&t.push(u))}return t},T=(e,t={})=>{const s=t.includeSkipped??!1,n=s?m:Y(e);return R(e,[],e,new Set,(r,o,a)=>E(r,a,s)||n(o))},Q=["src/server","src/index.ts","src/worker.ts"],J=new Set([".ts",".tsx"]),b=(e,t=[])=>{let s;try{s=k(e)}catch{return t}if(s.isFile())return J.has(N(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=d(e),s=T(e).map(o=>({displayPath:f(e,o),filePath:o})),n=new Set(s.map(o=>o.filePath)),r=O(t);for(const o of[...Q.flatMap(a=>b(g(t,a))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),s.push({displayPath:f(t,o),filePath:o}));return s},ee=e=>Array.isArray(e),I=(e,t,s,n)=>{const r=[];for(const{displayPath:o,filePath:a}of t){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a);for(const u of c.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:f(e,t),filePath:t})),se=(e,t,s,n)=>I(e,te(t),s,n),Se=(e,t,s)=>se(e,t,p.CallExpression,s),he=(e,t,s)=>I(e,Z(t),p.CallExpression,s),ve=e=>U(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(s=>!i.isSpreadAssignment(s)&&B(s)===t),ye=(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},Pe=(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()),Ae=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},ae=(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=>ae(e).root,Fe=(e,t)=>e?.compilerNode===t.compilerNode,Ne=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},Oe=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},_e=e=>{const t=x(e);return t&&i.isCallExpression(t)?t:void 0},Le=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},Re=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Te=(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},ce=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},be=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)?ce(e):void 0},Ie=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"]),Ce=new Set(["run","runAction","runMutation","runQuery"]),ke=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};export{Ce as RUN_METHODS,X as TS_EXTENSION_RE,ve as bindingKeyName,we as chainRootOf,Se as collectCallRows,se as collectNodeRows,he as collectSecurityCallRows,Le as defaultExportExpression,S as findObjectProperty,ke as functionReferenceSegments,ye as handlerOf,ie as isConstDeclaration,Fe as isSameNode,xe as isTestPath,y as isWriteTarget,Re as limitNameOf,T as listLunoraSourceFiles,Z as listSecurityScanFiles,f as lunoraRelativePath,Ne as memberAccessOf,be as objectLiteralFromCallbackBody,Ae as optionsObjectLiteral,ne as outermostValueWrapper,Pe as propertyInitializer,B as propertyKeyName,U as propertyNameText,Oe as returningFunctionOf,Ie as stringPropertyFor,Te as stringPropertyOf,re as symbolConstInitializer,x as unwrapExpression,_e as unwrapToCallExpression,ae as walkChain};
@@ -0,0 +1 @@
1
+ import{l as e,r as f}from"./project-config-file-Cb5ouVEK.mjs";import{PROJECT_CONFIG_FILENAMES as t,findProjectConfigFile as a}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";export{t as PROJECT_CONFIG_FILENAMES,a as findProjectConfigFile,e as loadProjectConfig,f as readProjectConfigLiterals};
@@ -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{s as g}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-5ruOnRVA.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 n,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as v}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as E}from"./project-config-file-Cb5ouVEK.mjs";let f;const j=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"]),L=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&&n.isShorthandPropertyAssignment(r)){const i=r.getValueSymbol();r=(i?.getAliasedSymbol()??i)?.getValueDeclaration()}if(!(r===void 0||!n.isVariableDeclaration(r)))return r.getInitializer()},T=e=>{const t=e.getParent();return!n.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===h.Const},u=e=>{if(n.isParenthesizedExpression(e)||n.isAsExpression(e)||n.isSatisfiesExpression(e))return u(e.getExpression());if(n.isObjectLiteralExpression(e))return e;if(n.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),i=r!==void 0&&n.isPropertyAssignment(r)?r.getInitializer():void 0;return i===void 0?void 0:u(i)}if(!n.isIdentifier(e)||l.has(e))return;const t=S(e);if(!(t===void 0||!T(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},w="v",D=e=>{if(n.isIdentifier(e))return!0;let t=e;for(;n.isCallExpression(t);){const r=t.getExpression();if(!n.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return n.isIdentifier(t)&&t.getText()===w},c=e=>{if(n.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 n.isCallExpression(e)?P(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 b(t)}finally{g.delete(t)}},b=e=>{const t={};for(const r of e.getProperties()){if(n.isSpreadAssignment(r)){Object.assign(t,R(r));continue}const i=n.isShorthandPropertyAssignment(r);if(!i&&!n.isPropertyAssignment(r))continue;const o=r.getNameNode();if(n.isComputedPropertyName(o))continue;const a=i?r.getNameNode():r.getInitializer();if(!a)continue;const s=E(r);if(!A.test(s))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(s)}`);t[s]=c(a)}return t},d=(e,t)=>e&&n.isExpression(e)?c(e):t,V=e=>e===void 0?"undefined":n.isStringLiteral(e)||n.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}},x=(e,t,r)=>{if(N.has(e))return{kind:e};const[i,o]=t;switch(e){case"array":return{inner:d(i,{kind:"any"}),kind:"array"};case"from":return O(i);case"id":{if(!i||!n.isStringLiteral(i))throw v(i??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${i?i.getText():"no argument"}.`);return{kind:"id",tableName:i.getLiteralText()}}case"literal":return{kind:"literal",literalValue:V(i)};case"object":return i&&n.isObjectLiteralExpression(i)?{kind:"object",shape:b(i)}:{kind:"object",shape:{}};case"optional":return{inner:d(i,{kind:"any"}),kind:"optional"};case"record":return{keyType:d(i,{kind:"string"}),kind:"record",valueType:d(o,{kind:"any"})};case"storage":return i&&n.isStringLiteral(i)?{bucket:i.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>n.isExpression(a)).map(a=>c(a))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},M=e=>{const[t]=e;if(e.length!==1||t===void 0||!n.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},P=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),i=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const o=t.getExpression(),a=n.isExpression(o)?c(o):{kind:"any"};if(p.has(r))return k(a,r);if(!m.has(r))return a;const s=r==="max"&&a.kind==="string"?M(i):void 0;return s!==void 0?{...a,hasRefinement:!0,stringMaxLength:Math.min(a.stringMaxLength??s,s)}:{...a,hasRefinement:!0,unmodelledRefinement:!0}}return x(r,i,e)};export{c as a,b as p,u as r,j as s};
@@ -0,0 +1 @@
1
+ import{statSync as x,readFileSync as y}from"node:fs";import{basename as S}from"node:path";import{createJiti as E}from"jiti";import{Node as i,Project as P}from"ts-morph";import{findProjectConfigFile as b}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const h=t=>{if(i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)||i.isNumericLiteral(t))return t.getLiteralText();if(i.isComputedPropertyName(t)){const r=t.getExpression();if(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))return r.getLiteralText()}return t.getText()},c=t=>h(t.getNameNode()),f=new Map,k=async t=>{const r=b(t);if(r===void 0)return{};let e;try{const a=x(r);e=`${String(a.mtimeMs)}:${String(a.size)}`}catch{return{}}const n=f.get(r);if(n?.key===e)return n.value;const s=(async()=>{try{const o=(await E(r,{interopDefault:!1,moduleCache:!1}).import(r))?.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(r,{key:e,value:s}),s},A=t=>{let e=t.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=t.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},d=(t,r)=>i.isPropertyAssignment(t)?t.getInitializer():r.getVariableDeclaration(c(t))?.getInitializer(),g=t=>{let r=t;for(;r!==void 0&&(i.isSatisfiesExpression(r)||i.isAsExpression(r)||i.isParenthesizedExpression(r));)r=r.getExpression();return r},v=(t,r,e)=>{const n=g(t);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=>c(u)===e);if(o===void 0)return{absent:!0};const l=d(o,r);return l===void 0?{unreadable:!0}:{literal:l}},j=(t,r)=>{const e=v(t,r,"minSeverity");return"absent"in e?{advisor:{}}:"literal"in e&&i.isStringLiteral(e.literal)?{advisor:{minSeverity:e.literal.getLiteralValue()}}:{advisor:{unreadable:!0}}},N=(t,r)=>{const e=v(t,r,"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=new Map([["advisor",{advisor:{unreadable:!0}}],["codegen",{codegen:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),L=(t,r)=>{const e=t.getProperty(r);if(e!==void 0)return(i.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},m=(t,r)=>{const e=L(t,r);if(e!==void 0)return e!=="unreadable"&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},z=t=>{const r=L(t,"rpc");if(r!==void 0)return r!=="unreadable"&&i.isFalseLiteral(r)?!1:"unreadable"},C=t=>{const r=g(t);if(r===void 0||!i.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const n of r.getProperties()){if(!i.isPropertyAssignment(n)||i.isComputedPropertyName(n.getNameNode()))return{services:{unreadable:!0}};const s=g(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=z(s);if(typeof a!="string"||o===!1||l==="unreadable")return{services:{unreadable:!0}};e[c(n)]={dir:a,...o===void 0?{}:{entrypoint:o},...l===void 0?{}:{rpc:l}}}return{services:{declared:e}}},T=(t,r)=>{if(i.isGetAccessorDeclaration(t)||i.isMethodDeclaration(t))return w.get(c(t))??{};if(!i.isPropertyAssignment(t)&&!i.isShorthandPropertyAssignment(t))return{};const e=c(t);if(e==="advisor")return j(d(t,r),r);if(e==="services")return C(d(t,r));if(e==="codegen")return N(d(t,r),r);if(e!=="target"&&e!=="remote")return{};const n=d(t,r);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}},F=t=>{const r=b(t);if(r===void 0)return{};let e;try{e=y(r,"utf8")}catch{return{unreadable:!0}}const s=new P({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(S(r),e,{overwrite:!0}),a=A(s);if(a===void 0)return{unreadable:!0};if(a.getProperties().some(l=>i.isSpreadAssignment(l))){const l=u=>a.getProperties().some(p=>!i.isSpreadAssignment(p)&&c(p)===u);return{...l("advisor")?{advisor:{unreadable:!0}}:{},...l("codegen")?{codegen:{unreadable:!0}}:{},...l("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let o={};for(const l of a.getProperties())o={...o,...T(l,s)};return o};export{c as a,k as l,h as p,F 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-Cb5ouVEK.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
+ import{Node as l,SyntaxKind as g}from"ts-morph";import{lunoraRelativePath as L}from"./isTestPath-5ruOnRVA.mjs";import{posix as D}from"node:path";let S,v;const Ae=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Te=e=>{S?.push(...e)},j=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},w=(e,t)=>{S?.push({exportName:j(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Ne=e=>{v!==void 0&&w(v,e)},xe=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},k=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},De=(e,t)=>{const n=new Map;for(const r of e){const s=k(r,L(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},P=/\bany\b(?!\s*(?:\?\s*)?:)/u,U=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,O=e=>P.test(e.replaceAll(U,"")),K="/_generated/",B=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},F=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,T=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=F.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},h=new WeakMap,V=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=h.get(n.compilerSymbol);return r===void 0&&(r=new Map,h.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},_=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),W=(e,t,n)=>e.getModuleSpecifierValue()===t&&_(e,n)?n:void 0,q=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},G=(e,t,n)=>{if(!_(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:V(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},X=/^\.\.?(?:$|\/)/u,H=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),Y=(e,t)=>{const n=t.getModuleSpecifierValue();if(!X.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:H.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${D.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=D.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},J=(e,t,n)=>{const r=T(t);for(const s of e.getImportDeclarations()){const i=r===void 0?q(s,t)??G(s,t,n):W(s,r,n);if(i!==void 0)return{exportName:i,specifier:Y(e,s)??s.getModuleSpecifierValue()}}},z=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),m={kind:"verbatim"},p={kind:"expand"},Q=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),Z=e=>T(e)!==void 0||l.isExportable(e)&&e.isExported(),ee=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),M=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&T(e)===void 0||!Q.has(e.getKind()))return m;const i=s.getFilePath();if(i.includes(K))return m;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const a=J(t.getSourceFile(),o,o.getName());return a===void 0?Z(o)||!ee(r(),o.getName())?m:p:z(a.specifier,t)?p:{kind:"qualify",qualified:a}},te=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),I=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},ne=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},re=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=ne(s);return i===void 0||!I(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>te.has(s.getKind()))&&!I(r)&&t().startsWith("typeof ")},R=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=M(u,t,n,c);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||re(e,c)?p:m},se=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return m;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=M(a,t,n,()=>i.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?p:m},oe=/^[A-Za-z_$][\w$]*$/u,ie=e=>oe.test(e)?e:JSON.stringify(e),$=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},y=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),E=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),R(e,t,n).kind!=="verbatim"||$(e).some(s=>E(s,t,n,r))?!0:y(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>se(i,t,n).kind!=="verbatim")?!0:E(s.getTypeAtLocation(t),t,n,r)):!1),ae=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},C=(e,t)=>e!==void 0&&(y(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,ce=32,ue=8,le=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),a=o?i(o,t,n,r,s):void 0;if(a!==void 0)return`${C(o,a)}[]`},ge=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getUnionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(c)}return o.join(" | ")},de=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getIntersectionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(C(a,c))}return o.join(" & ")},me=(e,t,n,r,s,i)=>{if(!y(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ae(a,c),d=u&&c.isUnion()?c.getUnionTypes().filter(A=>!A.isUndefined()):[c],N=[];for(const A of d){const x=i(A,t,n,r+1,s);if(x===void 0)return;N.push(x)}o.push(`${ie(a.getName())}${u?"?":""}: ${N.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},fe=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},pe=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),b=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>ce)return!0;const i=new Set(r).add(e);if($(e).some(u=>b(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return b(o,t,n+1,i,s);if(B(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=y(e)&&e.getProperties().some(u=>b(u.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},Se=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(c,n,r,s+1,i);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},ve=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),f=(e,t,n,r,s)=>{if(r>ue||s.has(e))return;const i=R(e,t,n);if(i.kind==="verbatim"&&!E(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!pe(e)){if(e.isEnumLiteral())return fe(e);if(i.kind==="qualify"&&!ve(e)){const a=Se(i.qualified,e,t,n,r,o,f);if(a!==void 0)return a}return e.isArray()?le(e,t,n,r,o,f):e.isUnion()?ge(e,t,n,r,o,f):e.isIntersection()?de(e,t,n,r,o,f):me(e,t,n,r,o,f)}},he=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const i=n.getText(e);if(!i||i==="any"||i==="never"||O(i)||b(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();if(E(n,e,o)){const a=f(n,e,o,0,new Set);return a===void 0&&w(e,i),a??"unknown"}return i};export{E as a,Ne as b,Ae as c,De as d,f as e,O as i,xe as p,Te as r,he as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.265",
3
+ "version": "1.0.0-alpha.266",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -55,6 +55,7 @@
55
55
  "@lunora/scheduler": "1.0.0-alpha.110",
56
56
  "@lunora/values": "1.0.0-alpha.60",
57
57
  "@lunora/workflow": "1.0.0-alpha.71",
58
+ "@visulima/fs": "6.0.28",
58
59
  "jiti": "^2.7.0",
59
60
  "quicktype-core": "^26.0.0",
60
61
  "ts-morph": "^28.0.0"
@@ -1 +0,0 @@
1
- import{existsSync as p}from"node:fs";import{join as f}from"node:path";import{agentDefaultName as d,agentClassName as b,voiceBindingName as N,voiceClassName as y}from"@lunora/agent/naming";import{LunoraError as g}from"@lunora/errors";import{Node as a,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as A,findObjectProperty as c,stringPropertyFor as w}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{a as h}from"./attribution-JcwxPpyK.mjs";const E="agents.ts",v=o=>{const n=o.getSymbol();if(!n)return o.getText()==="defineAgent";for(const e of n.getDeclarations())if(a.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/agent"?!1:e.getNameNode().getText()==="defineAgent";return!1},P=w("agent"),x=(o,n,e)=>{if(o.getKind()===u.TrueKeyword)return!0;if(o.getKind()===u.FalseKeyword)return!1;throw l(o,`agent "${n}": \`${e}\` must be a static boolean literal — it is deploy configuration codegen writes into the ctx.agents wiring spec`)},I=(o,n)=>{const e=o.getArguments()[0];if(!e||!a.isObjectLiteralExpression(e))throw l(o,`agent "${n}": defineAgent must be passed an inline object literal`);const t={className:b(n),exportName:n,name:d(n)},i=c(e,"name");i&&a.isPropertyAssignment(i)&&(t.name=P(i.getInitializerOrThrow(),n,"name"));const r=c(e,"publicRun");r&&a.isPropertyAssignment(r)&&x(r.getInitializerOrThrow(),n,"publicRun")&&(t.publicRun=!0);const s=c(e,"voice");if(s&&a.isPropertyAssignment(s)){const m=s.getInitializerOrThrow();if(!a.isObjectLiteralExpression(m))throw l(m,`agent "${n}": \`voice\` must be an inline object literal — its presence tells codegen to emit the voice-session Durable Object`);t.voice=!0,t.voiceBindingName=N(n),t.voiceClassName=y(n)}return c(e,"onEmail")&&(t.onEmail=!0),t},S=o=>{const n=[];for(const e of o.getVariableDeclarations()){const t=A(e.getInitializer());if(!t)continue;const i=t.getExpression();if(!a.isIdentifier(i)||!v(i))continue;const r=e.getNameNode();if(!a.isIdentifier(r)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw l(r,"defineAgent exports must be plain named exports (no destructuring)")}const s=h(e,"binding");s!==void 0&&n.push(I(t,s))}return n},T=o=>{const n=new Map,e=new Map;for(const t of o){const i=n.get(t.name);if(i!==void 0)throw new g("DUPLICATE_AGENT_NAME",`Duplicate agent name "${t.name}": produced by both "${i}" and "${t.exportName}". Deployed agent names must be unique across the project.`,{status:500});n.set(t.name,t.exportName);const r=e.get(t.className);if(r!==void 0)throw new g("DUPLICATE_AGENT_CLASS",`Duplicate agent class "${t.className}": produced by both "${r}" and "${t.exportName}". Agent export names must yield unique generated class names.`,{status:500});e.set(t.className,t.exportName)}},z=(o,n)=>{const e=f(n,E);if(!p(e))return[];const t=o.getSourceFile(e)??o.addSourceFileAtPath(e),i=S(t);return i.sort((r,s)=>r.exportName.localeCompare(s.exportName)),T(i),i};export{E as AGENTS_FILENAME,z as discoverAgents};
@@ -1 +0,0 @@
1
- import{existsSync as T}from"node:fs";import{join as j}from"node:path";import{containerClassName as I,containerBindingName as A,DURABLE_OBJECT_POLICY_FORBIDDEN_KEYS as O,isManagedImage as k,isCloudflareRegistryDigest as C,normalizeContainerImage as m}from"@lunora/container";import{SyntaxKind as S,Node as s}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as b,stringPropertyFor as _,findObjectProperty as p,symbolConstInitializer as D,outermostValueWrapper as w,isWriteTarget as M}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{a as F}from"./attribution-JcwxPpyK.mjs";const V="containers.ts",K=t=>{const e=t.getSymbol();if(!e)return t.getText()==="defineContainer";for(const i of e.getDeclarations())if(s.isImportSpecifier(i))return i.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/container"?!1:i.getNameNode().getText()==="defineContainer";return!1},d=_("container"),y=(t,e,i)=>{if(s.isNumericLiteral(t))return t.getLiteralValue();throw a(t,`container "${e}": \`${i}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},$=(t,e)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return m(t.getLiteralValue());if(s.isObjectLiteralExpression(t)){const i=p(t,"registry");if(i&&s.isPropertyAssignment(i)){const r=i.getInitializerOrThrow();return m({registry:d(r,e,"image.registry")})}const n=p(t,"build");if(n&&s.isPropertyAssignment(n)){const r=n.getInitializerOrThrow();return m({build:d(r,e,"image.build")})}}throw a(t,`container "${e}": \`image\` must be a static string path, { registry: "…" }, or { build: "…" } literal`)},B=new Set(["buildArgs","image","images","instanceType","maxInstances","name","rollout","sandbox","schedulingPolicy"]),R=new Set(["gracePeriodSeconds","stepPercentage"]),E=t=>{let e=t;for(;s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isTypeAssertion(e)||s.isParenthesizedExpression(e);)e=e.getExpression();return e},U=(t,e)=>e.getDescendantsOfKind(S.Identifier).some(i=>{if(i.getSymbol()!==t)return!1;let n=w(i),r=n.getParent();if(s.isCallExpression(r)&&r.getExpression().getText()==="Object.assign")return r.getArguments()[0]===n;for(;(s.isPropertyAccessExpression(r)||s.isElementAccessExpression(r))&&r.getExpression()===n;){if(M(r))return!0;n=w(r),r=n.getParent()}return!1}),z=16,L=(t,e,i,n)=>{let r={name:i,symbol:t},o;for(let c=0;c<z;c+=1){const l=D(r.symbol);if(l===void 0||!s.isExpression(l))return o;if(o=E(l),s.isObjectLiteralExpression(o)&&r.symbol!==void 0&&U(r.symbol,e.getSourceFile()))throw a(e,`${n}: \`${r.name}\` is a const object that is written to elsewhere in this file, so its initializer is not the value the container runs with. Declare the settings where they are final.`);if(!s.isIdentifier(o))return o;r={name:o.getText(),symbol:o.getSymbol()}}return o},P=(t,e)=>{const i=E(t);return s.isIdentifier(i)?L(i.getSymbol(),i,i.getText(),e)??i:i},N=t=>{const e=t.getNonNullableType();return(e.isUnion()?e.getUnionTypes():[e]).flatMap(n=>n.getApparentType().getProperties().map(r=>r.getName()))},Y=(t,e,i)=>{const n=t.getExpression().getType(),r=e==="every"||n.isAny()||n.isUnknown()?["its keys"]:[...new Set(N(n))].filter(o=>e.has(o)).map(o=>`\`${o}\``);if(r.length>0)throw a(t,`${i}: this spread can set ${r.join(", ")}, which codegen writes into wrangler.jsonc and so must read statically. Spread a module-scope \`const\` object literal, or write the keys inline.`)},W=(t,e,i)=>{const n=b(t),r=s.isShorthandPropertyAssignment(t)?L(t.getValueSymbol(),t,n,i):void 0;if(r!==void 0)return[n,r];if(e==="every"||e.has(n))throw a(t,`${i}: \`${n}\` is deploy configuration codegen writes into wrangler.jsonc, so it must be a static literal — inline it, or name a module-scope \`const\` initialized with one.`)},f=(t,e,i,n=new Set)=>{const r=[],o=new Set(n).add(t);for(const c of t.getProperties())if(s.isPropertyAssignment(c))r.push([b(c),P(c.getInitializerOrThrow(),i)]);else if(s.isSpreadAssignment(c))r.push(...q(c,e,i,o));else{const l=W(c,e,i);l!==void 0&&r.push(l)}return r},q=(t,e,i,n)=>{const r=P(t.getExpression(),i);if(!s.isObjectLiteralExpression(r))return Y(t,e,i),[];if(n.has(r))throw a(t,`${i}: this spread refers back to an object it is part of, so it has no static value.`);return f(r,e,i,n)},x=(t,e)=>{if(!s.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`buildArgs\` must be a static object literal — it is deploy configuration codegen writes into wrangler.jsonc`);const i={};for(const[n,r]of f(t,"every",`container "${e}" buildArgs`))i[n]=d(r,e,`buildArgs.${n}`);return Object.keys(i).length>0?i:void 0},H=(t,e)=>{if(!s.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`rollout\` must be a static object literal — it is deploy configuration codegen writes into wrangler.jsonc`);const i={};for(const[n,r]of f(t,R,`container "${e}" rollout`))(n==="gracePeriodSeconds"||n==="stepPercentage")&&(i[n]=y(r,e,`rollout.${n}`));return i.gracePeriodSeconds===void 0&&i.stepPercentage===void 0?void 0:i},v=t=>{if(s.isTrueLiteral(t))return!0;if(s.isFalseLiteral(t))return!1},J=t=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isNumericLiteral(t))return t.getLiteralValue()},X=(t,e)=>{if(s.isStringLiteral(t))return t.getLiteralValue();if(s.isObjectLiteralExpression(t)){const i={};for(const n of t.getProperties()){if(!s.isPropertyAssignment(n))throw a(n,`container "${e}": \`instanceType\` must be an object of static number literals`);const r=b(n);if(r!=="diskMb"&&r!=="memoryMib"&&r!=="vcpu")throw a(n,`container "${e}": unknown \`instanceType\` field "${r}" — expected vcpu, memoryMib, or diskMb`);i[r]=y(n.getInitializerOrThrow(),e,`instanceType.${r}`)}return i}throw a(t,`container "${e}": \`instanceType\` must be a static string or { vcpu, memoryMib, diskMb } literal`)},G=(t,e)=>{if(!s.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`images\` must be a static object literal — codegen writes it into wrangler.jsonc`);const i={};for(const[n,r]of f(t,"every",`container "${e}" images`)){const o=$(r,e);if(o.kind==="build")throw a(r,`container "${e}": \`images["${n}"]\` cannot be a Railpack { build } source — use a Dockerfile path or a { registry } reference`);if(o.kind==="registry"&&!C(o.reference))throw a(r,`container "${e}": \`images["${n}"].registry\` must be a digest-pinned (@sha256) reference under registry.cloudflare.com — push other registries' images there first`);i[n]=o}return i},Q=(t,e)=>{const i=t.findLast(([r])=>r==="schedulingPolicy");if(i===void 0)return;const n=d(i[1],e,"schedulingPolicy");if(n!=="default"&&n!=="durable_object")throw a(i[1],`container "${e}": unknown \`schedulingPolicy\` "${n}" — use "default" or "durable_object"`);return n==="durable_object"?n:void 0},Z=(t,e,i,n)=>{if(i!==void 0&&O.includes(t))throw a(e,`container "${n}": \`${t}\` is not supported with schedulingPolicy "durable_object"`);if(i===void 0&&t==="images")throw a(e,`container "${n}": \`images\` needs schedulingPolicy "durable_object"`)},ee=(t,e,i,n)=>{const{base:r,policy:o}=i;switch(t){case"buildArgs":{r.buildArgs=x(e,n);break}case"enableInternet":{r.enableInternet=v(e);break}case"image":{i.scheduled||(o.image=$(e,n));break}case"images":{o.images=G(e,n);break}case"instanceType":{r.instanceType=X(e,n);break}case"maxInstances":{o.maxInstances=y(e,n,"maxInstances");break}case"name":{r.name=d(e,n,"name");break}case"rollout":{o.rollout=H(e,n);break}case"sandbox":{const c=v(e);if(c===void 0)throw a(e,`container "${n}": \`sandbox\` must be a static true/false literal`);r.sandbox=c;break}case"sleepAfter":{r.sleepAfter=J(e);break}}},te=(t,e,i)=>{const n=t.findLast(([o])=>o==="image")?.[1];if(n===void 0||!(s.isStringLiteral(n)||s.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();if(!Object.hasOwn(e??{},r)&&!k(r))throw a(n,`container "${i}": \`image\` "${r}" must name an entry of \`images\` or a Cloudflare-managed "cloudflare/…" image`)},ne=(t,e)=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))throw a(t,`container "${e}": defineContainer must be passed an inline object literal`);const n=f(i,B,`container "${e}"`),r=Q(n,e),o={base:{bindingName:A(e),className:I(e),exportName:e},policy:{},scheduled:r!==void 0};for(const[g,u]of n)Z(g,u,r,e),ee(g,u,o,e);const{base:c,policy:l}=o;if(r==="durable_object")return te(n,l.images,e),{...c,...l.images===void 0?{}:{images:l.images},schedulingPolicy:r};if(l.image===void 0)throw a(i,`container "${e}": defineContainer requires a static \`image\` property`);return{...c,image:l.image,...l.maxInstances===void 0?{}:{maxInstances:l.maxInstances},...l.rollout===void 0?{}:{rollout:l.rollout}}},ie=t=>{const e=[],i=new Map;for(const n of t.getVariableDeclarations()){const r=n.getInitializer();if(r?.getKind()!==S.CallExpression)continue;const o=r,c=o.getExpression();if(!s.isIdentifier(c)||!K(c))continue;const l=n.getNameNode();if(!s.isIdentifier(l)){if(n.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw a(l,"defineContainer exports must be plain named exports (no destructuring)")}const g=F(n,"binding");if(g===void 0)continue;const u=ne(o,g),h=i.get(u.bindingName);if(h!==void 0)throw a(l,`containers "${h}" and "${u.exportName}" both map to the binding ${u.bindingName} — rename one so each container gets its own Durable Object binding`);i.set(u.bindingName,u.exportName),e.push(u)}return e},ge=(t,e)=>{const i=j(e,V);if(!T(i))return[];const n=t.getSourceFile(i)??t.addSourceFileAtPath(i),r=ie(n);return r.sort((o,c)=>o.exportName.localeCompare(c.exportName)),r};export{V as CONTAINERS_FILENAME,ge as discoverContainers};
@@ -1 +0,0 @@
1
- import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as b}from"@lunora/platform";import{readProjectConfigLiterals as g}from"./loadProjectConfig-CuGQsqYS.mjs";const d="cloudflare",v=t=>{const{target:e}=g(t);return e!==void 0&&e.length>0?e:void 0},A=(t,e)=>e??v(t)??d,L=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=g(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${d}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${d}" }\`), or pass \`--target\`.`,target:d}]},u={celld:b,cloudflare:h,node:f},C=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),S={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:null},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","services","topics","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],m={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},y=(t,e,a)=>({level:"error",message:`${e.name} does not support ${m[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${m[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),k=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:c,target:i}=t;for(const s of w){if(c[s]!==!0)continue;const o=r.features[s]?.level;o!=="unsupported"&&o!==void 0||(a[s]=!1,!n.has(s)&&e.push(o==="unsupported"?y(s,r,i):T(s,r,i)))}},_=(t,e,a,r={})=>{const n={...t},c={...r},i=[],s=new Set;for(const[o,l]of Object.entries(S)){if(l===null||!t[o])continue;const p=e.features[l]?.level;p==="unsupported"?(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${l}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${l}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return k({diagnostics:i,gatedSignals:c,matrix:e,reported:s,signals:r,target:a}),{diagnostics:i,signals:c,usage:n}},E=(t,e,a={})=>{const r=u[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],signals:{...a},usage:{...t}}:_(t,r,e,a)},I=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{S as CAPABILITY_TO_FEATURE,d as DEFAULT_TARGET,_ as gateAgainstMatrix,E as gatePlatformFeatures,C as platformMatrixIds,v as readProjectTarget,L as readTargetDiagnostics,A as resolveCodegenTarget,I as studioPlatformFor};
@@ -1 +0,0 @@
1
- import{existsSync as l}from"node:fs";import{join as p}from"node:path";import{Node as t}from"ts-morph";import{defaultExportExpression as g,propertyInitializer as f,findObjectProperty as c}from"./listLunoraSourceFiles-DRes9d5p.mjs";const d="flags.ts",u=new Set(["@lunora/flags/providers/flagship","lunorash/flags/flagship"]),m=e=>{const i=e.getSymbol();if(!i)return e.getText()==="flagshipProvider";for(const r of i.getDeclarations())if(t.isImportSpecifier(r))return u.has(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="flagshipProvider":!1;return!1},v=(e,i)=>{const r=c(e,i);if(!r||!t.isPropertyAssignment(r))return;const o=r.getInitializerOrThrow();if(t.isStringLiteral(o)||t.isNoSubstitutionTemplateLiteral(o))return o.getLiteralValue()},h=e=>{const i=e.getArguments()[0];if(i&&t.isObjectLiteralExpression(i)){const r=v(i,"binding");if(r!==void 0&&r.length>0)return{bindingName:r,mode:"binding",provider:"flagship"}}return{mode:"http",provider:"flagship"}},S=e=>f(e.getArguments()[0],"provider"),b=(e,i)=>{const r=p(i,d);if(!l(r))return;const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=g(o);if(!n||!t.isCallExpression(n))return{provider:"custom"};const s=S(n);if(s&&t.isCallExpression(s)){const a=s.getExpression();if(t.isIdentifier(a)&&m(a))return h(s)}return{provider:"custom"}};export{d as FLAGS_FILENAME,b as discoverFlags};
@@ -1 +0,0 @@
1
- import{existsSync as E}from"node:fs";import{join as y}from"node:path";import{Node as o,SyntaxKind as l}from"ts-morph";import{diagnosticAt as I}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as M}from"./module-specifiers-WF8iAydP.mjs";import{p as A}from"./parse-validator-B4mFs19C.mjs";import{findObjectProperty as c,unwrapExpression as d,isConstDeclaration as P}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{j as D,i as b,f as g,d as O}from"./attribution-JcwxPpyK.mjs";import{u as w}from"./unwrap-handler-return-D7E2TKkS.mjs";const z="mutators.ts",x=M,h=r=>{const e=r.getSymbol();if(!e)return r.getText()==="defineMutator";for(const t of e.getDeclarations())if(o.isImportSpecifier(t))return x(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMutator":!1;return!1},C=r=>{const e=r.getSymbol();if(!e)return!1;for(const t of e.getDeclarations()){if(!o.isNamespaceImport(t))continue;const i=t.getFirstAncestorByKind(l.ImportDeclaration);return i!==void 0&&x(i.getModuleSpecifierValue())}return!1},N=r=>{if(o.isIdentifier(r))return h(r);if(o.isPropertyAccessExpression(r)){const e=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(e)&&C(e)}return!1},S=r=>{const e=r.getArguments()[0];return e&&o.isObjectLiteralExpression(e)?e:void 0},m=new WeakMap,p=r=>{let e=m.get(r.compilerNode);if(e===void 0){const t=r.getNameNode(),i=t?.getText();e=r.getSourceFile().getDescendantsOfKind(l.Identifier).filter(s=>s!==t&&s.getText()===i&&g(s)?.compilerNode===r.compilerNode).length===1&&O(r)===void 0,m.set(r.compilerNode,e)}return e},f=r=>{const e=o.isIdentifier(r)?g(r):void 0,t=o.isSourceFile(e?.getParent())||o.isSourceFile(e?.getParent()?.getParent()?.getParent());if(e===void 0||e.getSourceFile()!==r?.getSourceFile()||!t)return;if(o.isFunctionDeclaration(e))return e.hasBody()&&p(e)?e:void 0;const i=P(e)?d(e.getInitializer()):void 0;return(o.isArrowFunction(i)||o.isFunctionExpression(i))&&o.isVariableDeclaration(e)&&p(e)?i:void 0},G=r=>{const e=r.getInitializer();if(!o.isCallExpression(e)||!N(e.getExpression()))return;const t=c(S(e),"server");if(o.isMethodDeclaration(t))return t;if(o.isShorthandPropertyAssignment(t))return f(t.getNameNode());const i=o.isPropertyAssignment(t)?d(t.getInitializer()):void 0;return o.isArrowFunction(i)||o.isFunctionExpression(i)?i:f(i)},T=r=>{const e=c(r,"args");if(!e||!o.isPropertyAssignment(e))return{};const t=e.getInitializer();return t&&o.isObjectLiteralExpression(t)?A(t):{}},L=r=>{const e=c(r,"server");if(!e||!o.isPropertyAssignment(e))return"unknown";const t=e.getInitializer();return!t||!(o.isArrowFunction(t)||o.isFunctionExpression(t))?"unknown":w(t)},j=r=>{const e=c(r,"owner");if(!e||!o.isPropertyAssignment(e))return;const t=e.getInitializer();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0},R=r=>{const e=[];for(const t of r.getVariableDeclarations()){if(!t.isExported())continue;const i=t.getInitializer();if(i?.getKind()!==l.CallExpression)continue;const n=i,s=n.getExpression();if(!N(s))continue;const a=t.getNameNode();if(!o.isIdentifier(a))throw I(a,"defineMutator exports must be plain named exports (no destructuring)");const u=S(n);for(const v of D(t).filter(F=>b(F)))e.push({args:T(u),exportName:v,filePath:"mutators",line:n.getStartLineNumber(),owner:j(u),returnType:L(u)})}return e},J=(r,e)=>{const t=y(e,z);if(!E(t))return[];const i=r.getSourceFile(t)??r.addSourceFileAtPath(t),n=R(i);return n.sort((s,a)=>s.exportName.localeCompare(a.exportName)),n};export{z as MUTATORS_FILENAME,J as discoverMutators,N as isDefineMutatorCallee,S as mutatorLiteral,G as mutatorServerImplOf};
@@ -1 +0,0 @@
1
- import{existsSync as P}from"node:fs";import{join as S}from"node:path";import{SyntaxKind as l,Node as f}from"ts-morph";import{listLunoraSourceFiles as p,lunoraRelativePath as y,defaultExportExpression as E,findObjectProperty as d,handlerOf as g}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{b as N,d as v}from"./attribution-JcwxPpyK.mjs";import{i as a}from"./context-root-Dlht00NP.mjs";import{c as F}from"./classify-procedure-call-OnJoKgqu.mjs";const O="notify.ts",A=new Set(["chat","inApp","send","webhook"]),h=new Set(["broadcast","send"]),b=e=>{const t=e.getInitializer();if(!t||!f.isCallExpression(t))return;const o=F(t);if(!o)return;const r=g(t,o.receiver);return r?{exportName:v(e)??e.getName(),handler:r,kind:o.kind}:void 0},m=e=>{const t=[];for(const o of N(e)){const r=b(o);r&&t.push(r)}return t},x=e=>a(e,["notify"])?"notify":a(e,["push"])||a(e,["notify","push"])?"push":void 0,k=e=>{if(!f.isPropertyAccessExpression(e))return;const t=e.getName(),o=x(e.getExpression());if(o==="notify"&&A.has(t))return`ctx.notify.${t}`;if(o==="push"&&h.has(t))return`ctx.push.${t}`},C=e=>f.isPropertyAccessExpression(e)?x(e.getExpression())==="push"&&h.has(e.getName()):!1,M=(e,t)=>{const o=[];for(const r of p(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=y(t,r);for(const s of m(n))if(!(s.kind!=="query"&&s.kind!=="mutation"))for(const i of s.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const u=k(i);u!==void 0&&o.push({callee:u,exportName:s.exportName,file:c,kind:s.kind,line:i.getStartLineNumber()})}}return o},D=(e,t)=>{for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const n of m(r))for(const c of n.handler.getDescendantsOfKind(l.PropertyAccessExpression))if(C(c))return!0}return!1},z=(e,t)=>{const o=S(t,O);if(!P(o))return;const r=e.getSourceFile(o)??e.addSourceFileAtPath(o),n=E(r);let c=!1,s=!1;if(n&&f.isCallExpression(n)){const i=n.getArguments()[0];i&&f.isObjectLiteralExpression(i)&&(c=d(i,"webPush")!==void 0,s=d(i,"fcm")!==void 0)}return{hasFcm:s,hasWebPush:c,usesPush:D(e,t)}};export{O as NOTIFY_FILENAME,M as discoverNotifyCalls,z as discoverNotifyConfig};
@@ -1 +0,0 @@
1
- import{existsSync as b}from"node:fs";import{join as h}from"node:path";import{LunoraError as f}from"@lunora/errors";import{queueDefaultName as y,queueBindingName as q}from"@lunora/queue";import{SyntaxKind as N,Node as c}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,stringPropertyFor as w}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{a as x}from"./attribution-JcwxPpyK.mjs";import{r as v}from"./handler-reference-Dzp5GZ5p.mjs";const E="queues.ts",S=i=>{const t=e=>e==="defineQueue"||e==="defineSubscription"||e==="defineTopic",o=i.getSymbol();if(!o){const e=i.getText();return t(e)?e:void 0}for(const e of o.getDeclarations()){if(!c.isImportSpecifier(e))continue;if(e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue")return;const r=e.getNameNode().getText();return t(r)?r:void 0}},l=w("queue"),$=(i,t,o)=>{if(c.isNumericLiteral(i))return i.getLiteralValue();throw d(i,`queue "${t}": \`${o}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},I=(i,t)=>{const o=m(i,"name");if(!o||!c.isPropertyAssignment(o))return;const e=l(o.getInitializerOrThrow(),t,"name");if(e.length===0)throw d(o,`queue "${t}": \`name\` must be a non-empty string when provided`);return e},g=(i,t,o,e)=>{const r=v(m(i,"handler"),e)?.site,s={bindingName:q(t),exportName:t,mode:"push",name:I(i,t)??y(t),...o===void 0?{}:{topic:o},...r===void 0?{}:{handlerSite:r},tuning:{}},n=m(i,"mode");if(n&&c.isPropertyAssignment(n)){if(o!==void 0)throw d(n,`subscription "${t}": \`mode\` is not allowed — a subscription is always a push consumer`);const u=l(n.getInitializerOrThrow(),t,"mode");if(u!=="push"&&u!=="pull")throw d(n,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(u)})`);s.mode=u}const a=m(i,"deadLetterQueue");a&&c.isPropertyAssignment(a)&&(s.tuning.deadLetterQueue=l(a.getInitializerOrThrow(),t,"deadLetterQueue"));for(const u of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const p=m(i,u);p&&c.isPropertyAssignment(p)&&(s.tuning[u]=$(p.getInitializerOrThrow(),t,u))}return s},P=(i,t,o)=>{const e=i.getArguments()[0];if(!e||!c.isObjectLiteralExpression(e))throw d(i,`queue "${t}": defineQueue must be passed an inline object literal`);return g(e,t,void 0,o)},T=(i,t,o,e)=>{const[r,s]=i.getArguments();if(!r||!c.isIdentifier(r)||!o.has(r.getText()))throw d(r??i,`subscription "${t}": the first argument must name a \`defineTopic()\` export of lunora/queues.ts`);if(!s||!c.isObjectLiteralExpression(s))throw d(i,`subscription "${t}": defineSubscription must be passed an inline object literal`);return g(s,t,o.get(r.getText()),e)},A=i=>{const t=[];for(const o of i.getVariableDeclarations()){const e=o.getInitializer();if(e?.getKind()!==N.CallExpression)continue;const r=e,s=r.getExpression(),n=c.isIdentifier(s)?S(s):void 0;if(n===void 0)continue;const a=o.getNameNode();if(!c.isIdentifier(a)){if(o.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw d(a,`${n} exports must be plain named exports (no destructuring)`)}const u=x(o,"binding");u!==void 0&&t.push({call:r,exportName:u,factory:n,localName:a.getText()})}return t},Q=(i,t)=>{const o=A(i),e=new Map(o.filter(n=>n.factory==="defineTopic").map(n=>[n.localName,n.exportName])),r=[];for(const n of o)n.factory==="defineQueue"?r.push(P(n.call,n.exportName,t)):n.factory==="defineSubscription"&&r.push(T(n.call,n.exportName,e,t));const s=[...e.values()].map(n=>({exportName:n}));return{queues:r,topics:s}},L=i=>{const t=new Map,o=new Map;for(const e of i){const r=t.get(e.name);if(r!==void 0)throw new f("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${e.name}": produced by both "${r}" and "${e.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(e.name,e.exportName);const s=o.get(e.bindingName);if(s!==void 0)throw new f("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${e.bindingName}": produced by both "${s}" and "${e.exportName}". Queue export names must yield unique binding names.`,{status:500});o.set(e.bindingName,e.exportName)}},O=(i,t)=>{const o=h(t,E);if(!b(o))return{queues:[],topics:[]};const e=i.getSourceFile(o)??i.addSourceFileAtPath(o),{queues:r,topics:s}=Q(e,t),n=r.toSorted((a,u)=>a.exportName.localeCompare(u.exportName));return L(n),{queues:n,topics:s.toSorted((a,u)=>a.exportName.localeCompare(u.exportName))}},V=(i,t)=>O(i,t).queues;export{E as QUEUES_FILENAME,O as discoverQueueDeclarations,V as discoverQueues};