@lunora/codegen 1.0.0-alpha.243 → 1.0.0-alpha.244

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 (55) hide show
  1. package/dist/index.d.mts +59 -1
  2. package/dist/index.d.ts +59 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-Bb2jxbOa.mjs → AGENTS_FILENAME-D8SgT3OR.mjs} +1 -1
  5. package/dist/packem_shared/{CONTAINERS_FILENAME-CGB4bqUr.mjs → CONTAINERS_FILENAME-CBCG6g9n.mjs} +1 -1
  6. package/dist/packem_shared/{DEFAULT_TARGET-wK6-Tado.mjs → DEFAULT_TARGET-BLYeFMMT.mjs} +1 -1
  7. package/dist/packem_shared/{FLAGS_FILENAME-BedPDCsR.mjs → FLAGS_FILENAME-W5XQz_Po.mjs} +1 -1
  8. package/dist/packem_shared/{MUTATORS_FILENAME-B6cKrN_m.mjs → MUTATORS_FILENAME-DqWOgC5Z.mjs} +1 -1
  9. package/dist/packem_shared/{NOTIFY_FILENAME-Cri3NT5U.mjs → NOTIFY_FILENAME-C1J_47et.mjs} +1 -1
  10. package/dist/packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs +3 -0
  11. package/dist/packem_shared/{QUEUES_FILENAME-BzOl92QK.mjs → QUEUES_FILENAME-RGwht3Xu.mjs} +1 -1
  12. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-D1zEPvOK.mjs +11 -0
  13. package/dist/packem_shared/{SHAPES_FILENAME-zJgzynXR.mjs → SHAPES_FILENAME-DRUFomCj.mjs} +1 -1
  14. package/dist/packem_shared/{WORKFLOWS_FILENAME-DNaUHGS8.mjs → WORKFLOWS_FILENAME-4-ib4HH-.mjs} +1 -1
  15. package/dist/packem_shared/buildOpenApiDocument-SxfElVzK.mjs +3 -0
  16. package/dist/packem_shared/chain-mte5djRJ.mjs +1 -0
  17. package/dist/packem_shared/{classify-procedure-call-BztLe76A.mjs → classify-procedure-call-CmcShAze.mjs} +1 -1
  18. package/dist/packem_shared/{context-property-calls-CjDzLU8p.mjs → context-property-calls-CWf9-6G5.mjs} +1 -1
  19. package/dist/packem_shared/{discoverAuthApiCalls-FxrdBeVt.mjs → discoverAuthApiCalls-DoSN_yc3.mjs} +1 -1
  20. package/dist/packem_shared/{discoverCrons-0lNudk0S.mjs → discoverCrons-BEALHx1S.mjs} +1 -1
  21. package/dist/packem_shared/{discoverFunctions-BsmX-sEq.mjs → discoverFunctions-BcBzcG5x.mjs} +1 -1
  22. package/dist/packem_shared/{discoverHttpRoutes-BcXI9CNt.mjs → discoverHttpRoutes-CJHS4llq.mjs} +1 -1
  23. package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +1 -0
  24. package/dist/packem_shared/{discoverInserts-CFJ3IVeI.mjs → discoverInserts-DpuLYPPd.mjs} +1 -1
  25. package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +1 -0
  26. package/dist/packem_shared/{discoverMigrations-DbrHwcGE.mjs → discoverMigrations-Dt7ywfZv.mjs} +1 -1
  27. package/dist/packem_shared/{discoverNondeterministicCalls-CSQ_GDcA.mjs → discoverNondeterministicCalls-CNJV2BiP.mjs} +1 -1
  28. package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +1 -0
  29. package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +1 -0
  30. package/dist/packem_shared/{discoverRlsMetadata-CPmAGL0W.mjs → discoverRlsMetadata-mXBmPOGj.mjs} +1 -1
  31. package/dist/packem_shared/{discoverRlsProcedures-BO4qC77y.mjs → discoverRlsProcedures-F4Cy-kSi.mjs} +1 -1
  32. package/dist/packem_shared/{discoverSandboxUsage-CrjZ6yNg.mjs → discoverSandboxUsage-DkbwwFvO.mjs} +1 -1
  33. package/dist/packem_shared/discoverSchema-D5R60b4F.mjs +1 -0
  34. package/dist/packem_shared/{discoverStorageRulesMetadata-D8VYflWt.mjs → discoverStorageRulesMetadata-D3Ot9g5f.mjs} +1 -1
  35. package/dist/packem_shared/{emitApp-D_9NVcvv.mjs → emitApp-Cu0w-3vl.mjs} +2 -2
  36. package/dist/packem_shared/{exported-procedure-chains-CmCDiPBV.mjs → exported-procedure-chains-D48EXUVQ.mjs} +1 -1
  37. package/dist/packem_shared/{fingerprintSchemaSources-L3nGKDQt.mjs → fingerprintSchemaSources-Cl1CJFeh.mjs} +1 -1
  38. package/dist/packem_shared/{index-BoaHhVtM.mjs → index-D7dKfGPh.mjs} +1 -1
  39. package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +1 -0
  40. package/dist/packem_shared/{loadProjectConfig-CKsFNgn3.mjs → loadProjectConfig-CktK_il-.mjs} +1 -1
  41. package/dist/packem_shared/modules-DyCocr1e.mjs +1 -0
  42. package/dist/packem_shared/{parse-validator-C94Yiabo.mjs → parse-validator-C6fHL7OS.mjs} +1 -1
  43. package/dist/packem_shared/{unwrap-handler-return-CoV_GK33.mjs → unwrap-handler-return-DVY_kFF7.mjs} +1 -1
  44. package/package.json +4 -4
  45. package/dist/packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs +0 -3
  46. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DX6sZtLG.mjs +0 -9
  47. package/dist/packem_shared/buildOpenApiDocument-nYvBhjxu.mjs +0 -3
  48. package/dist/packem_shared/chain-H2N_uKgj.mjs +0 -1
  49. package/dist/packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs +0 -1
  50. package/dist/packem_shared/discoverMaskProcedures-CV_Cc2_g.mjs +0 -1
  51. package/dist/packem_shared/discoverQueries-C7y8i_Ga.mjs +0 -1
  52. package/dist/packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs +0 -1
  53. package/dist/packem_shared/discoverSchema-D8DBDHEg.mjs +0 -1
  54. package/dist/packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs +0 -1
  55. package/dist/packem_shared/queries-B-f4jO-x.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,propertyKeyName as I}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{r as B,p as V}from"./parse-validator-C6fHL7OS.mjs";const q=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:U(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=J(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>G(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},H=e=>{const t=X(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},Q=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},Y=(e,t)=>{const n=H(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Q(o,n);return typeof a!="object"||a===null?void 0:W(a)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},L=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},A=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,t)=>{if(ae.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(le.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ie(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?ce(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ue=e=>{const t=de(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=fe(s);r&&n.push(r)}return n},pe=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},me=e=>{const[t,n,s]=e,r=ge(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},be=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=L(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},xe=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},he=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},ve=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Ee=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ie=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Se=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:te(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},ke=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(n));break}case"global":{e.shardMode="global",e.globalBackend=Ie(n);break}case"index":{e.indexes.push(me(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Se(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(n);break}case"vectorize":{const r=Ee(n,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of _){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ne(t))},P=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))ke(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,t,n.searchIndexes),_e(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=B(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(w(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(P(o,a))}}return t},Le=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:o,table:Le(s)}},$=e=>{const t=[];for(const n of e.getProperties()){const s=Oe(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Ae=(e,t)=>{if(!N.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?S(t,e):e,Ne=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,t)=>{const n=Pe(e);if(n){if(i.isPropertyAccessExpression(t)){const s=De(n);return s?b(s,t.getName()):void 0}return n}},Me=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,je(t))return t;const s=$e(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ze(a,t)}},Re=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Fe=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);w(a,r.getNameNode()),s.push(P(o,a))}return s},Ce=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:$(n)},D=(e,t,n,s,r)=>{Ae(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>Ne(c,e,o,r)),l=n.map(c=>({...c,name:S(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Be=(e,t,n)=>D(e,Fe(n),Ce(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ve=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Me(n);if(!s){if(t!==void 0){const o=Y(n,t);if(o){for(const a of o.bareTables)w(a.name,n);return D(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Je=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of qe(e)){const a=Ve(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}t=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,a,n),k=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:k}};export{rt as default};
@@ -1 +1 @@
1
- import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{w as d}from"./classify-procedure-call-BztLe76A.mjs";import{e as m}from"./exported-procedure-chains-CmCDiPBV.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};
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{w as d}from"./classify-procedure-call-CmcShAze.mjs";import{e as m}from"./exported-procedure-chains-D48EXUVQ.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
@@ -1,4 +1,4 @@
1
- import{A as w}from"./capabilities-DJJWVEtk.mjs";import{i as k}from"./ir-DBSvhNa-.mjs";import{G as S}from"./shared-DjUziztz.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,g=w.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>g.some(([t])=>e[t]),D=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],A=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],C=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],v=e=>(e.emailAgents?.length??0)>0,T=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],N=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],d=e=>e.tables.some(t=>k(t)),I=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],s=[...r||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,h)=>c.localeCompare(h)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},L=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...C(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(i),...A(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...T(e),...I(e),"",...D(e.identity),...N(e),...a||n?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},q=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>g.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
1
+ import{A as w}from"./capabilities-DJJWVEtk.mjs";import{i as k}from"./ir-DBSvhNa-.mjs";import{G as S}from"./shared-DjUziztz.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,g=w.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>g.some(([t])=>e[t]),D=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],A=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],C=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],v=e=>(e.emailAgents?.length??0)>0,T=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],N=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],d=e=>e.tables.some(t=>k(t)),I=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],s=[...r||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,h)=>c.localeCompare(h)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},L=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...C(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(i),...A(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...T(e),...I(e),"",...D(e.identity),...N(e),...a||n?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},q=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>g.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
2
2
  public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
3
3
  this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
4
4
 
@@ -289,7 +289,7 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${_(t.shardMode)}],`)
289
289
  }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
290
290
  ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
291
291
  `)}
292
- };`]:[]],U=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],F=e=>e.hasScheduler?`
292
+ };`]:[]],U=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture,"]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],F=e=>e.hasScheduler?`
293
293
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
294
294
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
295
295
  const namespace = this.schedulerDeclaration?.namespace(env);
@@ -1 +1 @@
1
- import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-BztLe76A.mjs";const f=s=>{const i=[];for(const r of s.getVariableStatements())if(r.isExported())for(const t of r.getDeclarations()){const e=t.getInitializer(),o=e&&a.isCallExpression(e)?n(e):void 0;o?.receiver&&i.push({name:t.getName(),receiver:o.receiver})}return i};export{f as e};
1
+ import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-CmcShAze.mjs";const f=s=>{const i=[];for(const r of s.getVariableStatements())if(r.isExported())for(const t of r.getDeclarations()){const e=t.getInitializer(),o=e&&a.isCallExpression(e)?n(e):void 0;o?.receiver&&i.push({name:t.getName(),receiver:o.receiver})}return i};export{f as e};
@@ -1 +1 @@
1
- import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const S=t=>{if(!s(t))return"unreadable";const e=u(t),o=h(t,"schema.ts");s(o)&&e.push(o);const r=c("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(i(a))}catch{}return r.digest("hex")};export{S as default};
1
+ import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const S=t=>{if(!s(t))return"unreadable";const e=u(t),o=h(t,"schema.ts");s(o)&&e.push(o);const r=c("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(i(a))}catch{}return r.digest("hex")};export{S as default};
@@ -1 +1 @@
1
- import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{w as g,c as h}from"./classify-procedure-call-BztLe76A.mjs";const u=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return f(e)},k=e=>g(e,"use","mask"),x=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();if(t&&r.isStringLiteral(t)){const s=t.getLiteralText();if(s==="redact"||s==="hash")return s}}return"custom"},v=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const i of t.getProperties()){const n=u(i);if(n===void 0||!r.isPropertyAssignment(i))continue;const o=i.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=u(a);c!==void 0&&s.push({column:c,table:n})}}return s},P=e=>{const t=k(e);return{maskColumns:t.flatMap(s=>v(s)),usesMask:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),C=new Set(["delete","insert","patch","replace"]),M=(e,t)=>{if(!r.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const i=h(s);if(!i)return;const n=i.receiver?P(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:o,tablesWritten:a}=d(e,y,C);return{exportName:e.getName(),file:t,maskColumns:n.maskColumns,tablesRead:o,tablesWritten:a,usesMask:n.usesMask,visibility:i.visibility}},E=(e,t)=>{const s=[];for(const i of m(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=p(t,i);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=M(c,o);l&&s.push(l)}}return s};export{u as a,E as d,k as m,x as s};
1
+ import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{w as g,c as h}from"./classify-procedure-call-CmcShAze.mjs";const u=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return f(e)},k=e=>g(e,"use","mask"),x=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();if(t&&r.isStringLiteral(t)){const s=t.getLiteralText();if(s==="redact"||s==="hash")return s}}return"custom"},v=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const i of t.getProperties()){const n=u(i);if(n===void 0||!r.isPropertyAssignment(i))continue;const o=i.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=u(a);c!==void 0&&s.push({column:c,table:n})}}return s},P=e=>{const t=k(e);return{maskColumns:t.flatMap(s=>v(s)),usesMask:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),C=new Set(["delete","insert","patch","replace"]),M=(e,t)=>{if(!r.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const i=h(s);if(!i)return;const n=i.receiver?P(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:o,tablesWritten:a}=d(e,y,C);return{exportName:e.getName(),file:t,maskColumns:n.maskColumns,tablesRead:o,tablesWritten:a,usesMask:n.usesMask,visibility:i.visibility}},E=(e,t)=>{const s=[];for(const i of m(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=p(t,i);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=M(c,o);l&&s.push(l)}}return s};export{u as a,E as d,k as m,x as s};
@@ -0,0 +1 @@
1
+ import{readdirSync as x,realpathSync as P,lstatSync as A,statSync as O}from"node:fs";import{dirname as N,join as f,relative as w,sep as T,extname as m}from"node:path";import{Node as s,VariableDeclarationKind as F,SyntaxKind as S}from"ts-morph";import{diagnosticAt as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findProjectConfigFile as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const D=/\.ts$/u,u=(t,e)=>w(t,e).split(T).join("/").replace(D,""),C=new Set(["_generated","node_modules"]),_=(t,e,i)=>t==="schema.ts"&&e===i,j=t=>{try{return O(t)}catch{console.warn(`@lunora/codegen: skipping ${t} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},y=(t,e,i,n)=>{let o,r;try{o=x(t),r=P(t)}catch{return e}if(n.has(r))return e;n.add(r);for(const a of o){const l=f(t,a),c=j(l);c!==void 0&&(c.isDirectory()?C.has(a)||y(l,e,i,n):c.isFile()&&m(a)===".ts"&&!_(a,t,i)&&e.push(l))}return e},b=t=>y(t,[],t,new Set),z=["src/server","src/index.ts","src/worker.ts"],V=new Set([".ts",".tsx"]),h=(t,e=[])=>{let i;try{i=A(t)}catch{return e}if(i.isFile())return V.has(m(t))&&e.push(t),e;if(!i.isDirectory())return e;for(const n of x(t))n==="_generated"||n==="node_modules"||h(f(t,n),e);return e},K=t=>{const e=N(t),i=b(t).map(r=>({displayPath:u(t,r),filePath:r})),n=new Set(i.map(r=>r.filePath)),o=I(e);for(const r of[...z.flatMap(a=>h(f(e,a))),...o===void 0?[]:[o]])n.has(r)||(n.add(r),i.push({displayPath:u(e,r),filePath:r}));return i},v=(t,e,i)=>{const n=[];for(const{displayPath:o,filePath:r}of e){const a=t.getSourceFile(r)??t.addSourceFileAtPath(r);for(const l of a.getDescendantsOfKind(S.CallExpression)){const c=i(l,o);c!==void 0&&n.push(c)}}return n},J=(t,e,i)=>v(t,b(e).map(n=>({displayPath:u(e,n),filePath:n})),i),Z=(t,e,i)=>v(t,K(e),i),tt=t=>{for(const e of t.getAncestors()){if(s.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0)return e.getName();if(s.isExportAssignment(e)&&!e.isExportEquals())return"default"}return""},L=t=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isNumericLiteral(t))return t.getLiteralText();if(s.isComputedPropertyName(t)){const e=t.getExpression();if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText()}return t.getText()},k=t=>L(t.getNameNode()),et=t=>L(t.getPropertyNameNode()??t.getNameNode()),p=(t,e)=>t?.getProperties().find(i=>!s.isSpreadAssignment(i)&&k(i)===e),it=(t,e)=>{if(e){const r=t.getArguments()[0];return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0}const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=p(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const o=n.getInitializer();return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0},st=(t,e)=>{if(!t||!s.isObjectLiteralExpression(t))return;const i=p(t,e);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},M=t=>{const e=t?.getDeclarations().find(o=>s.isVariableDeclaration(o));if(e===void 0||!s.isVariableDeclaration(e))return;const i=e.getParent();if(!s.isVariableDeclarationList(i)||i.getDeclarationKind()!==F.Const)return;const n=i.getParent();return s.isVariableStatement(n)&&s.isSourceFile(n.getParent())?e.getInitializer():void 0},$=t=>M(t.getSymbol()),nt=t=>{if(!t)return;if(s.isObjectLiteralExpression(t))return t;if(!s.isIdentifier(t))return;const e=$(t);return e!==void 0&&s.isObjectLiteralExpression(e)?e:void 0},g=t=>s.isPropertyAccessExpression(t)&&t.getName()==="db"||s.isIdentifier(t)&&t.getText()==="db",q=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),rt=t=>{const e=t.getExpression();if(!s.isPropertyAccessExpression(e)||!q.has(e.getName()))return;const i=e.getExpression();if(g(i)){const n=t.getArguments()[0];return{options:t.getArguments()[1],table:n&&s.isStringLiteral(n)?n.getLiteralText():""}}if(s.isPropertyAccessExpression(i)){const n=i.getExpression();if(g(n))return{options:t.getArguments()[0],table:i.getName()}}},d=(t,e)=>{const i=t.getExpression();return!s.isPropertyAccessExpression(i)||!e.has(i.getName())?!1:g(i.getExpression())},E=t=>{const e=t.getArguments()[0];return e&&s.isStringLiteral(e)?e.getLiteralText():""},ot=(t,e,i)=>{const n=new Set,o=new Set;for(const r of t.getDescendantsOfKind(S.CallExpression))if(d(r,e)){const a=E(r);a!==""&&n.add(a)}else if(d(r,i)){const a=E(r);a!==""&&o.add(a)}return{tablesRead:[...n],tablesWritten:[...o]}},B=t=>{let e=t;for(;e&&(s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isParenthesizedExpression(e)||s.isNonNullExpression(e));)e=e.getExpression();return e},at=t=>{const e=B(t);return e&&s.isCallExpression(e)?e:void 0},ct=t=>{const e=t.getExportAssignment(o=>!o.isExportEquals());if(!e)return;const i=e.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},lt=t=>{const e=t.getArguments()[1];return e&&s.isStringLiteral(e)?e.getLiteralValue():""},ut=(t,e)=>{if(!s.isObjectLiteralExpression(t))return;const i=p(t,e);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},U=t=>{const e=t.getStatements(),[i]=e;if(e.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},gt=t=>{if(s.isObjectLiteralExpression(t))return t;if(s.isParenthesizedExpression(t)){const e=t.getExpression();return s.isObjectLiteralExpression(e)?e:void 0}return s.isBlock(t)?U(t):void 0},ft=t=>s.isIdentifier(t)&&t.getText()==="ctx",pt=t=>(e,i,n)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw R(e,`${t} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},W=new Set(["api","internal"]),dt=new Set(["run","runAction","runMutation","runQuery"]),Et=t=>{if(t===void 0||!s.isPropertyAccessExpression(t))return;const e=[];let i=t;for(;s.isPropertyAccessExpression(i);)e.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&W.has(i.getText())&&e.length>=2?e:void 0};export{dt as RUN_METHODS,D as TS_EXTENSION_RE,et as bindingKeyName,J as collectCallRows,Z as collectSecurityCallRows,ct as defaultExportExpression,tt as enclosingExportName,p as findObjectProperty,Et as functionReferenceSegments,it as handlerOf,ft as isContextIdentifier,g as isDatabaseAccessor,lt as limitNameOf,b as listLunoraSourceFiles,K as listSecurityScanFiles,u as lunoraRelativePath,gt as objectLiteralFromCallbackBody,nt as optionsObjectLiteral,st as propertyInitializer,k as propertyKeyName,L as propertyNameText,rt as readTargetOf,pt as stringPropertyFor,ut as stringPropertyOf,M as symbolConstInitializer,E as tableArgumentOf,ot as tablesAccessedIn,B as unwrapExpression,at as unwrapToCallExpression};
@@ -1 +1 @@
1
- import{statSync as p,readFileSync as m}from"node:fs";import{basename as v}from"node:path";import{createJiti as E}from"jiti";import{Project as b,Node as r}from"ts-morph";import{propertyKeyName as u}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const g=new Map,N=async t=>{const i=f(t);if(i===void 0)return{};let e;try{const n=p(i);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=g.get(i);if(s?.key===e)return s.value;const l=(async()=>{try{const o=(await E(i,{interopDefault:!1,moduleCache:!1}).import(i))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return g.set(i,{key:e,value:l}),l},x=t=>{let e=t.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&r.isIdentifier(e))for(e=t.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e));)e=e.getExpression();return e!==void 0&&r.isObjectLiteralExpression(e)?e:void 0},c=(t,i)=>r.isPropertyAssignment(t)?t.getInitializer():i.getVariableDeclaration(u(t))?.getInitializer(),S=(t,i)=>{let e=t;for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e===void 0||!r.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),l=s.filter(a=>r.isPropertyAssignment(a)&&!r.isComputedPropertyName(a.getNameNode())||r.isShorthandPropertyAssignment(a));if(l.length!==s.length)return{advisor:{unreadable:!0}};const n=l.find(a=>u(a)==="minSeverity");if(n===void 0)return{advisor:{}};const o=c(n,i);return o!==void 0&&r.isStringLiteral(o)?{advisor:{minSeverity:o.getLiteralValue()}}:{advisor:{unreadable:!0}}},h=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),P=(t,i)=>{if(r.isGetAccessorDeclaration(t)||r.isMethodDeclaration(t))return h.get(u(t))??{};if(!r.isPropertyAssignment(t)&&!r.isShorthandPropertyAssignment(t))return{};const e=u(t);if(e==="advisor")return S(c(t,i),i);if(e!=="target"&&e!=="remote")return{};const s=c(t,i);return s===void 0?{unreadable:!0}:e==="target"?r.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:r.isTrueLiteral(s)||r.isFalseLiteral(s)?{remote:s.getLiteralValue()}:r.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},O=t=>{const i=f(t);if(i===void 0)return{};let e;try{e=m(i,"utf8")}catch{return{unreadable:!0}}const l=new b({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(v(i),e,{overwrite:!0}),n=x(l);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(a=>r.isSpreadAssignment(a)))return n.getProperties().some(d=>!r.isSpreadAssignment(d)&&u(d)==="advisor")?{advisor:{unreadable:!0},unreadable:!0}:{unreadable:!0};let o={};for(const a of n.getProperties())o={...o,...P(a,l)};return o};export{I as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,N as loadProjectConfig,O as readProjectConfigLiterals};
1
+ import{statSync as p,readFileSync as m}from"node:fs";import{basename as v}from"node:path";import{createJiti as E}from"jiti";import{Project as b,Node as r}from"ts-morph";import{propertyKeyName as u}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const g=new Map,N=async t=>{const i=f(t);if(i===void 0)return{};let e;try{const n=p(i);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=g.get(i);if(s?.key===e)return s.value;const l=(async()=>{try{const o=(await E(i,{interopDefault:!1,moduleCache:!1}).import(i))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return g.set(i,{key:e,value:l}),l},x=t=>{let e=t.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&r.isIdentifier(e))for(e=t.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e));)e=e.getExpression();return e!==void 0&&r.isObjectLiteralExpression(e)?e:void 0},c=(t,i)=>r.isPropertyAssignment(t)?t.getInitializer():i.getVariableDeclaration(u(t))?.getInitializer(),S=(t,i)=>{let e=t;for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e===void 0||!r.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),l=s.filter(a=>r.isPropertyAssignment(a)&&!r.isComputedPropertyName(a.getNameNode())||r.isShorthandPropertyAssignment(a));if(l.length!==s.length)return{advisor:{unreadable:!0}};const n=l.find(a=>u(a)==="minSeverity");if(n===void 0)return{advisor:{}};const o=c(n,i);return o!==void 0&&r.isStringLiteral(o)?{advisor:{minSeverity:o.getLiteralValue()}}:{advisor:{unreadable:!0}}},h=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),P=(t,i)=>{if(r.isGetAccessorDeclaration(t)||r.isMethodDeclaration(t))return h.get(u(t))??{};if(!r.isPropertyAssignment(t)&&!r.isShorthandPropertyAssignment(t))return{};const e=u(t);if(e==="advisor")return S(c(t,i),i);if(e!=="target"&&e!=="remote")return{};const s=c(t,i);return s===void 0?{unreadable:!0}:e==="target"?r.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:r.isTrueLiteral(s)||r.isFalseLiteral(s)?{remote:s.getLiteralValue()}:r.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},O=t=>{const i=f(t);if(i===void 0)return{};let e;try{e=m(i,"utf8")}catch{return{unreadable:!0}}const l=new b({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(v(i),e,{overwrite:!0}),n=x(l);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(a=>r.isSpreadAssignment(a)))return n.getProperties().some(d=>!r.isSpreadAssignment(d)&&u(d)==="advisor")?{advisor:{unreadable:!0},unreadable:!0}:{unreadable:!0};let o={};for(const a of n.getProperties())o={...o,...P(a,l)};return o};export{I as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,N as loadProjectConfig,O 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"./listLunoraSourceFiles-CSlcBYlo.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};
@@ -1 +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{propertyKeyName as E}from"./listLunoraSourceFiles-DP-5e-RE.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};
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{propertyKeyName as E}from"./listLunoraSourceFiles-CSlcBYlo.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};
@@ -1 +1 @@
1
- import{Node as l,SyntaxKind as g}from"ts-morph";import{lunoraRelativePath as L}from"./listLunoraSourceFiles-DP-5e-RE.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};
1
+ import{Node as l,SyntaxKind as g}from"ts-morph";import{lunoraRelativePath as L}from"./listLunoraSourceFiles-CSlcBYlo.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.243",
3
+ "version": "1.0.0-alpha.244",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,12 +46,12 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.175",
50
- "@lunora/agent": "1.0.0-alpha.157",
49
+ "@lunora/advisor": "1.0.0-alpha.176",
50
+ "@lunora/agent": "1.0.0-alpha.158",
51
51
  "@lunora/container": "1.0.0-alpha.64",
52
52
  "@lunora/errors": "1.0.0-alpha.48",
53
53
  "@lunora/platform": "1.0.0-alpha.47",
54
- "@lunora/queue": "1.0.0-alpha.82",
54
+ "@lunora/queue": "1.0.0-alpha.83",
55
55
  "@lunora/scheduler": "1.0.0-alpha.101",
56
56
  "@lunora/values": "1.0.0-alpha.58",
57
57
  "@lunora/workflow": "1.0.0-alpha.69",
@@ -1,3 +0,0 @@
1
- import{r as c}from"./json-data-Chfs2Cz5.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{G as l}from"./shared-DjUziztz.mjs";const d="1.3.2",R={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},h=e=>{const r=u(e.filePath),o=`${r}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((n,s)=>({code:-32e3-s,data:{code:n},message:n})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):R},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:r}]}},g=e=>{const r=e.version??"0.0.0",n=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>h(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:r},methods:n,openrpc:d}},$=e=>`${JSON.stringify(g(e),void 0,2)}
2
- `,y=e=>`${l}export const openRpcSpec = ${c(e,"Record<string, unknown>")};
3
- `;export{d as OPENRPC_VERSION,g as buildOpenRpcDocument,$ as emitOpenRpc,y as emitOpenRpcModule};