@lunora/codegen 1.0.0-alpha.423 → 1.0.0-alpha.425

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 (54) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/packem_shared/{AGENTS_FILENAME-C4tHmiZZ.mjs → AGENTS_FILENAME-BSW65Q9R.mjs} +1 -1
  3. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs → ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs} +1 -1
  4. package/dist/packem_shared/{CONTAINERS_FILENAME-d3XTFcqV.mjs → CONTAINERS_FILENAME-Dy3qWGfI.mjs} +1 -1
  5. package/dist/packem_shared/{ENV_FILENAME-DJ11PXN5.mjs → ENV_FILENAME-DFx_jlpa.mjs} +1 -1
  6. package/dist/packem_shared/{FLAGS_FILENAME-DeSjFBWq.mjs → FLAGS_FILENAME-CDaIBL6L.mjs} +1 -1
  7. package/dist/packem_shared/{MUTATORS_FILENAME-C0ZV0hh6.mjs → MUTATORS_FILENAME-SLAN2VXq.mjs} +1 -1
  8. package/dist/packem_shared/{OPENRPC_VERSION-BOBo0zdQ.mjs → OPENRPC_VERSION-DkWde9eh.mjs} +1 -1
  9. package/dist/packem_shared/{QUEUES_FILENAME-DbuJZnrY.mjs → QUEUES_FILENAME-CVkpGqoY.mjs} +1 -1
  10. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CdN_q7ja.mjs → SCHEMA_SNAPSHOT_FILENAME-DamKv-D7.mjs} +15 -15
  11. package/dist/packem_shared/{SHAPES_FILENAME-DTJKanSz.mjs → SHAPES_FILENAME-Cf4sum4C.mjs} +1 -1
  12. package/dist/packem_shared/{WORKFLOWS_FILENAME-7FysJsMZ.mjs → WORKFLOWS_FILENAME-Dtxo_XBw.mjs} +1 -1
  13. package/dist/packem_shared/attribution-B8xa6AeK.mjs +1 -0
  14. package/dist/packem_shared/{buildOpenApiDocument-DmV_PBFv.mjs → buildOpenApiDocument-C3zlve6K.mjs} +1 -1
  15. package/dist/packem_shared/{capabilitiesUsedBy-BNvoiCu1.mjs → capabilitiesUsedBy-BcDkRoOu.mjs} +1 -1
  16. package/dist/packem_shared/{classify-procedure-call-BmEirzc_.mjs → classify-procedure-call-BK_MMoue.mjs} +1 -1
  17. package/dist/packem_shared/{context-property-calls-BT1J7BqY.mjs → context-property-calls-As5I0QR6.mjs} +1 -1
  18. package/dist/packem_shared/context-root-CO8PbZi5.mjs +1 -0
  19. package/dist/packem_shared/{createCodegenProject-dC6oJh5H.mjs → createCodegenProject-C4XuJSap.mjs} +1 -1
  20. package/dist/packem_shared/{database-calls-d-Sssc-3.mjs → database-calls-Cug60vT9.mjs} +1 -1
  21. package/dist/packem_shared/{discoverAuthApiCalls-CuqaLRa0.mjs → discoverAuthApiCalls-DcvsgL5u.mjs} +1 -1
  22. package/dist/packem_shared/{discoverCrons-BlL_VbIv.mjs → discoverCrons-MpIC14pg.mjs} +1 -1
  23. package/dist/packem_shared/discoverFunctions-CGwHnz_a.mjs +1 -0
  24. package/dist/packem_shared/{discoverHttpRoutes-CesuhqW1.mjs → discoverHttpRoutes-BtMgsfzG.mjs} +1 -1
  25. package/dist/packem_shared/discoverHyperdriveCalls-B--Nvx36.mjs +1 -0
  26. package/dist/packem_shared/{discoverInserts-DIarYU2P.mjs → discoverInserts-Dx7Lxey3.mjs} +1 -1
  27. package/dist/packem_shared/discoverMaskProcedures-Dj_hkZz2.mjs +1 -0
  28. package/dist/packem_shared/{discoverMigrations-C9AlZYFi.mjs → discoverMigrations-DaBdK1Bv.mjs} +1 -1
  29. package/dist/packem_shared/{discoverNondeterministicCalls-ZeZDQJAI.mjs → discoverNondeterministicCalls-MeKjo_UX.mjs} +1 -1
  30. package/dist/packem_shared/{discoverQueries-DLZHcDzB.mjs → discoverQueries-BlhMsXuk.mjs} +1 -1
  31. package/dist/packem_shared/discoverR2sqlCalls-DHvclvkv.mjs +1 -0
  32. package/dist/packem_shared/{discoverRlsMetadata-C0UkQkWd.mjs → discoverRlsMetadata-CO-pRHOx.mjs} +1 -1
  33. package/dist/packem_shared/{discoverRlsProcedures-BbSdCvmA.mjs → discoverRlsProcedures-CUfhUqfY.mjs} +1 -1
  34. package/dist/packem_shared/{discoverSandboxUsage-Dgvv6F_7.mjs → discoverSandboxUsage-CdrJNRFd.mjs} +1 -1
  35. package/dist/packem_shared/{discoverSchema-BLTROO8Z.mjs → discoverSchema-CL9PLdOu.mjs} +1 -1
  36. package/dist/packem_shared/{discoverStorageRulesMetadata-DeBgC7po.mjs → discoverStorageRulesMetadata-D_pYyr1i.mjs} +1 -1
  37. package/dist/packem_shared/{exported-procedure-chains-CfH5jrzD.mjs → exported-procedure-chains-ej9ozyZB.mjs} +1 -1
  38. package/dist/packem_shared/{fingerprintSchemaSources-TN-rU6Of.mjs → fingerprintSchemaSources-BqPD3mw0.mjs} +1 -1
  39. package/dist/packem_shared/{handler-reference-BkOkxxg8.mjs → handler-reference-_zhtPddp.mjs} +1 -1
  40. package/dist/packem_shared/{index-M4HwQ4Jr.mjs → index-BwLaIVqA.mjs} +1 -1
  41. package/dist/packem_shared/{index-CfSmiylg.mjs → index-CQuAXbal.mjs} +1 -1
  42. package/dist/packem_shared/ip-reads-D8rPYtZ6.mjs +1 -0
  43. package/dist/packem_shared/{isTestPath-Uwb5a6Kq.mjs → isTestPath-DJeZ18i9.mjs} +1 -1
  44. package/dist/packem_shared/{modules-DdOd-7Wp.mjs → modules-isOWiSYI.mjs} +1 -1
  45. package/dist/packem_shared/{policies-Dn_tuTZd.mjs → policies-CrNWTJQi.mjs} +1 -1
  46. package/dist/packem_shared/{unwrap-handler-return-DvbyiLjc.mjs → unwrap-handler-return-BnsKyz9W.mjs} +1 -1
  47. package/package.json +5 -5
  48. package/dist/packem_shared/attribution-Cwt30DDJ.mjs +0 -1
  49. package/dist/packem_shared/context-root-BpDEhvNE.mjs +0 -1
  50. package/dist/packem_shared/discoverFunctions-CGrAezsY.mjs +0 -1
  51. package/dist/packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs +0 -1
  52. package/dist/packem_shared/discoverMaskProcedures-jkRrWS86.mjs +0 -1
  53. package/dist/packem_shared/discoverR2sqlCalls-D_HWbbky.mjs +0 -1
  54. package/dist/packem_shared/ip-reads-By7tJdyu.mjs +0 -1
@@ -1 +1 @@
1
- import{join as j,relative as Q,isAbsolute as Y,sep as $,dirname as ee}from"node:path";import{LunoraError as te}from"@lunora/errors";import{Node as a,SyntaxKind as N}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,lunoraRelativePath as ne,unwrapExpression as D,symbolConstInitializer as re,descendantsOfKind as se}from"./isTestPath-Uwb5a6Kq.mjs";import{createRequire as ie}from"node:module";import{fileURLToPath as oe}from"node:url";import{createJiti as ae}from"jiti";import{l as le,N as ce}from"./project-config-file-DR7xrrNB.mjs";import{r as de,p as fe}from"./parse-validator-BisfC8bR.mjs";import{R as ue}from"./reserved-words-CW1QFbTd.mjs";import{a as P}from"./property-name-7cBlgK_O.mjs";const ge=(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.`,me=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}},pe=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}:{}}),b=e=>{const t=e?._meta??{},n=e?.kind??"unknown",r={column:pe(t.column),kind:n,...t.sensitive===!0?{sensitive:!0}:{}};switch(n){case"array":case"optional":{r.inner=b(t.inner);break}case"from":break;case"id":{r.tableName=t.tableName;break}case"literal":{r.literalValue=me(t.value);break}case"object":{const i=t.shape??{};r.shape=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,b(l)]));break}case"record":{r.valueType=b(t.valueValidator),t.keyValidator!==void 0&&(r.keyType=b(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(r.bucket=t.bucket);break}case"union":{const i=t.members??[];r.members=i.map(o=>b(o));break}}const s=t.constraints;return s!==void 0&&Object.keys(s).length>0&&(r.hasRefinement=!0,n==="string"&&typeof s.maxLength=="number"&&(r.stringMaxLength=s.maxLength)),r},he=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",be=e=>{const t=r=>typeof e[r]=="string"?e[r]:void 0,n=Array.isArray(e.columns)?e.columns.filter(r=>typeof r=="string"):void 0;return{binding:t("binding")??"",...n===void 0?{}:{columns:n},hasReconcile:e.reconcileEveryMs!==void 0,hasSoftDelete:e.softDeleteColumn!==void 0,hasTenantBy:e.tenantBy!==void 0,...t("idColumn")===void 0?{}:{idColumn:t("idColumn")},...t("mode")===void 0?{}:{mode:t("mode")},...t("query")===void 0?{}:{query:t("query")}}},xe=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=he(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:be(e.externalSource)}:{},...e.isPublic===!0?{isPublic:!0}:{},geoIndexes:(e.geoIndexes??[]).map(({field:i,name:o,precision:l})=>({field:i,name:o,...l===void 0?{}:{precision:l}})),...s==="global"?{globalBackend:e.shardMode?.backend==="hyperdrive"?"hyperdrive":"d1"}:{},indexes:r,...e.memoryMode===!0?{memory:!0}:{},name:t,rankIndexes:(e.rankIndexes??[]).map(({name:i,partitionBy:o,sortBy:l})=>({name:i,...o===void 0?{}:{partitionBy:o},sortBy:l.map(({direction:c,field:u})=>({direction:c,field:u}))})),relations:Object.entries(e.relationMap??{}).map(([i,o])=>o.through!==void 0?{kind:"many",name:i,table:o.table,through:{...o.through}}:{field:o.field,kind:o.kind,name:i,...o.onDelete===void 0?{}:{onDelete:o.onDelete},references:o.references,table:o.table}),searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,b(o)])),shardMode:s,...e.softDeleteMode?{softDelete:{field:e.softDeleteMode.field}}:{},...e.ttlPolicy?{ttl:{field:e.ttlPolicy.field,...e.ttlPolicy.after===void 0?{}:{after:e.ttlPolicy.after}}}:{},vectorIndexes:(e.vectorIndexes??[]).map(i=>({...i.dimensions===void 0?{}:{dimensions:i.dimensions},field:i.field,...i.metadata===void 0?{}:{metadata:i.metadata},...i.metric===void 0?{}:{metric:i.metric},name:i.name,table:t}))}},ye=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const r=Object.entries(n).map(([o,l])=>xe(l,o)),s=e.vectorIndexes??{},i=Object.entries(s??{}).map(([o,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:o,table:l.table??""}));return{bareTables:r,bareVectorIndexes:i,key:t}},ve=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},Ee=e=>{const t=ve(e);if(t===void 0)return;const n=a.isPropertyAccessExpression(e)?e.getName():void 0,r=n===void 0?[]:[n];for(const s of e.getSourceFile().getImportDeclarations()){const i=s.getModuleSpecifierValue();for(const o of s.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===t)return{importedName:o.getName(),moduleSpecifier:i,propertyPath:r};if(s.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:i,propertyPath:r};if(s.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:i,propertyPath:[]}}},R=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?R(e.getExpression()):void 0,Ie=(e,t,n)=>{const r=n.getSymbol()?.compilerSymbol,s=i=>r!==void 0&&i?.getSymbol()?.compilerSymbol===r;return a.isPropertyAccessExpression(t)?s(e.getNamespaceImport())?t.getName():void 0:s(e.getDefaultImport())?"default":e.getNamedImports().find(i=>s(i.getAliasNode()??i.getNameNode()))?.getName()},Se=e=>{if(!a.isPropertyAccessExpression(e)||!a.isIdentifier(e.getExpression()))return;const t=e.getExpression().getSymbol(),n=(t?.getAliasedSymbol()??t)?.getValueDeclaration(),r=a.isVariableDeclaration(n)?n.getInitializer():void 0,s=r===void 0?void 0:R(r),i=s?.getExpression(),o=i!==void 0&&a.isPropertyAccessExpression(i)?i.getExpression():i;if(s===void 0||i===void 0||o===void 0||!a.isIdentifier(o))return;const l=s.getArguments().map(u=>le(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(ce)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const g=u.getModuleSpecifierValue();if(g.startsWith("."))continue;const h=Ie(u,i,o);if(h!==void 0)return{args:l,importedName:h,moduleSpecifier:g,propertyPath:[e.getName()]}}},F=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},we=(e,t)=>F(e[t.importedName],t.propertyPath),C=(e,t)=>{const n=ae(j(t,"noop.js")).esmResolve(e);return ie(j(t,"noop.cjs"))(n.startsWith("file:")?oe(n):n)},Te=(e,t)=>{const n=Ee(e);if(n&&!n.moduleSpecifier.startsWith("."))return we(C(n.moduleSpecifier,t),n);const r=Se(e);if(!r)return;const s=C(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?F(s(...r.args),r.propertyPath):void 0},ke=(e,t)=>{try{const n=Te(e,t);return typeof n!="object"||n===null?void 0:ye(n)}catch{return}},Ne=new Set(["cosine","dot-product","euclidean"]),v=(e,t)=>{const n=m(e,t);if(n&&a.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=v(e,t);if(n&&a.isStringLiteral(n))return n.getLiteralText()},I=(e,t)=>{const n=v(e,t);if(n&&a.isNumericLiteral(n))return Number(n.getLiteralText())},B=(e,t)=>{const n=v(e,t);if(n&&(a.isTrueLiteral(n)||a.isFalseLiteral(n)))return n.getLiteralValue()},S=(e,t)=>{const n=v(e,t);if(n&&a.isArrayLiteralExpression(n))return n.getElements().filter(r=>a.isStringLiteral(r)).map(r=>r.getLiteralText())},V=e=>e&&Ne.has(e)?e:void 0,w=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",Ae=(e,t)=>{const n=S(e,t);return n!==void 0&&n.length>0?n:void 0},q=(e,t,n,r,s)=>{let i=e;for(;;){const o=i.getParent();if(!o||!a.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!a.isCallExpression(l))break;if(o.getName()===t){const c=l.getArguments()[0];if(!c||!a.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${s})`);const u=c.getLiteralText();if(!r.has(u))throw d(c,`unknown ${n} ${JSON.stringify(u)} — expected ${s}`);return u}i=l}},Pe=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.`,Oe=/^(?:sqlite_|_cf_|__)/u,Le=/__(?:agg|rank|geo|fts)_/u,_e=e=>Oe.test(e)||Le.test(e),J=()=>{},je=e=>t=>{const n=t.getSourceFile().getFilePath(),r=Q(e,n);if(!(r===""||Y(r)||r.split($)[0]===".."||r.split($).includes("node_modules")))return{file:ne(e,n),line:t.getStartLineNumber()}},$e=new Set(["cascade","restrict","set null"]),De=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),U=/^[A-Za-z_$][\w$]*$/u,O=(e,t)=>{if(De.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(ue.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(!U.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(_e(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&&$e.has(e)?e:void 0,ze=e=>{if(!a.isArrowFunction(e))return;let t=e.getBody();if(a.isParenthesizedExpression(t))t=t.getExpression();else if(a.isBlock(t)){const n=t.getStatements().find(r=>a.isReturnStatement(r));t=n&&a.isReturnStatement(n)?n.getExpression()??t:t}return a.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,n)=>{const r=a.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!a.isObjectLiteralExpression(r))throw d(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[s,i,o]=["table","from","to"].map(l=>f(r,l));if(s===void 0||i===void 0||o===void 0)throw d(r,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(i===o)throw d(r,`relation \`through\` has \`from\` and \`to\` both set to "${i}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:i,table:s,to:o}}},Re=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?Me(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ce(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},Fe=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isPropertyAccessExpression(n))return;const r=n.getName();if(r!=="one"&&r!=="many")return;const[s,i]=t.getArguments();if(!s||!a.isStringLiteral(s))throw d(s??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${s?s.getText():"no argument"}.`);const o=s.getLiteralText();return Re(r,P(e),o,i)},Be=(e,t)=>{const n=ze(e);if(!n)return[];const r=[];for(const s of n.getProperties()){const i=Fe(s);if(i){const o=t(s);r.push(o===void 0?i:{...i,site:o})}}return r},Ve=(e,t,n)=>{if(!t.includes("."))return;const[r="",...s]=t.split("."),i=`${r}${s.map(o=>o.charAt(0).toUpperCase()+o.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. \`${i}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},qe=e=>{if(!e||!a.isObjectLiteralExpression(e))return!1;const t=m(e,"unique");if(!t||!a.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!a.isTrueLiteral(n)&&!a.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return a.isTrueLiteral(n)},Je=e=>{const[t,n,r]=e,s=qe(r),i=w(t),o=n&&a.isArrayLiteralExpression(n)?n.getElements():[];for(const c of o)if(!a.isStringLiteral(c))throw d(c,`index "${i}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>a.isStringLiteral(c));for(const c of l)Ve(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},Ue=e=>{const[t,n]=e;let r="_unknown_",s,i,o,l;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=S(n,"filterFields"),i=f(n,"language"),o=B(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:w(t),staged:o,strategy:l}},Ke=e=>{const[t,n]=e;let r="_unknown_",s;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=I(n,"precision")),{field:r,name:w(t),precision:s}},We=e=>{const[t,n]=e,r=t&&a.isStringLiteral(t)?t.getLiteralText():"_unknown_";let s;return n&&a.isObjectLiteralExpression(n)&&(s=I(n,"after")),{after:s,field:r}},He=e=>{if(!a.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Xe=e=>{const[t,n]=e;let r=[],s;if(n&&a.isObjectLiteralExpression(n)){const i=m(n,"sortBy");if(i&&a.isPropertyAssignment(i)){const o=i.getInitializer();o&&a.isArrayLiteralExpression(o)&&(r=o.getElements().map(l=>He(l)).filter(l=>l!==void 0))}s=S(n,"partitionBy")}return{name:w(t),partitionBy:s,sortBy:r}},Ze=(e,t)=>{const[n,r]=e,s=n&&a.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!r||!a.isObjectLiteralExpression(r)))return{dimensions:I(r,"dimensions"),field:s,metadata:S(r,"metadata"),metric:V(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Ge=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},z=(e,t)=>{if(e===void 0)return t;if(!a.isObjectLiteralExpression(e))throw d(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=m(e,"field");if(n===void 0)return t;const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(r&&a.isStringLiteral(r))return r.getLiteralText();throw d(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Qe=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:Ae(t,"columns"),hasReconcile:m(t,"reconcileEveryMs")!==void 0,hasSoftDelete:m(t,"softDeleteColumn")!==void 0,hasTenantBy:m(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},x=(e,t)=>t===void 0?e:{...e,site:t},Ye=(e,t,n,r,s)=>{const i=e.locate(s);switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(x(Ke(n),i));break}case"global":{e.shardMode="global",e.globalBackend=Ge(n);break}case"index":{e.indexes.unshift(x(Je(n),i));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(x(Xe(n),i));break}case"relations":{const o=n[0];o&&e.relations.push(...Be(o,e.locate));break}case"searchIndex":{e.searchIndexes.push(x(Ue(n),i));break}case"shardBy":{const o=n[0];e.shardMode={field:o&&a.isStringLiteral(o)?o.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:z(n[0],"deletedAt")};break}case"source":{e.externalSource=Qe(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(z(n[0],"updatedAt"));break}case"ttl":{e.ttl=We(n);break}case"vectorize":{const o=Ze(n,r);o&&e.vectorIndexes.push(x(o,i));break}}},M=["__vocab","_config","_content","_data","_docsize","_idx"],et=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of M){const o=`${s.name}${i}`;if(!r.has(o))continue;const l=i==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${s.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" 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 "${s.name}" and "${o}", whose generated FTS5 tables collide: "${s.name}" already owns "${t}__fts_${o}" as its "${i}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${M.join(", ")}.`)}},tt=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,Pe(t))},nt=(e,t,n)=>{const{softDelete:r,timestampsFields:s}=n,i={};r&&!(r.field in t)&&(i[r.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[o]=s;if(o===void 0)return{...t,...i};if(s.length>1)throw d(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(o===r?.field)throw d(e,`\`.softDelete()\` and \`.timestamps()\` both use "${o}"; give one of them another field.`);const l=t[o];if(l===void 0)i[o]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw d(e,`\`.timestamps()\` would add "${o}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...i}},k=4,rt=e=>{const t=e.getParent(),n=a.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol();return re(n?.isAlias()===!0?n.getAliasedSymbol():n)},A=(e,t)=>d(e,`table "${t}" is defined as ${JSON.stringify(e.getText())}, but codegen reads a table only from an inline defineTable(...) chain or one bound to a module-scope const. Inline the defineTable(...) call, or bind it to a const.`),st=(e,t,n)=>{const s=t.getParentIfKind(N.VariableDeclaration)?.getNameNode();if(!(s===void 0||!a.isIdentifier(s)))for(const i of s.findReferencesAsNodes()){const o=i.getParent();if(i!==e&&a.isPropertyAccessExpression(o)&&o.getExpression()===i&&a.isCallExpression(o.getParent())&&o.getParentIfKindOrThrow(N.CallExpression).getExpression()===o)throw d(i,`table "${n}" is built from "${s.getText()}", which also has .${o.getName()}(...) called on it outside the chain the schema uses. Table builder methods change the shared builder, so codegen cannot see that call. Chain every method in one expression.`)}},it=e=>{let t=0;return n=>{let r=D(n)??n;for(;a.isIdentifier(r);){if(t+=1,t>k)throw d(r,`table "${e}" is reached through more than ${String(k)} const bindings, and codegen follows at most ${String(k)}. Inline the defineTable(...) call.`);const s=rt(r);if(s===void 0)throw A(r,e);st(r,s,e),r=D(s)??s}return r}},ot=e=>e.getText()==="defineTable"?!0:e.getSymbol()?.getDeclarations().some(t=>a.isImportSpecifier(t)&&t.getName()==="defineTable")===!0,at=(e,t)=>{if(e===void 0)return{};if(a.isObjectLiteralExpression(e))return fe(e);throw d(e,`table "${t}" calls defineTable(${JSON.stringify(e.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.`)},K=(e,t,n=J)=>{const r={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,locate:n,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={};const i=it(t);let o=i(e),l=!1,c;for(;a.isCallExpression(o);){const g=o.getExpression(),h=o.getArguments();if(a.isPropertyAccessExpression(g))Ye(r,g.getName(),h,t,g.getNameNode()),o=i(g.getExpression());else if(a.isIdentifier(g)&&ot(g)){c=o,s=at(h[0],t),l=!0;break}else throw A(o,t)}if(!l)throw A(o,t);s=nt(e,s,r),et(e,t,r.searchIndexes),tt(e,t,r);const u=c===void 0?void 0:n(c);return{...r.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:r.commitOrdered,externallyManaged:r.externallyManaged,externalSource:r.externalSource,geoIndexes:r.geoIndexes,...u===void 0?{}:{site:u},globalBackend:r.shardMode==="global"?r.globalBackend??"d1":void 0,indexes:r.indexes,isPublic:r.isPublic,memory:r.memory,name:t,rankIndexes:r.rankIndexes,relations:r.relations,searchIndexes:r.searchIndexes,shape:s,shardMode:r.shardMode,softDelete:r.softDelete,ttl:r.ttl,vectorIndexes:r.vectorIndexes}},W=e=>a.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),H=(e,t=J,n=[],r=new Set,s=new Set)=>{s.add(e);for(const i of e.getProperties()){if(a.isSpreadAssignment(i)){const l=de(i.getExpression());l!==void 0&&!s.has(l)&&H(l,t,n,r,s);continue}if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(o){const l=P(i);if(O(l,i.getNameNode()),r.has(l))throw d(i.getNameNode(),`defineSchema({...}): table "${l}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);r.add(l),n.push(K(o,l,t))}}return n},lt=e=>{const t=m(e,"source");if(t&&a.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&a.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ct=(e,t)=>{if(!a.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!a.isCallExpression(n))return;const r=n.getExpression();if(!a.isIdentifier(r)||r.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!a.isObjectLiteralExpression(s))return;const i=e.getNameNode(),o=a.isStringLiteral(i)?i.getLiteralText():i.getText(),l=t(n);return{dimensions:I(s,"dimensions"),metric:V(f(s,"metric")),name:o,...l===void 0?{}:{site:l},table:lt(s)}},X=(e,t)=>{const n=[];for(const r of e.getProperties()){const s=ct(r,t);s&&n.push(s)}return n},L=(e,t)=>`${e}_${t}`,dt=(e,t)=>{if(!U.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.`)},y=(e,t,n)=>n.has(e)?L(t,e):e,E=(e,t)=>{const n=r=>r===void 0?void 0:E(r,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(r=>E(r,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([r,s])=>[r,E(s,t)]))}}},ft=(e,t,n,r)=>{const s=L(t,e.name);return{...e,extensionKey:t,...r?{extensionFromPackage:!0}:{},name:s,shape:Object.fromEntries(Object.entries(e.shape).map(([i,o])=>[i,E(o,l=>y(l,t,n))])),relations:e.relations.map(i=>{const o=y(i.table,t,n);return i.through===void 0?{...i,table:o}:{...i,table:o,through:{...i.through,table:y(i.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,t,n)}))}},ut=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},gt=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},mt=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},pt=e=>{if(a.isObjectLiteralExpression(e))return e;if(a.isCallExpression(e)){const t=e.getExpression();let n;if(a.isIdentifier(t)?n=t.getText():a.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const r=e.getArguments()[1];return r&&a.isObjectLiteralExpression(r)?r:void 0}}},ht=(e,t)=>{const n=ut(e);if(n){if(a.isPropertyAccessExpression(t)){const r=pt(n);return r?v(r,t.getName()):void 0}return n}},bt=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,gt(t))return t;const r=mt(t),s=r&&a.isIdentifier(r)?r.getSymbol():void 0,o=(s?.getAliasedSymbol()?.getDeclarations()??s?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ht(o,t)}},xt=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},yt=(e,t)=>{const n=m(e,"tables");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();if(!r||!a.isObjectLiteralExpression(r))return[];const s=[];for(const i of r.getProperties()){if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(!o)continue;const l=P(i);O(l,i.getNameNode()),s.push(K(o,l,t))}return s},vt=(e,t)=>{const n=m(e,"vectorIndexes");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();return!r||!a.isObjectLiteralExpression(r)?[]:X(r,t)},Z=(e,t,n,r,s)=>{dt(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>ft(c,e,i,s)),l=n.map(c=>({...c,name:L(e,c.name),table:y(c.table,e,i)}));return{tables:o,vectorIndexes:l}},Et=(e,t,n,r)=>Z(e,yt(n,r),vt(n,r),t,t.getSourceFile().getFilePath().includes("/node_modules/")),It=(e,t,n)=>{const r=e.getArguments()[0];if(!r)return;let s=r;for(;a.isParenthesizedExpression(s)||a.isAsExpression(s)||a.isSatisfiesExpression(s);)s=s.getExpression();const i=bt(s);if(!i){if(t!==void 0){const l=ke(s,t);if(l){for(const c of l.bareTables)O(c.name,s);return Z(l.key,l.bareTables,l.bareVectorIndexes,s,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${s.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. If the receiver is a component built with options codegen cannot evaluate (a function, a variable), extend with the standalone extension the package exports instead (e.g. \`presenceExtension\`, \`actionCacheExtension\` or \`documentHistoryExtension\` from \`@lunora/server\`).`);return}const o=xt(i);if(!o){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Et(o.key,o.keyNode,o.options,n)},St=e=>{const t=[];let n=e;for(;;){const r=n.getParent();if(!r||!a.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!a.isCallExpression(s))break;r.getName()==="extend"&&t.push(s),n=s}return t},wt=(e,t,n,r)=>{const s=new Set(t.map(o=>o.name)),i=[];for(const o of St(e)){const l=It(o,n,r);if(l){for(const c of l.tables){if(s.has(c.name))throw d(o,`defineSchema(...).extend(...): table "${c.name}" already exists — another extension with the same key already contributed it.`);s.add(c.name),t.push(c)}i.push(...l.vectorIndexes)}}return i},Tt=new Set(["eu","fedramp","us"]),kt=e=>q(e,"jurisdiction","jurisdiction",Tt,'"eu", "us", or "fedramp"'),Nt=e=>{let t=e;for(;;){const n=t.getParent(),r=n?.getParent();if(!n||!a.isPropertyAccessExpression(n)||!r||!a.isCallExpression(r))return!1;if(n.getName()==="jurisdiction"){const s=r.getArguments()[1];return s!==void 0&&a.isObjectLiteralExpression(s)&&B(s,"pinAuth")===!0}t=r}},At=new Set(["required"]),Pt=e=>q(e,"rls","rls mode",At,'"required"'),Ot=e=>{if(!a.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(!r||!a.isCallExpression(r))return;const s=r.getExpression(),i=r.getArguments()[1],o=i&&a.isObjectLiteralExpression(i)?f(i,"on"):void 0;if(!a.isIdentifier(s)||s.getText()!=="defineAggregateIndex"||o===void 0)return;t.add(o)}return t},Lt=(e,t)=>{if(t===void 0)return;const n=Ot(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},Jt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=se(r,N.CallExpression).find(p=>{const _=p.getExpression();return a.isIdentifier(_)&&_.getText()==="defineSchema"});if(!s)throw new te("INTERNAL",`defineSchema() not found in ${t}`);const i=s.getArguments()[0];if(!i||!a.isObjectLiteralExpression(i))throw d(s,"defineSchema() expects an object literal");const o=je(ee(t)),l=H(i,o),c=s.getArguments()[1],u=c&&a.isObjectLiteralExpression(c)?X(c,o):[],g=wt(s,l,n,o);Lt(l,s.getArguments()[2]);const h=[...l.flatMap(p=>p.vectorIndexes),...u,...g],G=new Set(l.filter(p=>p.shardMode==="global").map(p=>p.name)),T=h.find(p=>G.has(p.table));if(T)throw d(s,ge(T.table,T.name));return{jurisdiction:kt(s),...Nt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:Pt(s),tables:l,vectorIndexes:h}};export{Jt as default};
1
+ import{join as j,relative as Q,isAbsolute as Y,sep as $,dirname as ee}from"node:path";import{LunoraError as te}from"@lunora/errors";import{Node as a,SyntaxKind as N}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,lunoraRelativePath as ne,unwrapExpression as D,symbolConstInitializer as re,descendantsOfKind as se}from"./isTestPath-DJeZ18i9.mjs";import{createRequire as ie}from"node:module";import{fileURLToPath as oe}from"node:url";import{createJiti as ae}from"jiti";import{l as le,N as ce}from"./project-config-file-DR7xrrNB.mjs";import{r as de,p as fe}from"./parse-validator-BisfC8bR.mjs";import{R as ue}from"./reserved-words-CW1QFbTd.mjs";import{a as P}from"./property-name-7cBlgK_O.mjs";const ge=(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.`,me=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}},pe=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}:{}}),b=e=>{const t=e?._meta??{},n=e?.kind??"unknown",r={column:pe(t.column),kind:n,...t.sensitive===!0?{sensitive:!0}:{}};switch(n){case"array":case"optional":{r.inner=b(t.inner);break}case"from":break;case"id":{r.tableName=t.tableName;break}case"literal":{r.literalValue=me(t.value);break}case"object":{const i=t.shape??{};r.shape=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,b(l)]));break}case"record":{r.valueType=b(t.valueValidator),t.keyValidator!==void 0&&(r.keyType=b(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(r.bucket=t.bucket);break}case"union":{const i=t.members??[];r.members=i.map(o=>b(o));break}}const s=t.constraints;return s!==void 0&&Object.keys(s).length>0&&(r.hasRefinement=!0,n==="string"&&typeof s.maxLength=="number"&&(r.stringMaxLength=s.maxLength)),r},he=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",be=e=>{const t=r=>typeof e[r]=="string"?e[r]:void 0,n=Array.isArray(e.columns)?e.columns.filter(r=>typeof r=="string"):void 0;return{binding:t("binding")??"",...n===void 0?{}:{columns:n},hasReconcile:e.reconcileEveryMs!==void 0,hasSoftDelete:e.softDeleteColumn!==void 0,hasTenantBy:e.tenantBy!==void 0,...t("idColumn")===void 0?{}:{idColumn:t("idColumn")},...t("mode")===void 0?{}:{mode:t("mode")},...t("query")===void 0?{}:{query:t("query")}}},xe=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=he(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:be(e.externalSource)}:{},...e.isPublic===!0?{isPublic:!0}:{},geoIndexes:(e.geoIndexes??[]).map(({field:i,name:o,precision:l})=>({field:i,name:o,...l===void 0?{}:{precision:l}})),...s==="global"?{globalBackend:e.shardMode?.backend==="hyperdrive"?"hyperdrive":"d1"}:{},indexes:r,...e.memoryMode===!0?{memory:!0}:{},name:t,rankIndexes:(e.rankIndexes??[]).map(({name:i,partitionBy:o,sortBy:l})=>({name:i,...o===void 0?{}:{partitionBy:o},sortBy:l.map(({direction:c,field:u})=>({direction:c,field:u}))})),relations:Object.entries(e.relationMap??{}).map(([i,o])=>o.through!==void 0?{kind:"many",name:i,table:o.table,through:{...o.through}}:{field:o.field,kind:o.kind,name:i,...o.onDelete===void 0?{}:{onDelete:o.onDelete},references:o.references,table:o.table}),searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,b(o)])),shardMode:s,...e.softDeleteMode?{softDelete:{field:e.softDeleteMode.field}}:{},...e.ttlPolicy?{ttl:{field:e.ttlPolicy.field,...e.ttlPolicy.after===void 0?{}:{after:e.ttlPolicy.after}}}:{},vectorIndexes:(e.vectorIndexes??[]).map(i=>({...i.dimensions===void 0?{}:{dimensions:i.dimensions},field:i.field,...i.metadata===void 0?{}:{metadata:i.metadata},...i.metric===void 0?{}:{metric:i.metric},name:i.name,table:t}))}},ye=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const r=Object.entries(n).map(([o,l])=>xe(l,o)),s=e.vectorIndexes??{},i=Object.entries(s??{}).map(([o,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:o,table:l.table??""}));return{bareTables:r,bareVectorIndexes:i,key:t}},ve=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},Ee=e=>{const t=ve(e);if(t===void 0)return;const n=a.isPropertyAccessExpression(e)?e.getName():void 0,r=n===void 0?[]:[n];for(const s of e.getSourceFile().getImportDeclarations()){const i=s.getModuleSpecifierValue();for(const o of s.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===t)return{importedName:o.getName(),moduleSpecifier:i,propertyPath:r};if(s.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:i,propertyPath:r};if(s.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:i,propertyPath:[]}}},R=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?R(e.getExpression()):void 0,Ie=(e,t,n)=>{const r=n.getSymbol()?.compilerSymbol,s=i=>r!==void 0&&i?.getSymbol()?.compilerSymbol===r;return a.isPropertyAccessExpression(t)?s(e.getNamespaceImport())?t.getName():void 0:s(e.getDefaultImport())?"default":e.getNamedImports().find(i=>s(i.getAliasNode()??i.getNameNode()))?.getName()},Se=e=>{if(!a.isPropertyAccessExpression(e)||!a.isIdentifier(e.getExpression()))return;const t=e.getExpression().getSymbol(),n=(t?.getAliasedSymbol()??t)?.getValueDeclaration(),r=a.isVariableDeclaration(n)?n.getInitializer():void 0,s=r===void 0?void 0:R(r),i=s?.getExpression(),o=i!==void 0&&a.isPropertyAccessExpression(i)?i.getExpression():i;if(s===void 0||i===void 0||o===void 0||!a.isIdentifier(o))return;const l=s.getArguments().map(u=>le(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(ce)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const g=u.getModuleSpecifierValue();if(g.startsWith("."))continue;const h=Ie(u,i,o);if(h!==void 0)return{args:l,importedName:h,moduleSpecifier:g,propertyPath:[e.getName()]}}},F=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},we=(e,t)=>F(e[t.importedName],t.propertyPath),C=(e,t)=>{const n=ae(j(t,"noop.js")).esmResolve(e);return ie(j(t,"noop.cjs"))(n.startsWith("file:")?oe(n):n)},Te=(e,t)=>{const n=Ee(e);if(n&&!n.moduleSpecifier.startsWith("."))return we(C(n.moduleSpecifier,t),n);const r=Se(e);if(!r)return;const s=C(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?F(s(...r.args),r.propertyPath):void 0},ke=(e,t)=>{try{const n=Te(e,t);return typeof n!="object"||n===null?void 0:ye(n)}catch{return}},Ne=new Set(["cosine","dot-product","euclidean"]),v=(e,t)=>{const n=m(e,t);if(n&&a.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=v(e,t);if(n&&a.isStringLiteral(n))return n.getLiteralText()},I=(e,t)=>{const n=v(e,t);if(n&&a.isNumericLiteral(n))return Number(n.getLiteralText())},B=(e,t)=>{const n=v(e,t);if(n&&(a.isTrueLiteral(n)||a.isFalseLiteral(n)))return n.getLiteralValue()},S=(e,t)=>{const n=v(e,t);if(n&&a.isArrayLiteralExpression(n))return n.getElements().filter(r=>a.isStringLiteral(r)).map(r=>r.getLiteralText())},V=e=>e&&Ne.has(e)?e:void 0,w=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",Ae=(e,t)=>{const n=S(e,t);return n!==void 0&&n.length>0?n:void 0},q=(e,t,n,r,s)=>{let i=e;for(;;){const o=i.getParent();if(!o||!a.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!a.isCallExpression(l))break;if(o.getName()===t){const c=l.getArguments()[0];if(!c||!a.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${s})`);const u=c.getLiteralText();if(!r.has(u))throw d(c,`unknown ${n} ${JSON.stringify(u)} — expected ${s}`);return u}i=l}},Pe=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.`,Oe=/^(?:sqlite_|_cf_|__)/u,Le=/__(?:agg|rank|geo|fts)_/u,_e=e=>Oe.test(e)||Le.test(e),J=()=>{},je=e=>t=>{const n=t.getSourceFile().getFilePath(),r=Q(e,n);if(!(r===""||Y(r)||r.split($)[0]===".."||r.split($).includes("node_modules")))return{file:ne(e,n),line:t.getStartLineNumber()}},$e=new Set(["cascade","restrict","set null"]),De=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),U=/^[A-Za-z_$][\w$]*$/u,O=(e,t)=>{if(De.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(ue.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(!U.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(_e(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&&$e.has(e)?e:void 0,ze=e=>{if(!a.isArrowFunction(e))return;let t=e.getBody();if(a.isParenthesizedExpression(t))t=t.getExpression();else if(a.isBlock(t)){const n=t.getStatements().find(r=>a.isReturnStatement(r));t=n&&a.isReturnStatement(n)?n.getExpression()??t:t}return a.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,n)=>{const r=a.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!a.isObjectLiteralExpression(r))throw d(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[s,i,o]=["table","from","to"].map(l=>f(r,l));if(s===void 0||i===void 0||o===void 0)throw d(r,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(i===o)throw d(r,`relation \`through\` has \`from\` and \`to\` both set to "${i}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:i,table:s,to:o}}},Re=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?Me(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ce(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},Fe=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isPropertyAccessExpression(n))return;const r=n.getName();if(r!=="one"&&r!=="many")return;const[s,i]=t.getArguments();if(!s||!a.isStringLiteral(s))throw d(s??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${s?s.getText():"no argument"}.`);const o=s.getLiteralText();return Re(r,P(e),o,i)},Be=(e,t)=>{const n=ze(e);if(!n)return[];const r=[];for(const s of n.getProperties()){const i=Fe(s);if(i){const o=t(s);r.push(o===void 0?i:{...i,site:o})}}return r},Ve=(e,t,n)=>{if(!t.includes("."))return;const[r="",...s]=t.split("."),i=`${r}${s.map(o=>o.charAt(0).toUpperCase()+o.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. \`${i}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},qe=e=>{if(!e||!a.isObjectLiteralExpression(e))return!1;const t=m(e,"unique");if(!t||!a.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!a.isTrueLiteral(n)&&!a.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return a.isTrueLiteral(n)},Je=e=>{const[t,n,r]=e,s=qe(r),i=w(t),o=n&&a.isArrayLiteralExpression(n)?n.getElements():[];for(const c of o)if(!a.isStringLiteral(c))throw d(c,`index "${i}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>a.isStringLiteral(c));for(const c of l)Ve(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},Ue=e=>{const[t,n]=e;let r="_unknown_",s,i,o,l;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=S(n,"filterFields"),i=f(n,"language"),o=B(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:w(t),staged:o,strategy:l}},Ke=e=>{const[t,n]=e;let r="_unknown_",s;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=I(n,"precision")),{field:r,name:w(t),precision:s}},We=e=>{const[t,n]=e,r=t&&a.isStringLiteral(t)?t.getLiteralText():"_unknown_";let s;return n&&a.isObjectLiteralExpression(n)&&(s=I(n,"after")),{after:s,field:r}},He=e=>{if(!a.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Xe=e=>{const[t,n]=e;let r=[],s;if(n&&a.isObjectLiteralExpression(n)){const i=m(n,"sortBy");if(i&&a.isPropertyAssignment(i)){const o=i.getInitializer();o&&a.isArrayLiteralExpression(o)&&(r=o.getElements().map(l=>He(l)).filter(l=>l!==void 0))}s=S(n,"partitionBy")}return{name:w(t),partitionBy:s,sortBy:r}},Ze=(e,t)=>{const[n,r]=e,s=n&&a.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!r||!a.isObjectLiteralExpression(r)))return{dimensions:I(r,"dimensions"),field:s,metadata:S(r,"metadata"),metric:V(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Ge=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},z=(e,t)=>{if(e===void 0)return t;if(!a.isObjectLiteralExpression(e))throw d(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=m(e,"field");if(n===void 0)return t;const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(r&&a.isStringLiteral(r))return r.getLiteralText();throw d(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Qe=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:Ae(t,"columns"),hasReconcile:m(t,"reconcileEveryMs")!==void 0,hasSoftDelete:m(t,"softDeleteColumn")!==void 0,hasTenantBy:m(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},x=(e,t)=>t===void 0?e:{...e,site:t},Ye=(e,t,n,r,s)=>{const i=e.locate(s);switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(x(Ke(n),i));break}case"global":{e.shardMode="global",e.globalBackend=Ge(n);break}case"index":{e.indexes.unshift(x(Je(n),i));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(x(Xe(n),i));break}case"relations":{const o=n[0];o&&e.relations.push(...Be(o,e.locate));break}case"searchIndex":{e.searchIndexes.push(x(Ue(n),i));break}case"shardBy":{const o=n[0];e.shardMode={field:o&&a.isStringLiteral(o)?o.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:z(n[0],"deletedAt")};break}case"source":{e.externalSource=Qe(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(z(n[0],"updatedAt"));break}case"ttl":{e.ttl=We(n);break}case"vectorize":{const o=Ze(n,r);o&&e.vectorIndexes.push(x(o,i));break}}},M=["__vocab","_config","_content","_data","_docsize","_idx"],et=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of M){const o=`${s.name}${i}`;if(!r.has(o))continue;const l=i==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${s.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" 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 "${s.name}" and "${o}", whose generated FTS5 tables collide: "${s.name}" already owns "${t}__fts_${o}" as its "${i}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${M.join(", ")}.`)}},tt=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,Pe(t))},nt=(e,t,n)=>{const{softDelete:r,timestampsFields:s}=n,i={};r&&!(r.field in t)&&(i[r.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[o]=s;if(o===void 0)return{...t,...i};if(s.length>1)throw d(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(o===r?.field)throw d(e,`\`.softDelete()\` and \`.timestamps()\` both use "${o}"; give one of them another field.`);const l=t[o];if(l===void 0)i[o]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw d(e,`\`.timestamps()\` would add "${o}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...i}},k=4,rt=e=>{const t=e.getParent(),n=a.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol();return re(n?.isAlias()===!0?n.getAliasedSymbol():n)},A=(e,t)=>d(e,`table "${t}" is defined as ${JSON.stringify(e.getText())}, but codegen reads a table only from an inline defineTable(...) chain or one bound to a module-scope const. Inline the defineTable(...) call, or bind it to a const.`),st=(e,t,n)=>{const s=t.getParentIfKind(N.VariableDeclaration)?.getNameNode();if(!(s===void 0||!a.isIdentifier(s)))for(const i of s.findReferencesAsNodes()){const o=i.getParent();if(i!==e&&a.isPropertyAccessExpression(o)&&o.getExpression()===i&&a.isCallExpression(o.getParent())&&o.getParentIfKindOrThrow(N.CallExpression).getExpression()===o)throw d(i,`table "${n}" is built from "${s.getText()}", which also has .${o.getName()}(...) called on it outside the chain the schema uses. Table builder methods change the shared builder, so codegen cannot see that call. Chain every method in one expression.`)}},it=e=>{let t=0;return n=>{let r=D(n)??n;for(;a.isIdentifier(r);){if(t+=1,t>k)throw d(r,`table "${e}" is reached through more than ${String(k)} const bindings, and codegen follows at most ${String(k)}. Inline the defineTable(...) call.`);const s=rt(r);if(s===void 0)throw A(r,e);st(r,s,e),r=D(s)??s}return r}},ot=e=>e.getText()==="defineTable"?!0:e.getSymbol()?.getDeclarations().some(t=>a.isImportSpecifier(t)&&t.getName()==="defineTable")===!0,at=(e,t)=>{if(e===void 0)return{};if(a.isObjectLiteralExpression(e))return fe(e);throw d(e,`table "${t}" calls defineTable(${JSON.stringify(e.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.`)},K=(e,t,n=J)=>{const r={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,locate:n,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={};const i=it(t);let o=i(e),l=!1,c;for(;a.isCallExpression(o);){const g=o.getExpression(),h=o.getArguments();if(a.isPropertyAccessExpression(g))Ye(r,g.getName(),h,t,g.getNameNode()),o=i(g.getExpression());else if(a.isIdentifier(g)&&ot(g)){c=o,s=at(h[0],t),l=!0;break}else throw A(o,t)}if(!l)throw A(o,t);s=nt(e,s,r),et(e,t,r.searchIndexes),tt(e,t,r);const u=c===void 0?void 0:n(c);return{...r.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:r.commitOrdered,externallyManaged:r.externallyManaged,externalSource:r.externalSource,geoIndexes:r.geoIndexes,...u===void 0?{}:{site:u},globalBackend:r.shardMode==="global"?r.globalBackend??"d1":void 0,indexes:r.indexes,isPublic:r.isPublic,memory:r.memory,name:t,rankIndexes:r.rankIndexes,relations:r.relations,searchIndexes:r.searchIndexes,shape:s,shardMode:r.shardMode,softDelete:r.softDelete,ttl:r.ttl,vectorIndexes:r.vectorIndexes}},W=e=>a.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),H=(e,t=J,n=[],r=new Set,s=new Set)=>{s.add(e);for(const i of e.getProperties()){if(a.isSpreadAssignment(i)){const l=de(i.getExpression());l!==void 0&&!s.has(l)&&H(l,t,n,r,s);continue}if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(o){const l=P(i);if(O(l,i.getNameNode()),r.has(l))throw d(i.getNameNode(),`defineSchema({...}): table "${l}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);r.add(l),n.push(K(o,l,t))}}return n},lt=e=>{const t=m(e,"source");if(t&&a.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&a.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ct=(e,t)=>{if(!a.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!a.isCallExpression(n))return;const r=n.getExpression();if(!a.isIdentifier(r)||r.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!a.isObjectLiteralExpression(s))return;const i=e.getNameNode(),o=a.isStringLiteral(i)?i.getLiteralText():i.getText(),l=t(n);return{dimensions:I(s,"dimensions"),metric:V(f(s,"metric")),name:o,...l===void 0?{}:{site:l},table:lt(s)}},X=(e,t)=>{const n=[];for(const r of e.getProperties()){const s=ct(r,t);s&&n.push(s)}return n},L=(e,t)=>`${e}_${t}`,dt=(e,t)=>{if(!U.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.`)},y=(e,t,n)=>n.has(e)?L(t,e):e,E=(e,t)=>{const n=r=>r===void 0?void 0:E(r,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(r=>E(r,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([r,s])=>[r,E(s,t)]))}}},ft=(e,t,n,r)=>{const s=L(t,e.name);return{...e,extensionKey:t,...r?{extensionFromPackage:!0}:{},name:s,shape:Object.fromEntries(Object.entries(e.shape).map(([i,o])=>[i,E(o,l=>y(l,t,n))])),relations:e.relations.map(i=>{const o=y(i.table,t,n);return i.through===void 0?{...i,table:o}:{...i,table:o,through:{...i.through,table:y(i.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,t,n)}))}},ut=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},gt=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},mt=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},pt=e=>{if(a.isObjectLiteralExpression(e))return e;if(a.isCallExpression(e)){const t=e.getExpression();let n;if(a.isIdentifier(t)?n=t.getText():a.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const r=e.getArguments()[1];return r&&a.isObjectLiteralExpression(r)?r:void 0}}},ht=(e,t)=>{const n=ut(e);if(n){if(a.isPropertyAccessExpression(t)){const r=pt(n);return r?v(r,t.getName()):void 0}return n}},bt=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,gt(t))return t;const r=mt(t),s=r&&a.isIdentifier(r)?r.getSymbol():void 0,o=(s?.getAliasedSymbol()?.getDeclarations()??s?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ht(o,t)}},xt=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},yt=(e,t)=>{const n=m(e,"tables");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();if(!r||!a.isObjectLiteralExpression(r))return[];const s=[];for(const i of r.getProperties()){if(!a.isPropertyAssignment(i)&&!a.isShorthandPropertyAssignment(i))continue;const o=W(i);if(!o)continue;const l=P(i);O(l,i.getNameNode()),s.push(K(o,l,t))}return s},vt=(e,t)=>{const n=m(e,"vectorIndexes");if(!n||!a.isPropertyAssignment(n))return[];const r=n.getInitializer();return!r||!a.isObjectLiteralExpression(r)?[]:X(r,t)},Z=(e,t,n,r,s)=>{dt(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>ft(c,e,i,s)),l=n.map(c=>({...c,name:L(e,c.name),table:y(c.table,e,i)}));return{tables:o,vectorIndexes:l}},Et=(e,t,n,r)=>Z(e,yt(n,r),vt(n,r),t,t.getSourceFile().getFilePath().includes("/node_modules/")),It=(e,t,n)=>{const r=e.getArguments()[0];if(!r)return;let s=r;for(;a.isParenthesizedExpression(s)||a.isAsExpression(s)||a.isSatisfiesExpression(s);)s=s.getExpression();const i=bt(s);if(!i){if(t!==void 0){const l=ke(s,t);if(l){for(const c of l.bareTables)O(c.name,s);return Z(l.key,l.bareTables,l.bareVectorIndexes,s,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${s.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. If the receiver is a component built with options codegen cannot evaluate (a function, a variable), extend with the standalone extension the package exports instead (e.g. \`presenceExtension\`, \`actionCacheExtension\` or \`documentHistoryExtension\` from \`@lunora/server\`).`);return}const o=xt(i);if(!o){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Et(o.key,o.keyNode,o.options,n)},St=e=>{const t=[];let n=e;for(;;){const r=n.getParent();if(!r||!a.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!a.isCallExpression(s))break;r.getName()==="extend"&&t.push(s),n=s}return t},wt=(e,t,n,r)=>{const s=new Set(t.map(o=>o.name)),i=[];for(const o of St(e)){const l=It(o,n,r);if(l){for(const c of l.tables){if(s.has(c.name))throw d(o,`defineSchema(...).extend(...): table "${c.name}" already exists — another extension with the same key already contributed it.`);s.add(c.name),t.push(c)}i.push(...l.vectorIndexes)}}return i},Tt=new Set(["eu","fedramp","us"]),kt=e=>q(e,"jurisdiction","jurisdiction",Tt,'"eu", "us", or "fedramp"'),Nt=e=>{let t=e;for(;;){const n=t.getParent(),r=n?.getParent();if(!n||!a.isPropertyAccessExpression(n)||!r||!a.isCallExpression(r))return!1;if(n.getName()==="jurisdiction"){const s=r.getArguments()[1];return s!==void 0&&a.isObjectLiteralExpression(s)&&B(s,"pinAuth")===!0}t=r}},At=new Set(["required"]),Pt=e=>q(e,"rls","rls mode",At,'"required"'),Ot=e=>{if(!a.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(!r||!a.isCallExpression(r))return;const s=r.getExpression(),i=r.getArguments()[1],o=i&&a.isObjectLiteralExpression(i)?f(i,"on"):void 0;if(!a.isIdentifier(s)||s.getText()!=="defineAggregateIndex"||o===void 0)return;t.add(o)}return t},Lt=(e,t)=>{if(t===void 0)return;const n=Ot(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},Jt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=se(r,N.CallExpression).find(p=>{const _=p.getExpression();return a.isIdentifier(_)&&_.getText()==="defineSchema"});if(!s)throw new te("INTERNAL",`defineSchema() not found in ${t}`);const i=s.getArguments()[0];if(!i||!a.isObjectLiteralExpression(i))throw d(s,"defineSchema() expects an object literal");const o=je(ee(t)),l=H(i,o),c=s.getArguments()[1],u=c&&a.isObjectLiteralExpression(c)?X(c,o):[],g=wt(s,l,n,o);Lt(l,s.getArguments()[2]);const h=[...l.flatMap(p=>p.vectorIndexes),...u,...g],G=new Set(l.filter(p=>p.shardMode==="global").map(p=>p.name)),T=h.find(p=>G.has(p.table));if(T)throw d(s,ge(T.table,T.name));return{jurisdiction:kt(s),...Nt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:Pt(s),tables:l,vectorIndexes:h}};export{Jt as default};
@@ -1 +1 @@
1
- import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-Uwb5a6Kq.mjs";import{w as d}from"./classify-procedure-call-BmEirzc_.mjs";import{e as m}from"./exported-procedure-chains-CfH5jrzD.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"./isTestPath-DJeZ18i9.mjs";import{w as d}from"./classify-procedure-call-BK_MMoue.mjs";import{e as m}from"./exported-procedure-chains-ej9ozyZB.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 +1 @@
1
- import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-Cwt30DDJ.mjs";import{c as n}from"./classify-procedure-call-BmEirzc_.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
1
+ import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-B8xa6AeK.mjs";import{c as n}from"./classify-procedure-call-BK_MMoue.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
@@ -1 +1 @@
1
- import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-Uwb5a6Kq.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
1
+ import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-DJeZ18i9.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
@@ -1 +1 @@
1
- import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-Uwb5a6Kq.mjs";import{r as v,h}from"./attribution-Cwt30DDJ.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
1
+ import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-DJeZ18i9.mjs";import{r as v,h}from"./attribution-B8xa6AeK.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-Uwb5a6Kq.mjs";import{e as K,i as O}from"./attribution-Cwt30DDJ.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-DvbyiLjc.mjs";import{m as J}from"./ip-reads-By7tJdyu.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BmEirzc_.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
1
+ import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-DJeZ18i9.mjs";import{e as K,i as O}from"./attribution-B8xa6AeK.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-BnsKyz9W.mjs";import{m as J}from"./ip-reads-D8rPYtZ6.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BK_MMoue.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
@@ -1 +1 @@
1
- import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f,declarationLineOf as m}from"./isTestPath-Uwb5a6Kq.mjs";import{j as p,h as d}from"./attribution-Cwt30DDJ.mjs";import{t as g}from"./database-calls-d-Sssc-3.mjs";import{w as h,c as k}from"./classify-procedure-call-BmEirzc_.mjs";import{a as v}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return v(e)},P=e=>h(e,"use","mask"),E=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},y=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},C=e=>{const s=P(e);return{maskColumns:s.flatMap(t=>y(t)),usesMask:s.length>0}},M=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","insert","patch","replace"]),A=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=k(t);if(!i)return;const o=i.receiver?C(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=g(e,M,x);return{exportName:d(e)??e.getName(),file:s,line:m(e),maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},z=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of p(o)){const c=A(a,n);c&&t.push(c)}}return t};export{l as a,z as d,P as m,E as s};
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f,declarationLineOf as m}from"./isTestPath-DJeZ18i9.mjs";import{j as p,h as d}from"./attribution-B8xa6AeK.mjs";import{t as g}from"./database-calls-Cug60vT9.mjs";import{w as h,c as k}from"./classify-procedure-call-BK_MMoue.mjs";import{a as v}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return v(e)},P=e=>h(e,"use","mask"),E=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},y=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},C=e=>{const s=P(e);return{maskColumns:s.flatMap(t=>y(t)),usesMask:s.length>0}},M=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","insert","patch","replace"]),A=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=k(t);if(!i)return;const o=i.receiver?C(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=g(e,M,x);return{exportName:d(e)??e.getName(),file:s,line:m(e),maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},z=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of p(o)){const c=A(a,n);c&&t.push(c)}}return t};export{l as a,z as d,P as m,E as s};
@@ -0,0 +1 @@
1
+ import{Node as r,SyntaxKind as l,VariableDeclarationKind as at}from"ts-morph";import{isConstDeclaration as B,unwrapExpression as u,descendantsOfKind as ct,bindingKeyName as Ee,findObjectProperty as lt}from"./isTestPath-DJeZ18i9.mjs";import{r as dt,b as F,d as m}from"./attribution-B8xa6AeK.mjs";import{i as Oe,r as ce,c as N,a as ut}from"./context-root-CO8PbZi5.mjs";import{a as ne,s as h}from"./property-name-7cBlgK_O.mjs";const gt=s=>{const e=s.getText(),t=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===e};for(const n of s.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(l.BindingElement).find(a=>t(a));if(o!==void 0)return o}},pt=s=>{let e=s;for(;;){const t=e.getParent();if(!r.isObjectBindingPattern(t))return;const n=t.getParent();if(r.isBindingElement(n)){e=n;continue}return r.isParameterDeclaration(n)?Ee(e):void 0}},ft=s=>{const e=s.getText();if(!s.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===e:a.getDescendantsOfKind(l.BindingElement).some(d=>d.getName()===e))&&Oe(a)}))return!1;const n=m(s),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(l.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Oe(i)},Se=(s,e)=>{const t=s.getParent();if(r.isPropertyAccessExpression(t)&&t.getNameNode()===s||r.isPropertyAssignment(t)&&t.getNameNode()===s)return!1;if(s.getText()===e)return!0;const n=gt(s);return n!==void 0&&pt(n)===e?!0:e==="args"&&ft(s)},K=(s,e)=>r.isIdentifier(s)?Se(s,e):s.getDescendantsOfKind(l.Identifier).some(t=>Se(t,e)),Le=s=>{let e=s;for(;r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isNonNullExpression(e);)e=e.getExpression();return r.isIdentifier(e)?e:void 0},v=s=>{const e=r.isIdentifier(s)?m(s):void 0;return r.isVariableDeclaration(e)&&r.isIdentifier(e.getNameNode())&&!F(e)?e.getInitializer():void 0},mt=(s,e)=>{const t=s.getParent();if(r.isVariableDeclarationList(t)&&t.getDeclarationKind()===at.Var)return e;const n=t.getParent();return r.isVariableStatement(n)?n.getParent():n},Et=(s,e)=>{const t=s.getNameNode();return r.isIdentifier(t)?t.getText()===e:t.getDescendantsOfKind(l.BindingElement).some(n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===e})},re=s=>s.getDescendantsOfKind(l.Identifier).filter(e=>{const t=e.getParent();return!(r.isPropertyAccessExpression(t)&&t.getNameNode()===e)&&!(r.isPropertyAssignment(t)&&t.getNameNode()===e)}),D=s=>r.isIdentifier(s)?[s]:re(s),w=s=>{let e=s;for(;;){const t=e.getParent();if(!((r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t))&&t.getExpression()===e))return e;e=t}},vt=s=>{const e=s.getParent();return r.isCallExpression(e)&&e.getExpression()===s?e:void 0},Re=new Set(["find","findFirst","findFirstOrThrow","findMany","findUnique","first","get","unique"]),de=new Set(["findFirst","findUnique","first","get","unique"]),P=s=>{const e=s.getExpression();return r.isPropertyAccessExpression(e)&&Re.has(e.getName())&&N(e)?.[0]==="db"},z=(s,e)=>{for(let t=s,n=s.getParent();n!==void 0&&t!==e;t=n,n=n.getParent()){if(r.isConditionalExpression(n))return!0;if(r.isBinaryExpression(n)){const i=n.getOperatorToken().getKind();if(t===n.getRight()&&(i===l.QuestionQuestionToken||i===l.BarBarToken)||t===n.getLeft()&&i===l.AmpersandAmpersandToken)return!0}}return!1},ve=s=>{if(!r.isIdentifier(s)||s.getText()!=="undefined")return!1;const e=m(s);return e===void 0||e.getSourceFile().isDeclarationFile()},Fe=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),W=s=>{const e=u(s)??s;if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e)||r.isNumericLiteral(e)||r.isNullLiteral(e)||r.isTrueLiteral(e)||r.isFalseLiteral(e)||ve(e))return!0;const t=r.isIdentifier(e)?m(e):void 0,n=B(t)&&r.isSourceFile(t.getVariableStatement()?.getParent())?t.getInitializer():void 0;return n!==void 0&&!r.isIdentifier(u(n))&&W(n)},f=s=>{let e=s;for(let t=e.getParent();;t=e.getParent()){if(!(r.isParenthesizedExpression(t)||r.isNonNullExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isTypeAssertion(t)))return e;e=t}},q=s=>r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isFunctionDeclaration(s)||r.isMethodDeclaration(s),O=s=>{const e=s.getFirstAncestor(t=>q(t));return q(e)?e:void 0},Ce=new Set([l.GreaterThanEqualsToken,l.GreaterThanToken,l.InKeyword,l.InstanceOfKeyword,l.LessThanEqualsToken,l.LessThanToken]),xt=(s,e)=>{if(N(s)!==void 0||W(s))return!0;const t=m(s);if(t===void 0)return!1;if(t.getSourceFile().isDeclarationFile())return!0;const n=r.isParameterDeclaration(t)?t:t.getFirstAncestorByKind(l.Parameter);return e!==void 0&&n?.getParent().compilerNode===e.compilerNode},Q=(s,e)=>{const t=u(s)??s;if(r.isPrefixUnaryExpression(t)&&t.getOperatorToken()===l.ExclamationToken)return Q(t.getOperand(),e);if(r.isBinaryExpression(t)){const n=t.getOperatorToken().getKind();if(Fe.has(n)||Ce.has(n))return!0;if(n===l.AmpersandAmpersandToken)return Q(t.getLeft(),e)&&Q(t.getRight(),e)}return r.isTrueLiteral(t)||r.isFalseLiteral(t)?!0:!K(t,"args")&&D(t).every(n=>xt(n,e))},L=s=>{const e=m(s);return s.getSourceFile().getDescendantsOfKind(l.Identifier).filter(t=>t.getText()===s.getText()&&m(t)===e).filter(t=>{const n=t.getParent();return!((r.isVariableDeclaration(n)||r.isBindingElement(n))&&n.getNameNode()===t)})},Y=s=>{const e=O(s);if(e===void 0)return;const t=f(e).getParent();if(r.isCallExpression(t))return t.getArguments().includes(f(e))?e:void 0;const n=r.isVariableDeclaration(t)&&B(t)?t.getNameNode():void 0,i=r.isIdentifier(n)?L(n):[];return i.length>0&&i.every(o=>{const a=f(o),c=a.getParent();return r.isCallExpression(c)&&c.getArguments().includes(a)})?e:void 0},At=s=>{const e=f(s),t=e.getParent();return r.isArrowFunction(t)?t.getBody()===e&&Y(e)!==void 0:r.isReturnStatement(t)?Y(t)!==void 0:r.isIfStatement(t)||r.isWhileStatement(t)||r.isDoStatement(t)?t.getExpression()===e:r.isForStatement(t)||r.isConditionalExpression(t)?t.getCondition()===e:r.isPrefixUnaryExpression(t)?t.getOperatorToken()===l.ExclamationToken:r.isBinaryExpression(t)&&(Fe.has(t.getOperatorToken().getKind())||Ce.has(t.getOperatorToken().getKind()))},Pt=s=>{let e=s;for(let t=f(e).getParent();r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.AmpersandAmpersandToken;t=f(e).getParent())e=t;return At(e)&&Q(e,Y(e))},ue=(s,e)=>{for(let t=s,n=s.getParent();n!==void 0&&t!==e;t=n,n=n.getParent()){if(r.isConditionalExpression(n))return!0;const i=r.isBinaryExpression(n)?n.getOperatorToken().getKind():void 0;if(r.isBinaryExpression(n)&&(i===l.QuestionQuestionToken||i===l.BarBarToken)){if(t!==n.getLeft()||!W(n.getRight()))return!0}else if(r.isBinaryExpression(n)&&i===l.AmpersandAmpersandToken&&!Pt(n))return!0}return!1},ht=s=>{const e=O(s),t=e?.getBody();return e===void 0||!r.isBlock(t)||s.getParent()!==t?!1:e.getDescendantsOfKind(l.ReturnStatement).every(n=>n===s||O(n)!==e)},Nt=s=>{let e=f(s);for(let n=e.getParent();r.isBinaryExpression(n)&&n.getOperatorToken().getKind()===l.AmpersandAmpersandToken;n=e.getParent())e=f(n);const t=e.getParent();return r.isArrowFunction(t)&&t.getBody()===e||r.isReturnStatement(t)&&ht(t)},xe="userId",Z=s=>s?.length===2&&s[0]==="auth"&&s[1]===xe,I=s=>{let e=s;for(;;){const t=r.isNonNullExpression(e)||r.isAwaitExpression(e)?e.getExpression():u(e);if(t===void 0||t===e)return e;e=t}},T=s=>Z(N(I(s))),yt=new Set(["contains","gt","gte","isNull","lt","lte","ne","neq","not","notIn"]),ze=new Set(["NOT","not","OR"]),J=s=>{for(let e=s.getParent();e!==void 0&&!r.isCallExpression(e);e=e.getParent()){const t=r.isPropertyAssignment(e)?h(e.getNameNode()):void 0;if(t!==void 0&&ze.has(t))return!0}return!1},It=s=>s>=l.FirstAssignment&&s<=l.LastAssignment,ie=s=>{let e=s,t=e.getParent();for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t)||r.isArrayLiteralExpression(t)||r.isObjectLiteralExpression(t)||r.isSpreadElement(t)||r.isSpreadAssignment(t)||r.isShorthandPropertyAssignment(t)||r.isPropertyAssignment(t)&&t.getNameNode()!==e;)e=t,t=e.getParent();if(r.isBinaryExpression(t))return t.getLeft()===e&&It(t.getOperatorToken().getKind());if(r.isForOfStatement(t)||r.isForInStatement(t))return t.getInitializer()===e;if(r.isPrefixUnaryExpression(t)||r.isPostfixUnaryExpression(t)){const n=t.getOperatorToken();return n===l.PlusPlusToken||n===l.MinusMinusToken}return r.isDeleteExpression(t)},Ke=(s,e)=>s.every((t,n)=>n>=e.length||t===void 0||e[n]===void 0||t===e[n]),ge=(s,e)=>s.length<e.length&&Ke(s,e),_=s=>{const e=[];let t=f(s);for(let n=t.getParent();;n=t.getParent()){if(r.isPropertyAccessExpression(n)&&n.getExpression()===t)e.push(n.getName());else if(r.isElementAccessExpression(n)&&n.getExpression()===t){const i=u(n.getArgumentExpression());e.push(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i)?i.getLiteralValue():void 0)}else return{node:t,path:e};t=f(n)}},Ae=s=>{const e=s.getParent();return r.isCallExpression(e)&&e.getExpression()===s},qe=s=>{const e=s.getParent();if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),n=u(e.getLeft()===s?e.getRight():e.getLeft());return t===l.EqualsEqualsEqualsToken||t===l.ExclamationEqualsEqualsToken||(t===l.EqualsEqualsToken||t===l.ExclamationEqualsToken)&&(r.isNullLiteral(n)||ve(n))}return r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken||r.isTypeOfExpression(e)},Ve=(s,e)=>e.length===0&&qe(s),Tt=(s,e,t,n)=>{const i=s.getParent();if(r.isSpreadAssignment(i)||r.isVariableDeclaration(i)&&r.isObjectBindingPattern(i.getNameNode()))return t.every(c=>c.length===e.length+1);const a=r.isReturnStatement(i)&&n!==void 0&&O(i)?.compilerNode===n.compilerNode;return qe(s)||a},pe=(s,e,t=[])=>{const{node:n,path:i}=_(s),o=[...t,...i];if(ie(n))return i.length===0||!e.some(d=>Ke(o,d));if(Ae(n)){const d=o.slice(0,-1);return i.length===0||!e.some(g=>ge(d,g))}const a=e.filter(d=>ge(o,d)),c=m(s);return a.length===0||Tt(n,o,a,c===void 0?void 0:O(c))},oe=(s,e)=>{const t=s.getProperties(),n=r.isSpreadAssignment(e)?void 0:ne(e);return t.slice(t.indexOf(e)+1).some(i=>{if(r.isSpreadAssignment(i))return!0;const o=h(i.getNameNode());return o===void 0||o===n})},X=s=>{for(let e=s;e!==void 0&&!r.isCallExpression(e)&&!r.isVariableDeclaration(e)&&!q(e);e=e.getParent()){const t=e.getParent();if((r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&r.isObjectLiteralExpression(t)&&oe(t,e))return!0}return!1},De=(s,e)=>{const t=f(s),n=t.getParent();return r.isCallExpression(n)&&n.getArguments().includes(t)&&e(n)},Me=(s,e=P)=>{const t=f(s),n=t.getParent();if(r.isVariableDeclaration(n)&&B(n)){const i=n.getInitializer(),o=n.getNameNode(),a=r.isIdentifier(o)&&i===t?L(o):[];return a.length>0&&a.every(c=>De(c,e))}return De(t,e)},$=(s,e=P)=>{const t=f(s),n=t.getParent();if(r.isPropertyAssignment(n))return h(n.getNameNode())==="where"&&Me(n.getParent(),e);if(r.isArrayLiteralExpression(n)){const i=f(n).getParent();return r.isPropertyAssignment(i)&&h(i.getNameNode())==="AND"&&$(i.getParent(),e)}return r.isVariableDeclaration(n)?n.getInitializer()===t:!1},Ue=(s,e=P)=>{const t=s.getParent();if(!r.isObjectLiteralExpression(t)||!(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)))return!1;const n=h(s.getNameNode());if(n==="eq"||n==="in"){const i=f(t).getParent();return r.isPropertyAssignment(i)&&$(i.getParent(),e)}return $(t,e)},Ot=(s,e)=>{if(!r.isArrayLiteralExpression(s)||!s.getElements().every(a=>e.isCaller(a)))return!1;const t=f(s).getParent(),n=r.isVariableDeclaration(t)?t.getNameNode():void 0,o=r.isIdentifier(n)&&v(n)!==void 0?L(n):[s];return o.length>0&&o.every(a=>{const c=f(a).getParent();return r.isPropertyAssignment(c)&&h(c.getNameNode())==="in"&&!J(c)&&Ue(c,e.isRead)&&!X(c)})},St=s=>{const e=s.getPropertyNameNode();return!r.isComputedPropertyName(e)||W(e.getExpression())},Dt=s=>!F(s)&&[s,...s.getAncestors().filter(e=>r.isBindingElement(e))].every(e=>r.isBindingElement(e)&&e.getInitializer()===void 0&&e.getDotDotDotToken()===void 0&&St(e)),bt=(s,e,t)=>{const n=_(s).path;return t.getDescendantsOfKind(l.Identifier).filter(i=>i.getParent()!==e&&m(i)?.compilerNode===e?.compilerNode).every(i=>pe(i,[n]))},kt=(s,e)=>{const t=e===void 0?void 0:I(e);if(t===void 0)return!1;if(t===s)return!0;const n=r.isIdentifier(t)?v(t):void 0;return n!==void 0&&I(n)===s},wt=(s,e,t)=>{const n=u(s)??s,i=r.isPropertyAccessExpression(n)||r.isElementAccessExpression(n),o=i?Le(n):n,a=r.isIdentifier(o)?m(o):void 0,c=Y(e),d=c!==void 0&&kt(c,t)?c:void 0;let g;return r.isParameterDeclaration(a)&&i&&!F(a)?g=a.getParent():r.isBindingElement(a)&&Dt(a)&&(g=a.getFirstAncestorByKind(l.Parameter)?.getParent()),g!==void 0&&g===d&&r.isIdentifier(o)&&bt(o,a,g)},Bt=(s,e)=>{const{isRead:t,predicate:n}=e,i=s.getParent();if(r.isArrayLiteralExpression(i))return Ot(i,e);if(r.isPropertyAssignment(i)||r.isShorthandPropertyAssignment(i)){const c=h(i.getNameNode());return(r.isPropertyAssignment(i)?i.getInitializer():s)===s&&c!==void 0&&!yt.has(c)&&!ze.has(c)&&!J(i)&&Ue(i,t)&&!X(i)}if(r.isCallExpression(i)){const c=i.getExpression(),g=(r.isPropertyAccessExpression(c)?c.getName():void 0)==="eq"||t(i);return i.getArguments().includes(s)&&g}if(!r.isBinaryExpression(i))return!1;const o=i.getOperatorToken().getKind(),a=i.getLeft()===s?i.getRight():i.getLeft();return(o===l.EqualsEqualsEqualsToken||o===l.EqualsEqualsToken)&&Nt(i)&&wt(a,i,n)},Lt=(s,e)=>{if(!r.isCallExpression(s))return!1;const t=s.getExpression(),[n,...i]=s.getArguments(),o=r.isIdentifier(t)&&t.getText()==="String"?m(t):void 0;return n===e&&i.length===0&&o?.getSourceFile().isDeclarationFile()===!0},H=(s,e)=>{let t=w(s);for(let n=t.getParent();n!==void 0;n=t.getParent()){const i=r.isParenthesizedExpression(n)||r.isNonNullExpression(n)||r.isAsExpression(n)||r.isSatisfiesExpression(n)||r.isTypeAssertion(n)||r.isAwaitExpression(n),o=r.isBinaryExpression(n)?n.getOperatorToken().getKind():void 0,a=r.isBinaryExpression(n)&&(o===l.QuestionQuestionToken||o===l.BarBarToken)&&n.getLeft()===t&&W(n.getRight());if(!i&&!a&&!Lt(n,t))break;t=n}return Bt(t,e)},Rt=s=>{const e=f(s),t=e.getParent();if(r.isPropertyAssignment(t)||r.isShorthandPropertyAssignment(t))return h(t.getNameNode())==="where"&&!J(t)&&Me(t.getParent())&&!X(t);if(r.isArrayLiteralExpression(t)){const n=f(t).getParent();return r.isPropertyAssignment(n)&&h(n.getNameNode())==="AND"&&!J(n)&&$(n.getParent())&&!X(n)}return r.isCallExpression(t)&&t.getArguments().includes(e)&&P(t)},R=s=>{const e=I(s);if(r.isConditionalExpression(e))return[...R(e.getWhenTrue()),...R(e.getWhenFalse())];if(!r.isBinaryExpression(e))return[e];const t=e.getOperatorToken().getKind();return t===l.CommaToken?R(e.getRight()):t===l.QuestionQuestionToken||t===l.BarBarToken||t===l.AmpersandAmpersandToken?[...R(e.getLeft()),...R(e.getRight())]:[e]},We=s=>D(s).some(e=>{if(ue(e,s))return!1;if(T(w(e)))return H(e,{isCaller:T,isRead:P,predicate:s});const t=v(e),n=t===void 0?[]:R(t);if(n.length>0&&n.every(c=>T(c)))return H(e,{isCaller:T,isRead:P,predicate:s});const[i]=n,o=r.isObjectLiteralExpression(i),a=o||r.isArrayLiteralExpression(i)||r.isArrowFunction(i)||r.isFunctionExpression(i);return n.length!==1||i===void 0||!a||o&&!(r.isIdentifier(e)&&L(e).every(c=>Rt(c)))?!1:D(i).some(c=>T(w(c))&&!ue(c,i)&&H(c,{isCaller:T,isRead:P,predicate:s}))}),Ft=s=>P(s)&&s.getArguments().some(e=>We(e)),_e=(s,e)=>{for(let t=s.getParent();t!==void 0;t=t.getParent()){if(r.isCallExpression(t)&&N(t.getExpression())?.[0]==="db")return!0;if(t===e)return!1}return!1},Ct=new Set(["_id","id"]),Pe=s=>{let e=s;for(let t=e.getParent();;t=e.getParent()){if(r.isAwaitExpression(t)||r.isParenthesizedExpression(t)||r.isNonNullExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isTypeAssertion(t)){e=t;continue}if(r.isPropertyAccessExpression(t)&&t.getExpression()===e)return{field:t.getName(),read:t};if(r.isElementAccessExpression(t)&&t.getExpression()===e){const n=u(t.getArgumentExpression());return{field:r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)?n.getLiteralValue():void 0,read:t}}return{field:void 0,read:e}}},he=s=>r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():void 0,be=s=>{const e=f(s).getParent();return r.isCallExpression(e)&&P(e)&&e.getArguments().includes(f(s))},zt=s=>L(s).every(e=>{if(be(e))return!0;const t=f(e),n=t.getParent(),i=n?.getParent();return(r.isPropertyAssignment(n)&&n.getNameNode()!==t&&ne(n)==="where"||r.isShorthandPropertyAssignment(n)&&n.getName()==="where")&&i!==void 0&&be(i)}),ee=s=>{const e=u(s);if(r.isObjectLiteralExpression(e))return e;const t=r.isIdentifier(e)&&zt(e)?u(v(e)):void 0;return r.isObjectLiteralExpression(t)?t:void 0},Kt=s=>{const e=u(s)??s;if(!r.isObjectLiteralExpression(e))return T(s);const[t,...n]=e.getProperties(),i=n.length===0&&r.isPropertyAssignment(t)&&ne(t)==="eq"?t.getInitializer():void 0;return i!==void 0&&T(i)},Ne=s=>s.getProperties().some(e=>r.isGetAccessorDeclaration(e)||r.isSetAccessorDeclaration(e)||r.isMethodDeclaration(e)),Ge=(s,e)=>!Ne(s)&&s.getProperties().some(t=>{const n=he(t);if(n===void 0||r.isSpreadAssignment(t)||oe(s,t))return!1;const i=h(t.getNameNode());if(i===void 0)return!1;if(i==="AND"){const o=u(n);return r.isArrayLiteralExpression(o)&&o.getElements().some(a=>{const c=ee(a);return c!==void 0&&Ge(c,e)})}return(e===void 0||i===e)&&Kt(n)}),je=(s,e)=>{const t=ee(s),n=t===void 0?void 0:lt(t,"where"),i=t===void 0||n===void 0||Ne(t)||oe(t,n)?void 0:ee(he(n));return i!==void 0&&Ge(i,e)},Qe=s=>s.getArguments().some(e=>T(e)||je(e,void 0)),qt=(s,e)=>e===void 0?!1:Ct.has(e)?Qe(s):s.getArguments().some(t=>je(t,e)),Vt=new Set(["_creationTime","_id"]),Mt=(s,e)=>Vt.has(e)||s.getArguments().every(t=>{const n=ee(t);if(n===void 0)return!0;const i=n.getProperties(),o=i.findLast(c=>!r.isSpreadAssignment(c)&&ne(c)==="select");if(Ne(n))return!1;if(o===void 0)return!i.some(c=>r.isSpreadAssignment(c)||h(c.getNameNode())===void 0);if(oe(n,o))return!1;const a=u(he(o));return r.isArrayLiteralExpression(a)&&a.getElements().some(c=>(r.isStringLiteral(c)||r.isNoSubstitutionTemplateLiteral(c))&&c.getLiteralValue()===e)}),V=(s,e,t,n)=>{const i=s.getExpression(),o=r.isPropertyAccessExpression(i)&&(de.has(i.getName())||i.getName().endsWith("OrThrow"));return!Ft(s)||!o||t!==void 0&&!Mt(s,t)?!1:n!==void 0&&u(e)===u(n)&&Qe(s)||qt(s,t)},ye=(s,e)=>{const t=e.getExpression(),n=r.isPropertyAccessExpression(t)&&t.getName().endsWith("OrThrow");return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.hasQuestionDotToken()&&!n},He=(s,e)=>D(s).some(t=>{const n=w(t),i=N(n)?.[0];if(i==="auth")return!z(t,s)&&!_e(t,s);const o=i==="db"&&!z(t,s)?vt(n):void 0;if(o===void 0)return!1;const{field:a,read:c}=Pe(o);return!ye(c,o)&&V(o,c,a,e)}),Ut=s=>{const e=u(s);return r.isAwaitExpression(e)?u(e.getExpression()):e},M=s=>{const e=[];let t=u(s);for(;t!==void 0;)if(r.isPropertyAccessExpression(t))e.unshift(t.getName()),t=u(t.getExpression());else if(r.isElementAccessExpression(t)){const n=t.getArgumentExpression();if(!r.isStringLiteral(n))return;e.unshift(n.getLiteralValue()),t=u(t.getExpression())}else return r.isIdentifier(t)?{path:e,root:t}:void 0},S=(s,e)=>m(s)?.compilerNode===e.compilerNode,Ye=s=>{if(!r.isIdentifier(s))return;const e=dt(s),t=e?.isAlias()===!0?e.getAliasedSymbol():e,n=t?.getValueDeclaration()??t?.getDeclarations()[0];if(n===void 0)return;const i=n.getSourceFile();if(i.isDeclarationFile()||i.isInNodeModules())return;if(r.isFunctionDeclaration(n))return n.getBody()===void 0||n.isGenerator()||F(n)?void 0:n;if(!B(n))return;const o=u(n.getInitializer());return r.isArrowFunction(o)||r.isFunctionExpression(o)&&!o.isGenerator()?o:void 0},Ze=(s,e,t)=>s.getStart()<e.getEnd()||O(s)?.compilerNode!==t.compilerNode?!0:e.getAncestors().some(n=>r.isIterationStatement(n)&&n.getStart()<=s.getStart()&&s.getEnd()<=n.getEnd()),Wt=(s,e,t)=>e.getDescendantsOfKind(l.Identifier).some(n=>n.getText()===s.getName()&&ie(n)&&m(n)?.compilerNode===s.compilerNode&&Ze(n,t,e)),Ie=s=>{const e=[],t=[];let n=u(s);for(;n!==void 0;)if(r.isCallExpression(n))e.push(n),n=u(n.getExpression());else if(r.isPropertyAccessExpression(n))t.unshift(n.getName()),n=u(n.getExpression());else if(r.isElementAccessExpression(n)){const i=n.getArgumentExpression();if(!r.isStringLiteral(i))return;t.unshift(i.getLiteralValue()),n=u(n.getExpression())}else return r.isIdentifier(n)&&e.length>0&&t.length>0?{calls:e,names:t,root:n}:void 0},Te=s=>{const e=s.names[s.names.length-1]??"";if(de.has(e))return{selfEnforcing:!1};const t=e.endsWith("OrThrow")?e.slice(0,-7):void 0;return t!==void 0&&de.has(t)?{selfEnforcing:!0}:void 0},_t=s=>{const e=u(s),t=r.isIdentifier(e)?u(v(e))??e:e,n=M(t);if(n===void 0||n.path.length===0)return;const i=m(n.root);if(!B(i)||!r.isIdentifier(i.getNameNode()))return;const o=Ut(i.getInitializer()),a=r.isCallExpression(o)&&N(o.getExpression())?.[0]==="db"?Ie(o):void 0;return a!==void 0&&Te(a)!==void 0?{keyPath:n.path,row:i}:void 0},Gt=(s,e,t)=>{const n=s.getDescendantsOfKind(l.Identifier).filter(o=>o!==e.getNameNode()&&m(o)?.compilerNode===e.compilerNode);return{reads:n.flatMap(o=>{const{node:a,path:c}=_(o),d=[...t,...Ae(a)?c.slice(0,-1):c];return Ve(a,d)||ie(a)?[]:[d]}),uses:n.map(o=>({prefix:t,use:o}))}},Je=s=>s.calls.flatMap(e=>e.getArguments().flatMap(t=>[t,...t.getDescendants()])),jt=(s,e)=>{const t=r.isIdentifier(s)?m(s):void 0;if(!r.isBindingElement(t)||t.getDotDotDotToken()!==void 0||t.getInitializer()!==void 0)return!1;const n=t.getParent(),i=r.isObjectBindingPattern(n)?n.getParent():void 0;if(!B(i))return!1;const o=M(i.getInitializer());return o!==void 0&&Z([...o.path,Ee(t)])&&S(o.root,e)},ke=(s,e)=>{const t=M(s);if(t!==void 0&&t.path.length>0)return Z(t.path)&&S(t.root,e);const n=M(v(s));return n!==void 0&&Z(n.path)&&S(n.root,e)?!0:jt(s,e)},Qt=(s,e)=>{const t=s.getExpression();if(!r.isPropertyAccessExpression(t)||!Re.has(t.getName()))return!1;let n=t;for(;(r.isPropertyAccessExpression(n)||r.isElementAccessExpression(n))&&!r.isIdentifier(n.getExpression());)n=n.getExpression();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isPropertyAccessExpression(n)&&n.getName()==="db"&&r.isIdentifier(i)&&m(i)?.compilerNode===e.compilerNode},Ht=(s,e)=>[s,...s.getDescendants()].some(t=>ke(t,e)&&!ue(t,s)&&H(t,{isCaller:n=>ke(I(n),e),isRead:n=>Qt(n,e),predicate:s})),Xe=s=>{if(!r.isVariableStatement(s))return;const e=s.getDeclarations(),t=e.length===1?e[0]:void 0;return t!==void 0&&B(t)&&r.isIdentifier(t.getNameNode())?t:void 0},Yt=(s,e)=>{const t=u(s),n=d=>r.isIdentifier(d)&&S(d,e);if(r.isPrefixUnaryExpression(t))return t.getOperatorToken()===l.ExclamationToken&&n(u(t.getOperand()));if(!r.isBinaryExpression(t))return!1;const i=t.getOperatorToken().getKind(),o=d=>i===l.EqualsEqualsEqualsToken?r.isNullLiteral(d):i===l.EqualsEqualsToken&&(r.isNullLiteral(d)||ve(d)),a=u(t.getLeft()),c=u(t.getRight());return n(a)&&o(c)||n(c)&&o(a)},Zt=(s,e)=>{const t=r.isBlock(s)?s.getStatements():void 0,n=t===void 0?s:t[t.length-1];return r.isThrowStatement(n)||!e&&r.isReturnStatement(n)},$e=(s,e,t)=>r.isIfStatement(s)&&s.getElseStatement()===void 0&&Yt(s.getExpression(),e)&&Zt(s.getThenStatement(),t),Jt=(s,e,t)=>{const n=s.getBody();if(!r.isBlock(n))return;const i=n.getStatements();return i.find((o,a)=>{const c=Xe(o),d=u(c?.getInitializer()),g=r.isAwaitExpression(d)?Ie(d.getExpression()):void 0,A=g===void 0?void 0:Te(g);if(c===void 0||g===void 0||A===void 0||g.names[0]!=="db"||!S(g.root,e))return!1;const b=Je(g),E=g.calls.some(x=>x.getArguments().some(G=>Ht(G,e))),y=t.some(x=>b.some(G=>r.isIdentifier(G)&&S(G,x)));if(!E||!y)return!1;const p=A.selfEnforcing?o:i.slice(a+1).find(x=>$e(x,c,!0));return p!==void 0&&!s.getDescendantsOfKind(l.ReturnStatement).some(x=>O(x)?.compilerNode===s.compilerNode&&x.getStart()<p.getEnd())})},Xt=(s,e,t,n)=>{const i=[];for(const[o,a]of e.entries()){const c=M(u(a));if(o!==t&&c!==void 0&&S(c.root,n)){const d=s.getParameters()[o];if(d===void 0||d.isRestParameter()||!r.isIdentifier(d.getNameNode()))return;i.push({argument:a,tied:d,...Gt(s,d,c.path)})}}return i},$t=s=>!r.isArrowFunction(s)&&re(s).some(e=>e.getText()==="arguments"&&e.getFirstAncestor(t=>q(t)&&!r.isArrowFunction(t))?.compilerNode===s.compilerNode),es=(s,e,t)=>{const n=Ye(s.getExpression()),i=s.getArguments();if(n===void 0||i.some(p=>r.isSpreadElement(p)))return;const o=i.flatMap((p,x)=>N(p)?.length===0?[x]:[]),a=o.length===1?o[0]:void 0,c=a===void 0?void 0:n.getParameters()[a];if(a===void 0||c===void 0||c.isRestParameter()||!r.isIdentifier(c.getNameNode()))return;const d=Xt(n,i,a,e);if(d===void 0)return;const g=d.map(({tied:p})=>p),A=d.flatMap(({reads:p})=>p),b=n.getReturnType(),E=n.isAsync()||b.isAny()||b.isUnknown()||b.getText().includes("Promise");if(g.length===0||!t&&E||$t(n))return;const y=Jt(n,c,g);if(y!==void 0)return[c,...g].some(p=>p.hasInitializer()||Wt(p,n,y))?void 0:{guardedPaths:A,helperArguments:d.map(({argument:p})=>p),helperUses:d.flatMap(({uses:p})=>p)}},ts=(s,e)=>{const t=Xe(s),n=u(t?.getInitializer()),i=r.isAwaitExpression(n)?Ie(n.getExpression()):void 0,o=i===void 0?void 0:Te(i);if(t===void 0||i===void 0||o===void 0||i.names[0]!=="db"||N(i.root)?.length!==0)return;const a=i.calls.some(d=>d.getArguments().some(g=>We(g))),c=Je(i).some(d=>r.isIdentifier(d)&&S(d,e));return a&&c?{declaration:t,selfEnforcing:o.selfEnforcing}:void 0},ss=(s,e,t)=>{const n=(i,o)=>o.getStart()<=i.getStart()&&i.getEnd()<=o.getEnd();for(let i=s.getParent();i!==void 0&&i.compilerNode!==e.compilerNode;i=i.getParent()){if(q(i)||r.isIfStatement(i)||r.isIterationStatement(i)||r.isCaseClause(i)||r.isDefaultClause(i)||r.isCatchClause(i))return!1;if(r.isTryStatement(i)&&i.getCatchClause()!==void 0){const o=i.getTryBlock();if(!n(s,o)||!n(t,o))return!1}}return!0},ns=(s,e)=>[s,...e.filter(t=>!ge(s,t))],rs=(s,e)=>s.getDescendantsOfKind(l.Identifier).flatMap(t=>{if(!S(t,e))return[];const{node:n,path:i}=_(t),o=Ae(n)?i.slice(0,-1):i;return Ve(n,o)?[]:[o]}),is=(s,e)=>{if(!r.isExpressionStatement(s))return;const t=u(s.getExpression()),n=r.isAwaitExpression(t),i=n?u(t.getExpression()):t;return r.isCallExpression(i)?es(i,e,n):void 0},os=(s,e,t,n,i)=>s.slice(0,e).flatMap((o,a)=>{if(!ss(o,n,i))return[];const c=is(o,t);if(c!==void 0)return[c];const d=ts(o,t);return d!==void 0&&(d.selfEnforcing||a+1<e&&$e(s[a+1],d.declaration,!1))?[{guardedPaths:rs(d.declaration,t)}]:[]}),ae=s=>{let e=u(s)??s;for(;r.isAwaitExpression(e);)e=u(e.getExpression())??e.getExpression();return e},j=s=>{const e=ae(s);return r.isCallExpression(e)||r.isNewExpression(e)},as=s=>{const e=ae(s);return r.isCallExpression(e)&&N(e.getExpression())?.[0]==="db"},et=s=>{const e=ae(s);return r.isCallExpression(e)&&P(e)},fe=s=>K(s,"args")||D(s).some(e=>{const t=v(e);return t!==void 0&&K(t,"args")}),te=(s,e)=>{const t=s?.getNameNode().getDescendantsOfKind(l.BindingElement).find(n=>r.isIdentifier(n.getNameNode())&&n.getNameNode().getText()===e);return t===void 0?[]:[t,...t.getAncestors().filter(n=>r.isBindingElement(n))].map(n=>r.isBindingElement(n)?n.getInitializer():void 0).filter(n=>n!==void 0)},tt=s=>{const e=r.isIdentifier(s)?m(s):void 0;if(!r.isBindingElement(e)||F(e))return;const t=e.getFirstAncestorByKind(l.VariableDeclaration),n=t?.getInitializer();if(!te(t,s.getText()).some(i=>fe(i)))return n!==void 0&&et(n)?n:void 0},U=s=>{const e=ae(s);return r.isCallExpression(e)&&P(e)?e:void 0},st=s=>{if(!(!r.isBindingElement(s)||!r.isObjectBindingPattern(s.getParent())||s.getDotDotDotToken()!==void 0||r.isBindingElement(s.getParent().getParent())))return Ee(s)},nt=s=>L(s).every(e=>{const t=f(e),n=t.getParent();return r.isVariableDeclaration(n)&&r.isObjectBindingPattern(n.getNameNode())||r.isSpreadAssignment(n)?!0:(r.isPropertyAccessExpression(n)||r.isElementAccessExpression(n))&&n.getExpression()===t&&!ie(f(w(n)))}),we=(s,e)=>{const t=e!==void 0&&u(s)===u(e),n=v(s);if(n!==void 0){const a=U(n);if(a===void 0)return He(n,t?n:void 0);if(r.isIdentifier(s)&&!nt(s))return!1;const{field:c,read:d}=Pe(s);return ye(d,a)?!1:V(a,d,c,e)}const i=tt(s),o=i===void 0?void 0:U(i);return o!==void 0&&r.isIdentifier(s)&&V(o,s,st(m(s)),e)},C=(s,e=!0)=>{const t=I(s);if(r.isTemplateExpression(t))return t.getTemplateSpans().flatMap(o=>C(o.getExpression(),e));if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.PlusToken)return[...C(t.getLeft(),e),...C(t.getRight(),e)];const n=e&&r.isIdentifier(t)?v(t):void 0,i=n===void 0?void 0:I(n);return i!==void 0&&(r.isTemplateExpression(i)||r.isBinaryExpression(i)&&i.getOperatorToken().getKind()===l.PlusToken)?C(i,!1).map(({part:o})=>({anchor:t,part:o})):[{anchor:t,part:t}]},cs=s=>r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)||r.isNumericLiteral(s),ls=s=>{const e=I(s.getExpression()),t=r.isIdentifier(e)?v(e):void 0;if(r.isIdentifier(e)&&t!==void 0&&!nt(e))return!1;const n=U(e)??(t===void 0?void 0:U(t));return n!==void 0&&!ye(s,n)&&V(n,s,Pe(s.getExpression()).field,void 0)},ds=s=>{const e=m(s),t=st(e),n=r.isBindingElement(e)?e.getFirstAncestorByKind(l.VariableDeclaration)?.getInitializer():void 0,i=n===void 0?void 0:N(I(n));if(i!==void 0)return i.length===1&&i[0]==="auth"&&t===xe;const o=tt(s),a=o===void 0?void 0:U(o);return a!==void 0&&V(a,s,t,void 0)},rt=(s,e=!0)=>{const t=I(s),n=r.isIdentifier(t)?m(t):void 0;if((r.isVariableDeclaration(n)||r.isBindingElement(n))&&F(n))return!1;const i=N(t);if(i!==void 0)return i.length===2&&i[0]==="auth"&&i[1]===xe;if(r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t))return ls(t);if(!r.isIdentifier(t))return!1;const o=v(t);return o===void 0?ds(t):e&&rt(o,!1)},Be=(s,e,t=s)=>{const n=C(e),i=(g,A)=>g.getPos()<=A.getPos()&&A.getEnd()<=g.getEnd(),o=n.findIndex(({part:g})=>!cs(g)),a=n.findIndex(({part:g})=>i(g,s)),c=a===-1?n.findIndex(({anchor:g,part:A})=>i(A,t)||i(g,t)):a,d=n[o];return d!==void 0&&o<c&&rt(d.part)},k=s=>K(s,"args"),se=s=>{if(!r.isIdentifier(s))return;const e=s.getText(),t=s.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(t===void 0)return;const n=s.getStart();let i,o=-1;for(const a of ct(t,l.VariableDeclaration)){if(!Et(a,e))continue;const c=mt(a,t);if(c===void 0||n<c.getStart()||n>=c.getEnd())continue;const d=a.getInitializer(),g=a.getStart();d!==void 0&&g<n&&g>o&&(i=a,o=g)}return i},me=s=>se(s)?.getInitializer(),Ss=s=>{if(k(s))return!0;const e=t=>{const n=se(t),i=n?.getInitializer();return i!==void 0&&k(i)||te(n,t.getText()).some(o=>k(o))};return e(s)||re(s).some(t=>e(t))},Ds=s=>{if(j(s))return!1;if(te(se(s),s.getText()).some(n=>k(n)&&!j(n)))return!0;const e=me(s);if(e!==void 0&&j(e)&&!(et(e)&&k(e)))return!1;const t=e??s;return k(t)?!0:re(t).some(n=>{if(n.getFirstAncestor(c=>c===t||r.isCallExpression(c)||r.isNewExpression(c))!==t)return!1;const o=se(n),a=c=>c!==void 0&&k(c)&&(!j(c)||as(c));return a(o?.getInitializer())||te(o,n.getText()).some(c=>a(c))})},bs=s=>{if(ce(s))return!0;const e=v(s);if(e!==void 0&&ce(e))return!0;const t=e??s;return(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(l.Identifier)).some(i=>{const o=v(i);return o!==void 0&&ce(o)})},ks=s=>{const e=v(s)??s,t=a=>D(a).some(c=>z(c,a)&&fe(w(c))&&!Be(c,a)),n=D(e).some(a=>{const c=v(a);return c!==void 0&&D(c).some(d=>z(d,c)&&fe(w(d))&&!Be(d,e,a))});if(t(e)||n)return!1;if(He(s,s)||we(s,s))return!0;const i=v(s)??s;return(r.isIdentifier(i)?[i]:i.getDescendantsOfKind(l.Identifier)).some(a=>!z(a,i)&&!_e(a,i)&&we(a,i))},le=(s,e)=>K(s,e),ws=(s,e)=>{if(le(s,e))return!0;const t=me(s);if(t!==void 0&&le(t,e))return!0;const n=Le(s);if(n!==void 0){const i=me(n);return i!==void 0&&le(i,e)}return!1},Bs=(s,e)=>{const t=O(s),n=_t(e);if(t===void 0||n===void 0||O(n.row)?.compilerNode!==t.compilerNode)return!1;const{keyPath:i,row:o}=n,a=o.getNameNode(),c=[];let d=s;for(let E=s.getParent();E!==void 0&&E.compilerNode!==t.compilerNode;E=E.getParent()){if(r.isBlock(E)){const y=E.getStatements(),p=y.findIndex(x=>x.compilerNode===d.compilerNode);c.push(...p>0?os(y,p,o,t,s):[])}d=E}if(!r.isIdentifier(a))return!1;const g=L(a).filter(E=>Ze(E,s,t)),A=new Set(c.flatMap(E=>E.helperArguments??[])),b=c.flatMap(E=>E.helperUses??[]);return c.some(E=>{const y=ns(i,E.guardedPaths);return g.every(p=>A.has(_(p).node)||pe(p,y))&&b.every(({prefix:p,use:x})=>pe(x,y,p))})},us=/rate|limit|\bip\b|geo|throttle/iu,gs=/^run[A-Z]/u,ps=s=>r.isIdentifier(s)?(s.getSymbol()?.getDeclarations()??[]).some(t=>t.getFirstAncestorByKind(l.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,fs=s=>{const e=r.isCallExpression(s)?s.getExpression():s;let t;return r.isIdentifier(e)?t=e:r.isPropertyAccessExpression(e)&&(t=e.getNameNode()),t!==void 0&&ps(r.isPropertyAccessExpression(e)?e.getExpression():t)&&!us.test(t.getText())},ms=s=>{const e=r.isCallExpression(s)?s.getExpression():void 0;if(r.isElementAccessExpression(e)){const t=e.getArgumentExpression();return(r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t))&&t.getLiteralText()==="use"}return r.isPropertyAccessExpression(e)&&e.getName()==="use"},Es=s=>{const e=s.getParent();return r.isPropertyAccessExpression(e)&&e.getExpression()===s?!gs.test(e.getName()):r.isElementAccessExpression(e)&&e.getExpression()===s?r.isStringLiteral(e.getArgumentExpression())||r.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):r.isVariableDeclaration(e)&&e.getInitializer()?.getText()===s.getText()},vs=s=>{if(r.isPropertyAccessExpression(s))return s.getName()==="ip";if(r.isElementAccessExpression(s)){const e=s.getArgumentExpression();return(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return r.isBindingElement(s)?s.getDotDotDotToken()!==void 0||(s.getPropertyNameNode()?.getText()??s.getName())==="ip":r.isShorthandPropertyAssignment(s)&&s.getName()==="ip"},xs=(s,e)=>{const t=s.getParent();if(!r.isCallExpression(t)||t.getExpression()===s)return!1;const n=t.getArguments(),i=n.indexOf(s);if(n.slice(0,Math.max(i,0)).some(c=>r.isSpreadElement(c)))return!1;const o=Ye(t.getExpression()),a=i===-1||o===void 0?void 0:o.getParameters()[i];return o===void 0||a===void 0||a.isRestParameter()||!r.isIdentifier(a.getNameNode())?!1:e.has(a.compilerNode)?!0:(e.add(a.compilerNode),!ot(o,a,e))},it=(s,e,t=new Set)=>{if(e===void 0||!r.isIdentifier(s))return!1;const n=m(s);if(n?.compilerNode===e.compilerNode)return!0;if(n===void 0||t.has(n.compilerNode))return!1;t.add(n.compilerNode);const i=r.isVariableDeclaration(n)&&r.isIdentifier(n.getNameNode())?n.getInitializer():void 0;return i!==void 0&&it(i,e,t)},As=s=>{const e=s.getParent();return r.isParameterDeclaration(e)||r.isBindingElement(e)||r.isVariableDeclaration(e)?e.getInitializer()!==s:!1},Ps=s=>r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isFunctionDeclaration(s)||r.isMethodDeclaration(s),hs=(s,e)=>!r.isBindingElement(s)||s.getDotDotDotToken()===void 0?!1:s.getFirstAncestorByKind(l.Parameter)?.getParent()?.getAncestors().some(i=>i!==e&&Ps(i)&&i.getAncestors().includes(e))===!0,ot=(s,e,t)=>{for(const n of s.getDescendants())if(vs(n)&&!hs(n,s)||ms(n)&&!fs(n.getArguments()[0])||r.isIdentifier(n)&&(ut(n)||it(n,e))&&!Es(n)&&!As(n)&&!xs(n,t))return!0;return!1},Ls=s=>ot(s,void 0,new Set);export{bs as a,Ds as b,ks as c,Bs as d,ws as e,le as f,se as g,Ss as i,Ls as m,k as r,me as s};
@@ -1 +1 @@
1
- import{statSync as F,readdirSync as P,realpathSync as D,lstatSync as I}from"node:fs";import{dirname as w,join as S,relative as N,sep as L,extname as O,basename as z}from"node:path";import{matcher as j}from"@visulima/fs";import{SyntaxKind as l,Node as s,VariableDeclarationKind as M}from"ts-morph";import{diagnosticAt as V}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{r as K}from"./project-config-file-DR7xrrNB.mjs";import{findProjectConfigFile as $,findCodegenConfigFile as B}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as U,a as W}from"./property-name-7cBlgK_O.mjs";const H=/\.ts$/u,E=(e,t)=>N(e,t).split(L).join("/").replace(H,""),he=e=>{const t=s.isFunctionDeclaration(e)?e:e.getFirstAncestor(i=>s.isVariableStatement(i)||s.isFunctionDeclaration(i)||s.isExpressionStatement(i)||s.isReturnStatement(i)||s.isArrowFunction(i)||s.isFunctionExpression(i));return(t===void 0||s.isArrowFunction(t)||s.isFunctionExpression(t)?e:t).getStartLineNumber()},X=new Set(["_generated","node_modules"]),T=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),R=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,ye=e=>{const t=e.split("/");return R.test(t.at(-1)??"")||t.slice(0,-1).some(i=>T.has(i))},m=(e,t,i)=>t?X.has(e)||!i&&T.has(e):!i&&R.test(e),h=new Map,x=()=>!1;let f;const G=e=>{const t=B(e),i=t===void 0?void 0:F(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return x;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=h.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=K(w(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?j(o.exclude):x;return h.set(t,{isExcluded:c,key:n}),c},Y=(e,t,i)=>e==="schema.ts"&&t===i,q=e=>{try{return F(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},_=(e,t,i,n,r)=>{let o,c;try{o=P(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const u of o){const p=S(e,u),a=q(p);a===void 0||r(u,N(i,p).split(L).join("/"),a.isDirectory())||(a.isDirectory()?_(p,t,i,n,r):a.isFile()&&O(u)===".ts"&&!Y(u,e,i)&&t.push(p))}return t},b=(e,t={})=>{const i=t.includeSkipped??!1,n=`${String(i)}\0${e}`,r=f?.get(n);if(r!==void 0)return[...r];const o=i?x:G(e),c=_(e,[],e,new Set,(u,p,a)=>m(u,a,i)||o(p));return f?.set(n,c),[...c]},Ae=e=>{if(f!==void 0)return e();f=new Map;try{return e()}finally{f=void 0}},Q=["src/server","src/index.ts","src/worker.ts"],J=new Set([".ts",".tsx"]),k=(e,t=[])=>{let i;try{i=I(e)}catch{return t}if(i.isFile())return J.has(O(e))&&!m(z(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of P(e))m(n,!0,!1)||k(S(e,n),t);return t},Z=e=>{const t=w(e),i=b(e).map(o=>({displayPath:E(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=$(t);for(const o of[...Q.flatMap(c=>k(S(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:E(t,o),filePath:o}));return i},ee=e=>Array.isArray(e),y=new WeakMap,te=(e,t)=>{let i=y.get(e.compilerNode);i===void 0&&(i=new Map,y.set(e.compilerNode,i));let n=i.get(t);return n===void 0&&(n=e.getDescendantsOfKind(t),i.set(t,n)),n},C=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const u=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const p of te(u,i)){const a=n(p,o);ee(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},ie=e=>b(e).map(t=>({displayPath:E(e,t),filePath:t})),se=(e,t,i,n)=>C(e,ie(t),i,n),Fe=(e,t,i)=>se(e,t,l.CallExpression,i),Pe=(e,t,i)=>C(e,Z(t),l.CallExpression,i),we=e=>U(e.getPropertyNameNode()??e.getNameNode()),v=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&W(i)===t),Ne=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=v(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},Le=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=v(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},ne=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===M.Const},re=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},A=e=>{const t=re(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=l.FirstAssignment&&r<=l.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===l.PlusPlusToken||r===l.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&A(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&A(i)},oe=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!ne(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},ce=e=>oe(e.getSymbol()),Oe=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=ce(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},g=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},d=e=>{const t=g(e);if(t!==void 0){if(s.isNumericLiteral(t))return t.getLiteralValue();if(s.isPrefixUnaryExpression(t)){const i=d(t.getOperand());if(i===void 0)return;const n=t.getOperatorToken();return n===l.MinusToken?-i:n===l.PlusToken?i:void 0}if(s.isBinaryExpression(t)){const i=d(t.getLeft()),n=d(t.getRight());if(i===void 0||n===void 0)return;switch(t.getOperatorToken().getKind()){case l.AsteriskToken:return i*n;case l.MinusToken:return i-n;case l.PlusToken:return i+n;default:return}}}},ae=(e,t)=>{let i=g(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=g(i.getExpression())}return{root:i}},Te=e=>ae(e).root,Re=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),_e=(e,t)=>e?.compilerNode===t.compilerNode,be=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},ke=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Ce=e=>{const t=g(e);return t&&s.isCallExpression(t)?t:void 0},De=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},Ie=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},ze=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=v(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},le=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},je=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?le(e):void 0},Me=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw V(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},ue=new Set(["api","internal"]),Ve=new Set(["run","runAction","runMutation","runQuery"]),pe=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&ue.has(i.getText())&&t.length>=2?t:void 0},Ke=e=>{const t=pe(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{Ve as RUN_METHODS,H as TS_EXTENSION_RE,we as bindingKeyName,Te as chainRootOf,Fe as collectCallRows,se as collectNodeRows,Pe as collectSecurityCallRows,he as declarationLineOf,De as defaultExportExpression,te as descendantsOfKind,v as findObjectProperty,Ke as functionKeyOf,pe as functionReferenceSegments,Ne as handlerOf,ne as isConstDeclaration,Re as isFunctionLike,_e as isSameNode,ye as isTestPath,A as isWriteTarget,Ie as limitNameOf,b as listLunoraSourceFiles,Z as listSecurityScanFiles,E as lunoraRelativePath,be as memberAccessOf,je as objectLiteralFromCallbackBody,Oe as optionsObjectLiteral,re as outermostValueWrapper,Le as propertyInitializer,W as propertyKeyName,U as propertyNameText,ke as returningFunctionOf,d as staticNumberValue,Me as stringPropertyFor,ze as stringPropertyOf,oe as symbolConstInitializer,g as unwrapExpression,Ce as unwrapToCallExpression,ae as walkChain,Ae as withSourceListMemo};
1
+ import{statSync as F,readdirSync as P,realpathSync as D,lstatSync as I}from"node:fs";import{dirname as w,join as S,relative as N,sep as L,extname as O,basename as z}from"node:path";import{matcher as j}from"@visulima/fs";import{SyntaxKind as l,Node as s,VariableDeclarationKind as M}from"ts-morph";import{diagnosticAt as V}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{r as K}from"./project-config-file-DR7xrrNB.mjs";import{findProjectConfigFile as $,findCodegenConfigFile as B}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as U,a as W}from"./property-name-7cBlgK_O.mjs";const H=/\.ts$/u,E=(e,t)=>N(e,t).split(L).join("/").replace(H,""),he=e=>{const t=s.isFunctionDeclaration(e)?e:e.getFirstAncestor(i=>s.isVariableStatement(i)||s.isFunctionDeclaration(i)||s.isExpressionStatement(i)||s.isReturnStatement(i)||s.isArrowFunction(i)||s.isFunctionExpression(i));return(t===void 0||s.isArrowFunction(t)||s.isFunctionExpression(t)?e:t).getStartLineNumber()},X=new Set(["_generated","node_modules"]),T=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),R=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,ye=e=>{const t=e.split("/");return R.test(t.at(-1)??"")||t.slice(0,-1).some(i=>T.has(i))},m=(e,t,i)=>t?X.has(e)||!i&&T.has(e):!i&&R.test(e),h=new Map,x=()=>!1;let f;const G=e=>{const t=B(e),i=t===void 0?void 0:F(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return x;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=h.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=K(w(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?j(o.exclude):x;return h.set(t,{isExcluded:c,key:n}),c},Y=(e,t,i)=>e==="schema.ts"&&t===i,q=e=>{try{return F(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},_=(e,t,i,n,r)=>{let o,c;try{o=P(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const u of o){const p=S(e,u),a=q(p);a===void 0||r(u,N(i,p).split(L).join("/"),a.isDirectory())||(a.isDirectory()?_(p,t,i,n,r):a.isFile()&&O(u)===".ts"&&!Y(u,e,i)&&t.push(p))}return t},b=(e,t={})=>{const i=t.includeSkipped??!1,n=`${String(i)}\0${e}`,r=f?.get(n);if(r!==void 0)return[...r];const o=i?x:G(e),c=_(e,[],e,new Set,(u,p,a)=>m(u,a,i)||o(p));return f?.set(n,c),[...c]},Ae=e=>{if(f!==void 0)return e();f=new Map;try{return e()}finally{f=void 0}},Q=["src/server","src/index.ts","src/worker.ts"],J=new Set([".ts",".tsx"]),k=(e,t=[])=>{let i;try{i=I(e)}catch{return t}if(i.isFile())return J.has(O(e))&&!m(z(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of P(e))m(n,!0,!1)||k(S(e,n),t);return t},Z=e=>{const t=w(e),i=b(e).map(o=>({displayPath:E(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=$(t);for(const o of[...Q.flatMap(c=>k(S(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:E(e,o),filePath:o}));return i},ee=e=>Array.isArray(e),y=new WeakMap,te=(e,t)=>{let i=y.get(e.compilerNode);i===void 0&&(i=new Map,y.set(e.compilerNode,i));let n=i.get(t);return n===void 0&&(n=e.getDescendantsOfKind(t),i.set(t,n)),n},C=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const u=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const p of te(u,i)){const a=n(p,o);ee(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},ie=e=>b(e).map(t=>({displayPath:E(e,t),filePath:t})),se=(e,t,i,n)=>C(e,ie(t),i,n),Fe=(e,t,i)=>se(e,t,l.CallExpression,i),Pe=(e,t,i)=>C(e,Z(t),l.CallExpression,i),we=e=>U(e.getPropertyNameNode()??e.getNameNode()),v=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&W(i)===t),Ne=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=v(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},Le=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=v(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},ne=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===M.Const},re=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},A=e=>{const t=re(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=l.FirstAssignment&&r<=l.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===l.PlusPlusToken||r===l.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&A(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&A(i)},oe=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!ne(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},ce=e=>oe(e.getSymbol()),Oe=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=ce(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},g=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},d=e=>{const t=g(e);if(t!==void 0){if(s.isNumericLiteral(t))return t.getLiteralValue();if(s.isPrefixUnaryExpression(t)){const i=d(t.getOperand());if(i===void 0)return;const n=t.getOperatorToken();return n===l.MinusToken?-i:n===l.PlusToken?i:void 0}if(s.isBinaryExpression(t)){const i=d(t.getLeft()),n=d(t.getRight());if(i===void 0||n===void 0)return;switch(t.getOperatorToken().getKind()){case l.AsteriskToken:return i*n;case l.MinusToken:return i-n;case l.PlusToken:return i+n;default:return}}}},ae=(e,t)=>{let i=g(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=g(i.getExpression())}return{root:i}},Te=e=>ae(e).root,Re=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),_e=(e,t)=>e?.compilerNode===t.compilerNode,be=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},ke=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Ce=e=>{const t=g(e);return t&&s.isCallExpression(t)?t:void 0},De=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},Ie=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},ze=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=v(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},le=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},je=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?le(e):void 0},Me=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw V(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},ue=new Set(["api","internal"]),Ve=new Set(["run","runAction","runMutation","runQuery"]),pe=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&ue.has(i.getText())&&t.length>=2?t:void 0},Ke=e=>{const t=pe(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{Ve as RUN_METHODS,H as TS_EXTENSION_RE,we as bindingKeyName,Te as chainRootOf,Fe as collectCallRows,se as collectNodeRows,Pe as collectSecurityCallRows,he as declarationLineOf,De as defaultExportExpression,te as descendantsOfKind,v as findObjectProperty,Ke as functionKeyOf,pe as functionReferenceSegments,Ne as handlerOf,ne as isConstDeclaration,Re as isFunctionLike,_e as isSameNode,ye as isTestPath,A as isWriteTarget,Ie as limitNameOf,b as listLunoraSourceFiles,Z as listSecurityScanFiles,E as lunoraRelativePath,be as memberAccessOf,je as objectLiteralFromCallbackBody,Oe as optionsObjectLiteral,re as outermostValueWrapper,Le as propertyInitializer,W as propertyKeyName,U as propertyNameText,ke as returningFunctionOf,d as staticNumberValue,Me as stringPropertyFor,ze as stringPropertyOf,oe as symbolConstInitializer,g as unwrapExpression,Ce as unwrapToCallExpression,ae as walkChain,Ae as withSourceListMemo};
@@ -1 +1 @@
1
- import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-Uwb5a6Kq.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
1
+ import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-DJeZ18i9.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
@@ -1 +1 @@
1
- import{w as a,r as l}from"./classify-procedure-call-BmEirzc_.mjs";import{Node as e}from"ts-morph";import{unwrapExpression as o,symbolConstInitializer as c}from"./isTestPath-Uwb5a6Kq.mjs";const E=r=>a(r,"use","rls"),t=r=>{const s=o(r);return!s||!e.isIdentifier(s)?s:o(c(s.getSymbol()))},u=r=>r&&e.isCallExpression(r)&&l(r.getExpression(),"definePolicies")?t(r.getArguments()[0]):r,f=r=>{if(r&&e.isObjectLiteralExpression(r))return r;if(r&&e.isCallExpression(r)&&l(r.getExpression(),"definePolicy")){const s=t(r.getArguments()[0]);return s&&e.isObjectLiteralExpression(s)?s:void 0}},b=r=>{const s=u(t(r.getArguments()[0]));if(!s||!e.isArrayLiteralExpression(s))return[];const i=[];for(const p of s.getElements()){const n=f(t(p));n&&i.push(n)}return i};export{b as p,E as r};
1
+ import{w as a,r as l}from"./classify-procedure-call-BK_MMoue.mjs";import{Node as e}from"ts-morph";import{unwrapExpression as o,symbolConstInitializer as c}from"./isTestPath-DJeZ18i9.mjs";const E=r=>a(r,"use","rls"),t=r=>{const s=o(r);return!s||!e.isIdentifier(s)?s:o(c(s.getSymbol()))},u=r=>r&&e.isCallExpression(r)&&l(r.getExpression(),"definePolicies")?t(r.getArguments()[0]):r,f=r=>{if(r&&e.isObjectLiteralExpression(r))return r;if(r&&e.isCallExpression(r)&&l(r.getExpression(),"definePolicy")){const s=t(r.getArguments()[0]);return s&&e.isObjectLiteralExpression(s)?s:void 0}},b=r=>{const s=u(t(r.getArguments()[0]));if(!s||!e.isArrayLiteralExpression(s))return[];const i=[];for(const p of s.getElements()){const n=f(t(p));n&&i.push(n)}return i};export{b as p,E as r};
@@ -1 +1 @@
1
- import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-Uwb5a6Kq.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(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"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(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},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(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))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=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}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=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("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(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())},L=(e,t)=>e!==void 0&&(A(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})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(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 a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
1
+ import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-DJeZ18i9.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(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"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(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},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(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))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=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}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=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("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(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())},L=(e,t)=>e!==void 0&&(A(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})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(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 a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.423",
3
+ "version": "1.0.0-alpha.425",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -51,12 +51,12 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@lunora/advisor": "^1.0.0-alpha.295",
54
- "@lunora/agent": "^1.0.0-alpha.283",
54
+ "@lunora/agent": "^1.0.0-alpha.284",
55
55
  "@lunora/container": "1.0.0-alpha.108",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
- "@lunora/platform": "1.0.0-alpha.80",
58
- "@lunora/queue": "1.0.0-alpha.143",
59
- "@lunora/scheduler": "^1.0.0-alpha.170",
57
+ "@lunora/platform": "^1.0.0-alpha.81",
58
+ "@lunora/queue": "^1.0.0-alpha.144",
59
+ "@lunora/scheduler": "^1.0.0-alpha.171",
60
60
  "@lunora/values": "^1.0.0-alpha.95",
61
61
  "@lunora/workflow": "^1.0.0-alpha.111",
62
62
  "@visulima/fs": "7.0.0",