@lunora/codegen 1.0.0-alpha.383 → 1.0.0-alpha.385

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 (67) hide show
  1. package/dist/index.d.mts +43 -5
  2. package/dist/index.d.ts +43 -5
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-BedyJsOT.mjs → AGENTS_FILENAME-5mDMAMWy.mjs} +1 -1
  5. package/dist/packem_shared/{CONTAINERS_FILENAME-T1v8pyHN.mjs → CONTAINERS_FILENAME-BJYrxnq2.mjs} +1 -1
  6. package/dist/packem_shared/{GENERATED_HEADER-Bzf6ZJ9r.mjs → GENERATED_HEADER-B-tYRlRG.mjs} +1 -1
  7. package/dist/packem_shared/{MUTATORS_FILENAME-BGvYo46g.mjs → MUTATORS_FILENAME-D9WbOFm7.mjs} +1 -1
  8. package/dist/packem_shared/{NOTIFY_FILENAME-BJJObZHG.mjs → NOTIFY_FILENAME-CRU_TEKs.mjs} +1 -1
  9. package/dist/packem_shared/{OPENRPC_VERSION-CSjT8wJW.mjs → OPENRPC_VERSION-CT_E2DcI.mjs} +1 -1
  10. package/dist/packem_shared/{QUEUES_FILENAME-Dt5RG_P0.mjs → QUEUES_FILENAME-BeGwgqcw.mjs} +1 -1
  11. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DXilYf6b.mjs +31 -0
  12. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
  13. package/dist/packem_shared/SHAPES_FILENAME-D9beIrs1.mjs +1 -0
  14. package/dist/packem_shared/{SchemaSnapshotParseError-ycDz8gOB.mjs → SchemaSnapshotParseError-DnAuFdpl.mjs} +8 -8
  15. package/dist/packem_shared/{WORKFLOWS_FILENAME-VAXgqqP-.mjs → WORKFLOWS_FILENAME--RWiu_Vy.mjs} +1 -1
  16. package/dist/packem_shared/{attribution-DUbGYT4N.mjs → attribution-CTMkuBkn.mjs} +1 -1
  17. package/dist/packem_shared/{buildOpenApiDocument-afHH7rN5.mjs → buildOpenApiDocument-67-fasdW.mjs} +1 -1
  18. package/dist/packem_shared/{context-property-calls-B75cjwpy.mjs → context-property-calls-ZK1UcTQR.mjs} +1 -1
  19. package/dist/packem_shared/{context-root-D4Njep-A.mjs → context-root-DtpwprsY.mjs} +1 -1
  20. package/dist/packem_shared/{database-calls-aAjZJdma.mjs → database-calls-Cn47SfSU.mjs} +1 -1
  21. package/dist/packem_shared/{discoverAuthApiCalls-Ce3BdKQr.mjs → discoverAuthApiCalls-DZMYREsq.mjs} +1 -1
  22. package/dist/packem_shared/discoverFunctions-DU5ylqVC.mjs +1 -0
  23. package/dist/packem_shared/{discoverHttpRoutes-BQM2CPSF.mjs → discoverHttpRoutes-D9Q0lBBb.mjs} +1 -1
  24. package/dist/packem_shared/discoverHyperdriveCalls-DlyCZKX3.mjs +1 -0
  25. package/dist/packem_shared/{discoverInserts-DldQpEfF.mjs → discoverInserts-7Xdawmuk.mjs} +1 -1
  26. package/dist/packem_shared/discoverMaskProcedures-D6kAKDZG.mjs +1 -0
  27. package/dist/packem_shared/{discoverMigrations-E9k4Ykku.mjs → discoverMigrations-C649uAWL.mjs} +1 -1
  28. package/dist/packem_shared/{discoverNondeterministicCalls-DZ_kIie5.mjs → discoverNondeterministicCalls-DQgVTcLv.mjs} +1 -1
  29. package/dist/packem_shared/{discoverQueries-Bq2hqYHP.mjs → discoverQueries-C75OdGHl.mjs} +1 -1
  30. package/dist/packem_shared/discoverR2sqlCalls-BrDIti5c.mjs +1 -0
  31. package/dist/packem_shared/{discoverRlsMetadata-Dq6iSXnC.mjs → discoverRlsMetadata-DqZpiGts.mjs} +1 -1
  32. package/dist/packem_shared/discoverRlsProcedures-BiyDg2ej.mjs +1 -0
  33. package/dist/packem_shared/discoverSchema-Bs5JUiOE.mjs +1 -0
  34. package/dist/packem_shared/{discoverStorageRulesMetadata-CJ7h6SPK.mjs → discoverStorageRulesMetadata-H3RJzkH_.mjs} +1 -1
  35. package/dist/packem_shared/{emitAgents-BeM6PZv4.mjs → emitAgents-iTKWSKan.mjs} +1 -1
  36. package/dist/packem_shared/{emitApi-GFmStqmq.mjs → emitApi-DWJW8Vu9.mjs} +1 -1
  37. package/dist/packem_shared/{emitApp-D-6FIpYb.mjs → emitApp-L7PnfjJK.mjs} +1 -1
  38. package/dist/packem_shared/{emitCrons-Drdn8Mjn.mjs → emitCrons-BvqxeNRr.mjs} +1 -1
  39. package/dist/packem_shared/{emitDataModel-LTnwnhV6.mjs → emitDataModel-MjAOi3KM.mjs} +1 -1
  40. package/dist/packem_shared/{emitDrizzleSchema-CM9jh_F0.mjs → emitDrizzleSchema-Dszoyymv.mjs} +1 -1
  41. package/dist/packem_shared/{emitFunctions-CfSXBV_A.mjs → emitFunctions-CvMrX_cX.mjs} +100 -93
  42. package/dist/packem_shared/{emitServer-4l7MPmK0.mjs → emitServer-BgI9yXW1.mjs} +1 -1
  43. package/dist/packem_shared/emitShard-D4sAFu7Z.mjs +1 -0
  44. package/dist/packem_shared/{exported-procedure-chains-BaCIhnJ7.mjs → exported-procedure-chains-CRM-MVfP.mjs} +1 -1
  45. package/dist/packem_shared/handler-reference-90LXJART.mjs +1 -0
  46. package/dist/packem_shared/{index-11LAY5JO.mjs → index-CNI4vSyc.mjs} +1 -1
  47. package/dist/packem_shared/index-o449rQLQ.mjs +1 -0
  48. package/dist/packem_shared/ip-reads-Dotjify6.mjs +1 -0
  49. package/dist/packem_shared/{qualifiers-D1Q_3wo2.mjs → qualifiers-ClaCHu0X.mjs} +1 -1
  50. package/dist/packem_shared/{server-D69SOfX8.mjs → server-qWq5nN-R.mjs} +1 -1
  51. package/dist/packem_shared/{shard-CB0Ospyw.mjs → shard-BqfSKnmG.mjs} +94 -91
  52. package/dist/packem_shared/{shard-runtime-lkQU8trx.mjs → shard-runtime-C1P_uVye.mjs} +1 -1
  53. package/dist/packem_shared/{shared-A1XHcT4t.mjs → shared-DhqnD5R3.mjs} +6 -6
  54. package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +1 -0
  55. package/dist/packem_shared/{unwrap-handler-return-eQRIZSOX.mjs → unwrap-handler-return-c2s2-nk9.mjs} +1 -1
  56. package/package.json +8 -8
  57. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-kN0pgKNu.mjs +0 -31
  58. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs +0 -2
  59. package/dist/packem_shared/SHAPES_FILENAME-KyidzoqS.mjs +0 -1
  60. package/dist/packem_shared/discoverFunctions-CoQM_L6f.mjs +0 -1
  61. package/dist/packem_shared/discoverHyperdriveCalls-PUg-BESh.mjs +0 -1
  62. package/dist/packem_shared/discoverMaskProcedures-_Ey4eJLn.mjs +0 -1
  63. package/dist/packem_shared/discoverR2sqlCalls-CeNnalpk.mjs +0 -1
  64. package/dist/packem_shared/discoverRlsProcedures-MboagP9z.mjs +0 -1
  65. package/dist/packem_shared/discoverSchema-Cycd1-H0.mjs +0 -1
  66. package/dist/packem_shared/emitShard-B4fVJcJA.mjs +0 -1
  67. package/dist/packem_shared/handler-reference-D1wpw_qR.mjs +0 -1
@@ -0,0 +1,31 @@
1
+ import{existsSync as z,readFileSync as Qe,mkdirSync as qt,writeFileSync as yr,rmSync as Pe,readdirSync as Ln}from"node:fs";import{dirname as jt,join as E,relative as Ht}from"node:path";import{performance as Et}from"node:perf_hooks";import{runAdvisor as br}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{serializeSchemaSnapshot as Nr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Pr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Gt,ts as wr,VariableDeclarationKind as Yt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as ue,collectCallRows as O,findObjectProperty as W,collectSecurityCallRows as Ir,propertyInitializer as L,listSecurityScanFiles as Xe,objectLiteralFromCallbackBody as Dn,limitNameOf as Mn,optionsObjectLiteral as _n,handlerOf as Tr,collectNodeRows as ie,chainRootOf as Je,outermostValueWrapper as C,isWriteTarget as Ze,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Qt,returningFunctionOf as Ct,walkChain as Cr,RUN_METHODS as zn,functionReferenceSegments as Or,isTestPath as kr,isFunctionLike as oe,functionKeyOf as Kn,withSourceListMemo as Rr}from"./isTestPath-JdN4KXhV.mjs";import{j as J,h as G,d as M,b as Xt,c as S,a as et,w as Jt,k as Fr,l as Lr,f as Dr,m as Mr,g as Ot,i as _r}from"./attribution-CTMkuBkn.mjs";import{b as Ks,r as xt,a as Q,e as zr,m as $n,c as tt,f as Zt,E as Bn,C as Vn,d as Kr,g as $r,i as Br}from"./context-root-DtpwprsY.mjs";import{a as T,i as Un,c as te,d as Wn,e as Vr,f as Ur,g as qn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Wr}from"./property-name-7cBlgK_O.mjs";import{b as qr,a as st}from"./module-specifiers-BctA0m_p.mjs";import{r as nt,s as jr}from"./parse-validator-BisfC8bR.mjs";import Hr from"./discoverAuthApiCalls-DZMYREsq.mjs";import{i as K,r as jn}from"./database-calls-Cn47SfSU.mjs";import{i as kt,p as Hn,w as Gr,d as Yr}from"./index-o449rQLQ.mjs";import Qr from"./discoverHyperdriveCalls-DlyCZKX3.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as es,a as Ue,s as Gn,d as Xr}from"./index-CNI4vSyc.mjs";import{MUTATORS_FILENAME as Jr,isDefineMutatorCallee as Zr,mutatorServerImplOf as eo,discoverMutators as to}from"./MUTATORS_FILENAME-D9WbOFm7.mjs";import so from"./discoverNondeterministicCalls-DQgVTcLv.mjs";import{discoverNotifyConfig as no,discoverNotifyCalls as io}from"./NOTIFY_FILENAME-CRU_TEKs.mjs";import ro from"./discoverR2sqlCalls-BrDIti5c.mjs";import oo from"./discoverRlsProcedures-BiyDg2ej.mjs";import{s as ts,n as ao}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as co,redact as lo,isHeuristicSecretKind as uo,isSecretishName as fo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Yn,readMergeDurableObjects as go}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as De,d as po,r as mo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as ho,discoverWorkflows as vo}from"./WORKFLOWS_FILENAME--RWiu_Vy.mjs";import{r as Eo}from"./json-data-Chfs2Cz5.mjs";import{a as xo,I as So,g as Ao,G as Qn,d as yo,i as bo}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as No}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as BE,refreshCodegenProject as VE,tsconfigFingerprint as UE}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Po,usedCapabilities as wo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Xn,isHyperdriveGlobalTable as Jn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Io}from"./AGENTS_FILENAME-5mDMAMWy.mjs";import{discoverContainers as To}from"./CONTAINERS_FILENAME-BJYrxnq2.mjs";import Co from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as Oo,fileWiresRequestSecretTool as ko,createTargetScope as Ro,discoverFeatureUsage as Fo}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Zn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Lo,findProjectConfigFile as Do}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Mo}from"./QUEUES_FILENAME-BeGwgqcw.mjs";import{discoverSandboxUsage as _o}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as zo}from"./readServiceBindings-BA49C6aN.mjs";import Ko from"./discoverStorageRulesMetadata-H3RJzkH_.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as $o,readTargetDiagnostics as Bo,vectorizeDimensionDiagnostics as Vo,liveStreamsDeliveryAuthorizationDiagnostic as Uo,socketRoutesDeliveryAuthorizationDiagnostic as Wo,studioPlatformFor as qo,platformFeatureAvailable as jo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Ho}from"./schema-BgM8A3XV.mjs";import{b as ei,e as Go}from"./shard-BqfSKnmG.mjs";import{e as Yo,a as Qo}from"./server-qWq5nN-R.mjs";import{emitDataModel as Xo}from"./emitDataModel-MjAOi3KM.mjs";import{i as Jo,b as Zo,e as ea,d as ta,f as sa,c as na}from"./unwrap-handler-return-c2s2-nk9.mjs";import ia from"./discoverHttpRoutes-D9Q0lBBb.mjs";import ra from"./discoverInserts-7Xdawmuk.mjs";import{e as ti}from"./exported-procedure-chains-CRM-MVfP.mjs";import oa from"./discoverMigrations-C649uAWL.mjs";import $s from"./discoverQueries-C75OdGHl.mjs";import aa from"./discoverRlsMetadata-DqZpiGts.mjs";import ca from"./discoverSchema-Bs5JUiOE.mjs";import{discoverShapes as la}from"./SHAPES_FILENAME-D9beIrs1.mjs";import{i as da}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ua,emitApp as fa}from"./emitApp-L7PnfjJK.mjs";import{readJsonSync as ga}from"@visulima/fs";import{indexReferencesOf as pa,buildSchemaSnapshot as ma}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as ha,emitOpenApiModule as va}from"./buildOpenApiDocument-67-fasdW.mjs";import{buildOpenRpcDocument as Ea,emitOpenRpcModule as xa}from"./OPENRPC_VERSION-CT_E2DcI.mjs";import{w as Sa,u as Aa,v as ya,t as ba,x as Na}from"./shard-runtime-C1P_uVye.mjs";import{emitCollections as Pa,emitSeed as wa,emitApi as Ia,emitInternalApi as Ta}from"./emitApi-DWJW8Vu9.mjs";import{emitCrons as Ca,emitScheduler as Oa,emitShardRegistry as ka,emitDurableObjects as Ra,emitVectors as Fa,emitWranglerCronTriggers as La}from"./emitCrons-BvqxeNRr.mjs";import Da from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as si,emitFunctions as Ma,emitLazyFunctionModules as _a}from"./emitFunctions-CvMrX_cX.mjs";const za=(e,t=!1)=>{if(e.length===0)return"";const s=yo(t),n=e.map(c=>{if(xo(c.exportName,"live stream export name"),!So.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{Ao(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
+ __lunoraLive: ${m},
3
+ topic: \`${u.name}:${v}\`,
4
+ }),`});return` ${c.exportName}: {
5
+ ${l.join(`
6
+ `)}
7
+ },`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${Qn}import type { ${a} } from "${s.server}";
8
+
9
+ ${n.join(`
10
+ `)}
11
+
12
+ /**
13
+ * A typed reference to each declared live topic, grouped by the stream's export name:
14
+ * \`live.posts.post({ postId })\`. Pass one to \`ctx.live.publish(ref, payload)\` on the server, or to a
15
+ * live-topic hook in the browser. A reference is plain data and carries no server code.
16
+ */
17
+ export const live = {
18
+ ${i.join(`
19
+ `)}
20
+ };
21
+ `},ni=new Set(["delete","get","head","options","patch","post","put"]),Ka=new Set(["handler","stream"]),$a=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Bs=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Ba=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ni.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Va=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||ni.has(n.getName()))break;s=n.getExpression()}return Ba(s)},Ua=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Bs.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Bs.has(s.getText()))return!0}return!1},Wa=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Ka.has(n.getName()))return;const i=Va(s);if(!i||!$a.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&Ua(o);return{exportName:G(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},qa=(e,t)=>{const s=[];for(const n of J(e)){const i=Wa(n,t);i&&s.push(i)}return s},ja=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qa(i,w(t,n)))}return s},Ha=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Ga=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ue(t):void 0}},Ya=e=>{const t=e.getText();if(!e.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()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Ks(a)}))return!1;const n=M(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Ks(i)},Vs=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Ha(e);return n!==void 0&&Ga(n)===t?!0:t==="args"&&Ya(e)},ii=(e,t)=>r.isIdentifier(e)?Vs(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Vs(s,t)),Qa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Us=e=>{const t=r.isIdentifier(e)?M(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Xt(t)?t.getInitializer():void 0},Ft=e=>ii(e,"args"),X=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of x(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},H=e=>{if(Ft(e))return!0;const t=X(e);return t!==void 0&&Ft(t)},Xa=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=X(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},fe=e=>{if(xt(e))return!0;const t=Us(e);if(t!==void 0&&xt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Us(i);return o!==void 0&&xt(o)})},Me=(e,t)=>ii(e,t),Ja=(e,t)=>{if(Me(e,t))return!0;const s=X(e);if(s!==void 0&&Me(s,t))return!0;const n=Qa(e);if(n!==void 0){const i=X(n);return i!==void 0&&Me(i,t)}return!1},Za=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Q(e.getExpression(),["ai"]),ec=(e,t)=>{if(!Za(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||fe(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},tc=(e,t)=>O(e,t,ec),sc=new Set(["generateText","streamText"]),nc=new Set(["messages","prompt","system"]),ic=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],rc=(e,t)=>ic.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),oc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[zr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&rc(i,s));return n===void 0?void 0:`${n}.${s}`},ac=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=oc(t);if(s!==void 0)return s}},cc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ue(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},lc=e=>{if(Ft(e))return!0;const t=cc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},dc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!nc.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&lc(s))return!0}return!1},uc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=T(n.getExpression());if(i===void 0||!sc.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(T(c.getExpression())==="tool"&&(a=ac(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:dc(o)})}return s},fc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...uc(i,w(t,n)))}return s},gc=e=>Q(e,["fetch"]),pc=(e,t)=>{if(!gc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},mc=(e,t)=>O(e,t,pc),ss=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=nt(s.getExpression());return n===void 0||ss(n,t)})}finally{t.delete(e)}},hc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=W(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:nt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:ss(i)}},vc=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?nt(o):void 0;a===void 0?s=!0:(t.push(a),s||=ss(a))}n=i.getExpression()}return{objects:t,opaque:s}},ns=(e,t)=>t?vc(t):hc(e),ri=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=nt(s.getExpression());return n===void 0?[]:ri(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},Ec=e=>e.flatMap(t=>ri(t,new Set)),xc=new Set(["check","length","max"]),Lt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(xc.has(s.getName()))return!0;t=n}},Dt=e=>qr(e)||e==="@lunora/values",Sc=e=>{const t=new Set(["v"]);for(const s of Un(e,"v",Dt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Dt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Ac=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},yc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),bc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Dt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),is=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return yc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&bc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Nc=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},Pc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},wc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ic=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Pc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=wc(t);return s?[s]:[]}),oi=(e,t)=>{if(is(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return oi(e.getExpression(),t)},Tc=(e,t)=>{const s=Nc(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Lt(e),i=new Set(Ic(s).map(o=>oi(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=is(o,t);return a===void 0?[]:[{bounded:Lt(o)||n&&i.has(o),factory:a}]})},Cc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=is(s,t),i=n===void 0?[]:[{bounded:Lt(s),factory:n}];return r.isCallExpression(s)?[...i,...Tc(s,t)]:i}),Oc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Cc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},kc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=te(n);if(i?.visibility!=="public")return;const{objects:o}=ns(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Oc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:G(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Rc=(e,t)=>{const s=[],n=Sc(e),i={destructured:Ac(e,n),namespaces:n};for(const o of J(e)){const a=kc(o,t,i);a&&s.push(a)}return s},Fc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Rc(i,w(t,n)))}return s},St=e=>e?.getKind()===d.TrueKeyword,Lc=e=>e?.getKind()===d.FalseKeyword,Dc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Mc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),_c=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&T(t.getExpression())==="scim"),zc=e=>e!==void 0&&r.isCallExpression(e)&&Mc.has(T(e.getExpression())??""),Kc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),$c=e=>{const t=L(e,"advanced"),s=L(e,"emailAndPassword"),n=L(e,"session");return{analyzable:!0,disableCsrfCheck:St(L(t,"disableCSRFCheck")),emailPasswordEnabled:St(L(s,"enabled")),requireEmailVerification:St(L(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:_c(L(e,"plugins"))&&zc(L(e,"database")),secureCookiesDisabled:Lc(L(t,"useSecureCookies")),sessionFreshAgeZero:Dc(L(n,"freshAge")),trustedOriginsWildcard:Kc(L(e,"trustedOrigins"))}},Bc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Vc=(e,t)=>{if(T(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?$c(s):Bc();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},Uc=(e,t)=>Ir(e,t,Vc),Wc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return $n(e.getExpression(),t.matchReceiver)?s:void 0},qc=(e,t,s)=>{const n=Wc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!H(i)||fe(i))&&!(s.requireUnmodifiedReach===!0&&!Xa(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},it=(e,t,s)=>O(e,t,(n,i)=>qc(n,i,s)),jc=new Set(["content","pdf","scrape","screenshot"]),Hc=(e,t)=>it(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:jc}),Gc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Yc=new Set(["RateLimiter"]),Qc=new Set(["extend"]),Ws="lunora",Xc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ai=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Mt=e=>e&&r.isObjectLiteralExpression(e)?ai(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Jc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Dn(t.getBody());return s?ai(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Zc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=T(n.getExpression());i!==void 0&&(Gc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Mt(n.getArguments()[0])}):Qc.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jc(n.getArguments()[0])}))}for(const n of x(e,d.NewExpression)){const i=T(n.getExpression());i===void 0||!Yc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Mt(n.getArguments()[0])})}return s},el=e=>{for(const t of Xc){const s=E(e,t);if(!z(s))continue;const n=new Gt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Qe(s,"utf8")),i=[];for(const o of x(n,d.CallExpression))T(o.getExpression())===Ws&&i.push({callee:Ws,file:t,line:o.getStartLineNumber(),...Mt(o.getArguments()[0])});return i}return[]},tl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Xe(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Zc(o,n))}return s.push(...el(jt(t))),s},qs="ctx.containers.",sl=e=>{if(!e.startsWith(qs))return!1;const t=e.slice(qs.length);return t.length>0&&!t.includes(".")},nl=(e,t)=>it(e,t,{argIndex:0,matchReceiver:sl,methods:new Set(["get"])}),il=new Set(["allow","deny","setAllowed"]),rl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=W(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},ol=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!rl(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},al=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!il.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},cl=(e,t)=>ol(e,t)??al(e,t),ll=(e,t)=>O(e,t,cl),dl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&K(s.getExpression())?s.getName():void 0},ul=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&K(s)?1:0]},fl=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),gl=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>fl.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},pl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=dl(i);if(a===void 0)return;const c=gl(ul(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},ml=new Set(["defineExportSink","r2Sink","webhookExportSink"]),hl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return ml.has(s)?s:void 0},vl=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},El=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Xe(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of x(o,d.CallExpression)){const c=hl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?vl(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},xl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Sl=new Set(["dbRateLimit","rateLimit"]),Al=e=>{const t=_n(e);if(!t)return!1;const s=W(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},yl=(e,t)=>{const s=T(e.getExpression());if(s===void 0)return;const n=xl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:Al(e.getArguments()[n]),file:t,limitName:Sl.has(s)?Mn(e):"",line:e.getStartLineNumber()}},bl=(e,t)=>O(e,t,yl),Nl=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=te(t);if(s?.kind!=="query")return;const n=Tr(t,s.receiver);return n?{exportName:G(e)??e.getName(),handler:n}:void 0},js=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Pl=e=>{const t=js(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=js(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},wl=(e,t)=>{const s=[];for(const n of tt(e.handler,"flags"))s.push({callee:Pl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Il=(e,t)=>{const s=[];for(const n of J(e)){const i=Nl(n);i&&s.push(...wl(i,t))}return s},Tl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Il(i,w(t,n)))}return s},Cl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Q(e.getExpression(),["flags"]),Ol=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},kl=(e,t)=>{if(!Cl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Ol(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},Rl=(e,t)=>O(e,t,kl),Fl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Ll=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Dl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of x(i,d.CallExpression))Fl(a)&&s.push({file:o,indexName:Ll(a),line:a.getStartLineNumber()})}return s},Ml=new Set(["delete","get","head","options","patch","post","put"]),_l=new Set(["handler","stream"]),zl=new Set(["runAction","runMutation"]),Kl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),we=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,ci=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ue(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Hs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:ci(s,"ctx")},Gs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:ci(s,"request")},Ys=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(zl.has(a)&&we(c,t))return a;if(Kl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&we(c.getExpression(),t))return`db.${a}`}},Qs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&we(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!we(n.getInitializer(),t))){for(const o of i.getElements())if(ue(o)==="auth")return!0}}return!1},$l=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Bl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&we(n.getExpression(),t)},Vl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],li=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Vl(s)},Ul=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?li(t,a.getText()):[]}return[]},Wl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=li(s,t.getText());return n.length>0?n:Ul(t,s)},Xs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Bl(i,t)&&Wl(i).some(o=>$l.test(o)))},ql=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!_l.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Ml.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},jl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=kt(e.getArguments()[0]),l=c&&Hs(c,!0);if(!c||l===void 0||Xs(c,Gs(c,!0)))return;const u=Ys(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Qs(c,l),sideEffect:u}}const n=ql(e);if(n===void 0)return;const i=kt(e.getArguments()[0]),o=i&&Hs(i,!1);if(!i||o===void 0||Xs(i,Gs(i,!1)))return;const a=Ys(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Qs(i,o),sideEffect:a}},Hl=(e,t)=>O(e,t,jl),Gl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Yl=new Set(["append","set"]),di=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Js=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Gl.has(T(n.getExpression())??"")&&Me(n,t)),Ql=(e,t)=>{if(Js(e,t))return!0;const s=X(e);return s!==void 0&&Js(s,t)},_t=(e,t)=>Ja(e,t)&&!Ql(e,t),Xl=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=X(e);return t!==void 0&&r.isNewExpression(t)&&T(t.getExpression())==="Headers"},We=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=X(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},rs=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&_t(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:di(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();_t(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=We(n.getExpression());i!==void 0&&rs(i,t,s)}},ui=(e,t)=>{const s=We(e);if(s===void 0)return;const n=W(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=We(n.getInitializer());i!==void 0&&rs(i,"response-init",t)},Jl=(e,t)=>{const s=T(e.getExpression());if(s==="Response")ui(e.getArguments()[1],t);else if(s==="Headers"){const n=We(e.getArguments()[0]);n!==void 0&&rs(n,"headers-ctor",t)}},Zl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){ui(e.getArguments()[1],t);return}if(Yl.has(n)&&Xl(i)){const o=e.getArguments()[1];o!==void 0&&_t(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:di(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},ed=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Jl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Zl(s,t)},td=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=kt(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return ed(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},sd=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression))s.push(...td(n,t));return s},nd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sd(i,w(t,n)))}return s},fi="identity.ts",id=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return st(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},rd=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&st(n.getModuleSpecifierValue())}return!1},od=e=>{if(r.isIdentifier(e))return id(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&rd(t)}return!1},ad=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!od(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ae(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=et(s,"member");a!==void 0&&t.push({exportName:a})}return t},cd=(e,t)=>{const s=E(t,fi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=ad(n);if(i.length!==0){if(i.length>1)throw ae(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},ld=new Set(["auth","context.auth"]),dd="userId",ud=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},fd=(e,t)=>{const s=E(t,fi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(T(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?ud(o):void 0}},Zs=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return ld.has(t.getText())||Q(t,["auth"])?e:void 0},gd=e=>{if(r.isPropertyAccessExpression(e)&&Zs(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Zs(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},en=(e,t,s)=>{const n=gd(e);return n===void 0?void 0:{declared:n===dd||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},pd=(e,t)=>{const s=fd(e,t);return s===void 0?[]:[...ie(e,t,d.PropertyAccessExpression,(n,i)=>en(n,i,s)),...ie(e,t,d.ElementAccessExpression,(n,i)=>en(n,i,s))]},md=(e,t)=>{if(T(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=L(s,"key");if(!(!n||!H(n)||fe(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},hd=(e,t)=>O(e,t,md),vd=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ed=(e,t,s=[])=>{const n=it(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:vd});return Jt(n,s)},xd=new Set(["queue","send"]),tn=new Set(["bcc","cc","to"]),Sd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!xd.has(t))return;const s=e.getExpression();return Q(s,["mail"])||Q(s,["email"])?t:void 0},Ad=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return tn.has(A(t))&&H(n)&&!fe(n)}if(!r.isPropertyAssignment(t)||!tn.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!fe(s)}):!1,yd=(e,t)=>{const s=Sd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Ad(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},bd=(e,t)=>O(e,t,yd),Nd=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Ue(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Ue(l);if(u===void 0)continue;const f=Gn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Pd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;return n?.receiver?es(n.receiver).flatMap(i=>Nd(i,G(e)??e.getName(),t)):[]},wd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...Pd(a,o))}return s},Id=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return K(s)},Td=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=W(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Cd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Zr(s.getExpression())?s:void 0},Od=e=>{const t=Cd(e),s=t===void 0?void 0:Td(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?G(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Id(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},kd=e=>e.getVariableDeclarations().flatMap(t=>Od(t)),Rd=(e,t)=>{const s=E(t,Jr);if(!z(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return kd(n)},Fd=new Set(["delete","get","patch"]),Ld=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Dd=new Set(["auth","identity","session","user"]),Md=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),_d=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},zd=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},Kd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),$d=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Bd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Kd(s.getExpression(),t)&&$d(s.getThenStatement())),Vd=(e,t)=>{for(const s of x(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Fd.has(i))continue;const o=n.getExpression(),a=K(o);if(!(a||r.isPropertyAccessExpression(o)&&K(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},Ud=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Zt(Je(s))!==void 0)),Wd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Md.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),qd=e=>{for(const t of x(e,d.Identifier))if(Ld.has(t.getText()))return!0;return[...Dd].some(t=>tt(e,t).length>0)?!0:Ud(e)||Wd(e)},jd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Hn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Wn(n.receiver,"use","rls"),a=qd(i),c=new Set,l=[];for(const u of x(i,d.CallExpression)){const f=_d(u);if(f===void 0)continue;const g=zd(u);if(g===void 0||c.has(g)||!Bd(i,g))continue;const m=Vd(i,g);m!==void 0&&(c.add(g),l.push({exportName:G(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Hd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...jd(a,o))}return s},gi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?M(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Gd=e=>{const t=C(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Ze(s)},Yd=e=>{const t=C(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Qd=e=>{const s=C(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Ze(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},qe=e=>{const t=M(e);return t===void 0||Lr(t.getSourceFile())},zt=(e,t)=>{const s=C(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&qe(o);if(gi(Je(o),t))return!(r.isPropertyAccessExpression(o)&&Bn.has(o.getName()))||r.isExpressionStatement(C(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!qe(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},_e={kind:"opaque"},Xd={kind:"unreached"},Jd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Kt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?M(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Jd(s);return i===void 0||Xt(i)?void 0:i}const n=re(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},pi=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?_e:c===void 0?a.some(l=>l.isRestParameter())?_e:Xd:c.isRestParameter()?_e:{kind:"parameter",parameter:c}},Zd=e=>{const t=C(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Kt(s.getExpression());return n===void 0?_e:pi(n,s,t)},eu=new Set(["__defineGetter__","__defineSetter__","__proto__"]),tu=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,mi=e=>{const t=C(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=tu(s);if(n!==void 0)return b(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},su=4,hi=(e,t,s=0)=>{if(Fr(e))return!0;if(Gd(e)){const i=C(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!eu.has(c)}if(Yd(e)||Qd(e)||mi(e)||zt(e,t))return!0;const n=Zd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&nu(n.parameter,s+1)},sn=new WeakMap,nu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=sn.get(e.compilerNode);if(n!==void 0)return n;if(t>su)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||M(a)?.compilerNode!==e.compilerNode||hi(a,void 0,t));return(o||t===0)&&sn.set(e.compilerNode,o),o},nn=new WeakMap,iu=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=M(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},ru=(e,t,s)=>{const{context:n,impl:i}=e,o=nn.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?hi(g,n):!Ze(g),f=!iu(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const v=l.get(m);return v===void 0||c.includes(g)||M(g)?.compilerNode!==v?!0:u(g)});return nn.set(i.compilerNode,f),f},rn=new WeakMap,ou=e=>{let t=rn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=eo(s);return n===void 0?[]:[[n.compilerNode,s]]})),rn.set(e.compilerNode,t)),t},au=e=>{const t=ou(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:G(n)??n.getName()};return a!==void 0&&ru(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},At="args",Ae=e=>{const t=Qt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===At?t.member:void 0}if(!r.isIdentifier(e))return;const s=M(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=re(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ue(i)===At||r.isIdentifier(o)&&o.getText()===At?ue(s):void 0},cu=new Set(["auth","identity","user"]),$t=e=>{const t=i=>{const o=Zt(i);return o!==void 0&&o.length>0&&cu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=X(s);return n!==void 0&&t(n)},vi=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ae(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?X(n):void 0;if(o!==void 0)for(const a of vi(o,t-1))s.add(a)}return s},ze=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...ze(n),...ze(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=Ae(h(u)??u);return g===void 0?[]:ze(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ae(h(n)??n),c=Ae(h(i)??i);return a!==void 0&&$t(i)&&o.push(a),c!==void 0&&$t(n)&&o.push(c),o},lu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&Vr(i.getExpression(),"defineIdentityGuard")},du=e=>{if(!lu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ae(h(s)??s),o=t.some((a,c)=>c!==n&&$t(a));return i!==void 0&&o?[i]:[]})},uu=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},fu=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),on=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},gu=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),pu=(e,t)=>{const s=new Set;for(const n of x(e,d.IfStatement))if(n.getEnd()<=t&&on(n,e)&&uu(n.getThenStatement()))for(const i of ze(n.getExpression()))s.add(i);for(const n of x(e,d.CallExpression))if(n.getEnd()<=t&&gu(n)&&on(n,e))for(const i of du(n))s.add(i);return s},mu=(e,t)=>{const s=vi(t);if(s.size===0)return!1;const n=e.getFirstAncestor(fu);if(n===void 0)return!1;const i=pu(n,e.getStart());return[...s].every(o=>i.has(o))},hu=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),vu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Bt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Ei=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Eu=e=>{const t=C(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},xu=e=>{const t=Eu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||re(t)?[t]:void 0:Ei(t)},ye=e=>e.isUnion()?e.getUnionTypes().every(t=>ye(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ye(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),je=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Ke=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Su=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&vu.get(s.getText())?.has(t.getName())===!0&&qe(s)},Au=e=>{const t=Ct(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=C(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&je(n,Vn)?n:void 0},yu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=C(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:je(n,hu,t)?n:void 0},bu=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Nu=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},an=e=>{const t=C(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Su(s);return yu(s,t)??bu(s,t)??Nu(s,t)??(n?s:Au(t))},Pu=5e4,xi=()=>({inProgress:new Set,verdicts:new Map});class wu{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Pu&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Iu=8,Tu=8;class Cu{budget;scope;taint;verdicts=xi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ye(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Ei(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Iu?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(C(l),!0,a,0))&&(t===n||!ye(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=an(o);m!==void 0;m=an(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=C(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ye(o.getType());if(Ze(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=xu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=C(t).getParent();if(n>=Tu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===C(t)?this.valueCompromises(i,!1,s,n+1):!je(i,Bt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||re(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=C(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Ke(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=je(t,Bt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Kt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!zt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(zt(s,this.scope.context))return!1;const i=Kt(t.getExpression()),o=i===void 0?void 0:pi(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||mi(t)||b(Ct(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ct(t);return b(s,this.scope.impl)?void 0:s}}const Ou=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),ku=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=M(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Ru=new Set(["all","allSettled","any","race"]),cn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,yt=8;class Fu{budget=new wu;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=xi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Cu(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,yt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Dr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=M(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=C(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Bt.has(g.getName()))return!0;const m=a.getArguments().filter(v=>v!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(v=>this.isTaintedValue(v,!1))}const c=r.isVariableDeclaration(a)&&re(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=C(g),v=m.getParent();return!r.isCallExpression(v)||v.getExpression()!==m||this.isCallSiteTainted(v,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&qe(i)&&Ru.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Ke(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=M(t),i=cn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Bn.has(i)?!1:i!==void 0&&Vn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Ke(a)!==void 0)&&(i===void 0||!Ou.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Je(i),c=r.isIdentifier(a)?cn(M(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Ke(i);if(o===void 0)return!ku(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Cr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(gi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?M(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=re(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Xt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,yt))return!1;if(this.variableDepth>=yt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const ln=new WeakMap,Lu=e=>{const t=ln.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Fu(e);return ln.set(e.impl.compilerNode,s),s},Du=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Mu=new Set(["insert","insertManyUnsafe","patch","replace"]),_u=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Mu.has(t)&&Kr(e.getExpression())?t:void 0},zu=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Ku=(e,t)=>{const s=Qt(e);return s?.member===t?h(s.object):void 0},dn=(e,t)=>r.isIdentifier(e)&&M(e)?.compilerNode===t.compilerNode,Si=(e,t,s,n=1)=>{const i=Ku(e,s);if(i!==void 0)return dn(i,t);const o=r.isIdentifier(e)?M(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ue(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||re(l)&&dn(h(l.getInitializer()),t))}const a=re(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Si(a,t,s,n-1)},Vt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Vt(t.getWhenTrue()),...Vt(t.getWhenFalse())]:[t]},$u=(e,t,s)=>{const n=[],i=s===void 0?void 0:Lu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!Du.has(a))continue;const l=Vt(c).filter(f=>i===void 0?H(f)&&!$r(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Si(c,s.parameter,a),g=l.every(m=>mu(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Bu=(e,t,s)=>{const n=_u(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=zu(o,n);if(a.length===0)return[];const c=S(e),l=au(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>$u(f,u,l))},Vu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>Bu(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Jt(o,s).map(c=>Mr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Uu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Wu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,qu=e=>{const t=W(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Wu(t.getInitializer()):void 0},ju=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!Uu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?qu(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Hu=(e,t)=>O(e,t,ju),Gu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Yu=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Qu=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=W(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Ai=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},yi=(e,t)=>e===t||e.startsWith(`${t}.`),bi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},un=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Ni=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>un(s));return r.isIdentifier(e)&&un(e)&&t.push(e),t},Xu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Ju=e=>{const t=Ai(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Zu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Ju(e),i=new Set,o=a=>bi(a).some(c=>n.some(l=>yi(c.getText(),l)))?!0:Ni(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Xu(a))i.add(l)}return{names:i,prefixes:n}},ef=(e,t)=>bi(e).some(s=>t.prefixes.some(n=>yi(s.getText(),n)))?!0:Ni(e).some(s=>t.names.has(s.getText())),tf=e=>{const t=Or(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},sf=(e,t,s)=>{const n=Ai(e,0);if(n===void 0)return[];const i=Zu(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!zn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!ef(u,i))continue;const f=tf(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},nf=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Yu(n),o=i===void 0?void 0:Gu.get(i);if(o===void 0)continue;const a=Qu(n,o);a!==void 0&&s.push(...sf(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},rf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...nf(i,w(t,n)))}return s},fn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},gn=new Set(["account","credential","member","passkey","session","user"]),of=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),af=e=>{const s=of(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return gn.has(s)||gn.has(n)},cf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},lf=(e,t)=>{const{objects:s,opaque:n}=ns(e,t);return Ec(s).some(i=>cf(i))?!0:n?void 0:!1},df=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!W(t,"captcha"),usesRateLimit:!!W(t,"rateLimit")}},uf=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},$e={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},ff=e=>{const t=uf(e),s=t?T(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=df(t);return{...$e,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in fn?{...$e,[fn[s]]:!0}:$e},gf=e=>{const t={...$e};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=ff(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},pf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),mf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!pf.has(t.getName()))return!1;const s=t.getExpression();if(!K(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:af(i.getLiteralText())},hf=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),pn=new Set(["queues","scheduler","topics","workflows"]),vf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!hf.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&pn.has(s.getName())&&Br(s.getExpression()))return!0;s=s.getExpression()}const n=Zt(s);return n?.length===1&&pn.has(n[0]??"")},Ef=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return K(s)},Pi=new Set(["generateObject","generateText","streamObject","streamText"]),xf=e=>{const t=T(e.getExpression());return t!==void 0&&Pi.has(t)},Sf=e=>{const t=T(e.getExpression());if(t===void 0||!Pi.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!W(s,"maxOutputTokens")},Af=new Set(["log","span","trace"]),yf=new Set(["ai"]),bf=new Set(["email","mail"]),Nf=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),bt=(e,t)=>[...t].some(s=>tt(e,s).length>0),wi=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Pf=new Set(["every","filter","flatMap","forEach","map","some"]),wf=new Set(["all","allSettled","race"]),Ii=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Pf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&wf.has(n))return t},If=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(wi.has(t.getKind())){const s=Ii(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Tf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(wi.has(t.getKind())){if(t=Ii(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Cf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const v=m.getExpression();return r.isIdentifier(v)&&v.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Of=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},kf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Rf=e=>{let t=!1,s=!0;for(const n of[...Nf].flatMap(i=>tt(e,i))){const i=kf(n);i&&(t=!0,!If(i)&&!Of(i)&&!Cf(i)&&!Tf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ff=e=>x(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),mn="lunora-advisor-exempt",Lf=/^[\s*/]+/u,Df=/[\w-]/u,Mf=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
22
+ `);for(const n of s.split(`
23
+ `)){const i=n.replace(Lf,"");if(!i.startsWith(mn))continue;const o=i.slice(mn.length);if(Df.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},_f=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=W(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},zf=(e,t)=>{const s=_f(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Kf=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of x(e,d.CallExpression))if(mf(l)&&(o=!0),vf(l)&&(t=!0),Ef(l)&&(i=!0),xf(l)&&(s=!0),Sf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Rf(e);return{callsMail:bt(e,bf),emitsEvent:bt(e,Af),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||bt(e,yf),throwsBareError:Ff(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},$f=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=te(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?gf(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=zf(e,s);return{...o?Kf(o):{},...Mf(e),...i,analyzableBody:o!==void 0,exportName:G(e)??e.getName(),file:t,hasEmailArg:lf(s,n.receiver),kind:n.kind,visibility:n.visibility}},Bf=(e,t)=>{const s=[];for(const n of J(e)){const i=$f(n,t);i&&s.push(i)}return s},Vf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Bf(i,w(t,n)))}return s},Uf=new Set(["dbRateLimit","rateLimit"]),Wf=e=>r.isArrowFunction(e)?e.getBody():e,qf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Ti=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Ci=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},jf=(e,t)=>H(e)||t!==void 0&&Ci(e,t).some(s=>Ti(s)),Hf=(e,t)=>t===void 0?fe(e):Ci(e,t).some(s=>!Ti(s)),Gf=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!Uf.has(s))return;const n=L(_n(e.getArguments()[2]),"key");if(!n)return;const i=Wf(n),o=qf(n);if(!(!jf(i,o)||Hf(i,o)))return{callee:s,scope:S(e),file:t,limitName:Mn(e),line:e.getStartLineNumber()}},Yf=(e,t)=>O(e,t,Gf),Qf=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Xf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Qf.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},Jf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Zf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Oi=(e,t=!1)=>{const s=Zf(e);if(r.isIdentifier(s)){if(t)return;const n=X(s);return n===void 0?void 0:Oi(n,!0)}if(r.isCallExpression(s))return Xf(s)??Jf(s)},eg=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of x(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},tg=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query")return[];const i=Hn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Ur(n.receiver,"output"),a=n.receiver!==void 0&&Wn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of eg(i)){const f=Oi(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:G(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},sg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...tg(a,o))}return s},ng=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},ig=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=jn(o);if(a===void 0)continue;const c=ng(L(a.options,"with"));c.length!==0&&i.push({exportName:G(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},rg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...ig(a,o))}return s},j=(e,t)=>`${e}:${t}`,hn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},og=(e,t)=>[...ie(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?hn(s,n,s.getName(),s.isExported()):void 0),...ie(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?hn(i,n,s.getName(),i.isExported()):void 0})],ag=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=w(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(j(c,a))},cg=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,lg=(e,t)=>{const s=new Map(e.map(n=>[j(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(j(i.file,i.name))?.set(cg(n),{fields:n.fields,method:n.method,table:n.table})}return s},dg=(e,t,s)=>x(e.node,d.CallExpression).map(n=>ag(n,t,s)).filter(n=>n!==void 0),ug=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(j(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(j(o.file,o.name))?.push(a)}},fg=(e,t,s)=>{const n=new Map(e.map(a=>[j(a.file,a.name),a])),i=new Map(e.map(a=>[`${ts(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[j(a.file,a.name),dg(a,n,t)]));return ug(s,n,i,o),o},gg=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},pg=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(j(i.file,i.name))??[])gg(t.get(j(i.file,i.name)),t.get(j(o.file,o.name)))&&(n=!0)}},mg=(e,t,s,n)=>{const i=og(e,t),o=lg(i,s);return pg(i,o,fg(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(j(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},He=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=He(e.getLeft()),s=He(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},hg=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&He(t)!==void 0},vg=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Eg=(e,t,s)=>uo(e)?!kr(s)&&fo(vg(t)):!0,xg=(e,t)=>{const s=[],n=[...x(e,d.BinaryExpression),...x(e,d.StringLiteral),...x(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(hg(o))continue;const a=He(o);if(a===void 0)continue;const c=co(a);if(c===void 0||!Eg(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:lo(a)}))}return s},Sg=(e,t)=>{const s=[],n=new Gt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Qe(i,"utf8"),{overwrite:!0});s.push(...xg(o,w(t,i)))}return s},Ag=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=jn(o);if(a===void 0)continue;const c=L(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:G(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},yg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...Ag(a,o))}return s},bg=new Set(["query","unsafe"]),Ng=e=>!r.isPropertyAccessExpression(e)||!bg.has(e.getName())?!1:Q(e.getExpression(),["sql"]),Pg=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),wg=(e,t)=>{if(!Ng(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Pg(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Ig=(e,t)=>O(e,t,wg),Tg=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Cg=e=>{for(const[t,s]of Tg)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Og=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Cg(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},kg=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Rg=(e,t,s=[])=>{const n=it(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:kg,requireUnmodifiedReach:!0});return Jt(n,s)},Fg=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Lg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Dg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=Lg(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Mg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Fg.get(t);return s===void 0?void 0:$n(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},_g=(e,t)=>{const s=Mg(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Dg(e.getArguments()[s.optionsIndex])}},zg=(e,t)=>O(e,t,_g),Kg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),ki=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Kg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>oe(i)||s(i));if(!(n===void 0||oe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},os=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||oe(s)),t),$g=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,Ri=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||os(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=ki(e);return s!==void 0&&!$g(s,t)}return!1},Fi=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],Bg=e=>Fi(e).some(t=>Ri(t,e)),Vg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Ug=e=>Fi(e).some(t=>Ri(t,e)||r.isBreakStatement(t)&&b(ki(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Vg(t)&&os(t,e)),Wg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>os(t,e)),qg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),jg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Nt=(e,t)=>{const s=qg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||Ug(e)||Wg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(oe)!==void 0))return{file:t,kind:jg(e),line:e.getStartLineNumber(),scope:i}},Hg=(e,t)=>[...ie(e,t,d.WhileStatement,Nt),...ie(e,t,d.ForStatement,Nt),...ie(e,t,d.DoStatement,Nt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),Gg=new Set(["when","where"]),Pt=new Set(["definePolicy","defineShape"]),Yg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Pt.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Pt.has(i)?i:void 0}const s=t.getText();return Pt.has(s)?s:void 0},Qg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Li=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Qg(e))return"empty-object";if(r.isParenthesizedExpression(e))return Li(e.getExpression())}},as=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),Xg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>as(t)===e),Di=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>as(t)===e),Jg=e=>{const t=Xg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Di(e).length>0},Zg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>as(t)===e),Ut=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",ep=(e,t)=>Ut(e)||Ut(t),tp=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),vn=e=>!Ut(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),sp=(e,t,s)=>{const n=tp.get(e);if(n!==void 0)return ep(t,s)?n==="positive"?"negative":"positive":vn(t)||vn(s)?void 0:n},be=e=>{if(r.isParenthesizedExpression(e))return be(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=sp(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=be(e.getLeft()),i=be(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},En=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},np=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},ip=e=>r.isReturnStatement(e)?e.getExpression()??e:e,rp=e=>{const t=[];for(const s of Di(e)){const n=be(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Zg(e)){const n=be(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?En(s.getThenStatement()):En(s.getElseStatement())??np(s);i!==void 0&&t.push(ip(i))}return t},op=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},ap=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!Gg.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&Jg(a))for(const c of rp(a)){const l=Li(c);l!==void 0&&i.push({exportName:op(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},cp=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Yg(n);i!==void 0&&s.push(...ap(n,i,t))}return s},lp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...cp(i,w(t,n)))}return s},dp=new Set(["query","upsert","upsertMany","upsertNow"]),me=new Set,up=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(dp.has(t))return Q(e.getExpression(),["vectors"])?t:void 0},cs=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},Mi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},_i=e=>Mi(e)?.getDeclarations()[0],fp=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},zi=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},xn=(e,t,s)=>{const n=Mi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=zi(_i(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return ls(o,t,s-1)}return H(e)},ls=(e,t,s)=>{const n=cs(e);return fe(n)?!1:r.isIdentifier(n)?xn(n,t,s):H(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>fp(i)&&xn(i,t,s))},Ki=e=>{const t=zi(_i(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ee=(e,t)=>{const s=cs(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ee(s.getWhenTrue(),t),...ee(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ee(s.getLeft(),t),...ee(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Ki(s);return n===void 0?[]:ee(n,!1)}return[]},gp=(e,t)=>{const s=ee(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Ge(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},pp=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",mp=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Ge=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=gp(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else pp(n)&&(s=[mp(n)]);return s},hp=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},vp=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return me;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return me;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Wt=(e,t=!0,s=me)=>{const n=cs(e);if(r.isIdentifier(n)){const o=t?Ki(n):void 0;return o===void 0?[{node:n,parameters:s}]:Wt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Wt(o.getExpression(),t,s):ee(o,!0).flatMap(a=>Ge(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=ls(i.getExpression(),me,1)?vp(o):me;return hp(o).flatMap(c=>ee(c,!0).flatMap(l=>Ge(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Ep=(e,t)=>{const s=up(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Wt(n):ee(n,!0).flatMap(o=>Ge(o,!0).map(a=>({node:a,parameters:me})))).some(({node:o,parameters:a})=>ls(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},xp=(e,t)=>O(e,t,Ep),Sp=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:v}=s;return Pr({adminRoutes:ja(e,t),aiRawRuns:tc(e,t),aiToolSideEffects:fc(e,t),argumentDerivedFetches:mc(e,t),argumentValidators:Fc(e,t),authApiCalls:Hr(e,t),authConfigs:Uc(e,t),browserUrlAccesses:Hc(e,t),callEdges:n.callEdges,configCalls:tl(e,t),containerKeyAccesses:nl(e,t),containerOverrides:ll(e,t),containers:i,countReads:pl(e,t,f.tables),crons:o,cronTargets:o.flatMap(B=>B.functionPath===void 0?[]:[B.functionPath]),exportSinks:El(e,t),staleMigrationImports:Og(e,t),failOpenGuards:bl(e,t),flagReads:Tl(e,t),flagSecurityDefaults:Rl(e,t),geoIndexUsages:Dl(e,t),httpActionGuards:Hl(e,t),httpHeaderWrites:nd(e,t),hyperdriveCalls:Qr(e,t),identityClaimReads:pd(e,t),imageDeliveryUrlAccesses:hd(e,t),inserts:n.inserts,kvKeyAccesses:Ed(e,t,a),mailRecipientAccesses:bd(e,t),maskProcedures:Xr(e,t),maskStrategies:wd(e,t),mutatorWrites:Rd(e,t),nondeterministicCalls:so(e,t),normalizeIdAuthorizations:Hd(e,t),notifyCalls:io(e,t),notifyConfig:no(e,t),mutators:l,ownerFieldWrites:Vu(e,t,a,l),unrestrictedWhereBranches:lp(e,t),paymentWebhooks:Hu(e,t),privilegedDispatches:rf(e,t),procedureProtections:Vf(e,t),queries:n.queries,queues:u,r2sqlCalls:ro(e,t),ratelimitKeySelectors:Yf(e,t),rawRowReturns:sg(e,t),relationLoads:rg(e,t),rlsProcedures:oo(e,t),schema:f,secretLiterals:Sg(e,t),modules:c,shapes:g,softDeleteReads:yg(e,t),sqlInterpolations:Ig(e,t),storageKeyAccesses:Rg(e,t,a),storageUploads:zg(e,t),tableWrites:n.tableWrites,rowEffects:mg(e,t,n.tableWrites,n.callEdges),unboundedLoops:Hg(e,t),vectorNamespaceAccesses:xp(e,t),workflowCalls:n.workflowCalls,workflows:v,wranglerVariables:m})},Ap=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),yp=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Ap(i))]},bp=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Np=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Sn={error:"ERROR",info:"INFO",warn:"WARN"},An={ERROR:2,INFO:0,WARN:1},Pp=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),wp=(e,t)=>{const{advisor:s}=Yn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Sn,n)?Sn[n]:void 0;return i===void 0?[...t,Pp(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>Np(o)||An[o.level]>=An[i])},Ip=(e,t)=>{const{advisor:s}=Yn(e),n=yp(t,s?.accept??[]);return wp(e,s?.acceptUnreadable===!0?[...n,bp()]:n)},Tp={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Cp="crons",Op=ho.replace(/\.ts$/u,""),pe=(e,t)=>`${ts(e)}:${t}`,wt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},kp=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Tp[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...wt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...wt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...wt("workflow",t.workflow,"workflow name")}))],Rp=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Fp=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Rp(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Lp=e=>kp(e).flatMap(t=>Fp(t)),Dp=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Cp,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Mp=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Se=(e,t)=>t===void 0?e:{...e,module:t},_p=e=>{const t=new Map,s=new Map,n=Mp(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(pe(c.file,c.exportName),l)};for(const c of e.functions){const l=pe(c.filePath,c.exportName),u=[...ao(c.filePath),c.exportName].join(".");o(Se({detail:c.kind,id:`function:${l}`,kind:"function",name:u},De(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=pe(c.filePath,c.exportName);o(Se({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},De(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Se({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(Se({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},De(e.modules,c.filePath)),pe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Se({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},De(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},pe(Op,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},zp=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Kp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(pe(e.file,e.exportName))??{reason:zp(e.exportName)},$p=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Kp(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},It=e=>`${e.from}|${e.kind}|${e.to}`,Bp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Vp=e=>{const{nodes:t,sites:s}=_p(e),n=new Map,i=new Map;for(const o of[...Dp(e),...Lp(e)]){const a=$p(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(It(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Bp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>It(o).localeCompare(It(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},Up=e=>`${Qn}export const architecture = ${Eo(e,"Record<string, unknown>")};
24
+ `,yn=(e,t="api")=>{const s=new Map;for(const n of e){const i=ts(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new D("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Wp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Xn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Jn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:Po)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},qp=(e,t,s={})=>{if(t===void 0)return;const n=Wp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
25
+ `);throw new D("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
26
+ ${i}
27
+
28
+ Install them with your package manager, then re-run codegen.`)},jp="env.ts",Hp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return st(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Gp=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&st(n.getModuleSpecifierValue())}return!1},Yp=e=>{if(r.isIdentifier(e))return Hp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Gp(t)}return!1},Qp=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Yp(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ae(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=et(s,"member");a!==void 0&&t.push({exportName:a})}return t},Xp=(e,t)=>{const s=E(t,jp);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Qp(n);if(i.length!==0){if(i.length>1)throw ae(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Jp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Zp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),em=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},tm=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),sm=new Set(["durable"]),nm=new Set(["rollback"]),$i=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},im="defineApp",Ne="app",bn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Ne&&s.getInitializer()?.getText()===t)||t===Ne&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Ne),rm=e=>{if(e===void 0||!Lo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Ne;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Ne;if(r.isVariableDeclaration(t))return bn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&bn(e.getSourceFile(),s)},om="AppBuilder",Bi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},am=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===om&&s.getDeclarations().some(n=>Bi(n))},cm=e=>e.getText()===im&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Bi(t)),Vi=(e,t,s=new Set)=>{const n=Je(t);if(n===void 0||!r.isIdentifier(n))return!1;if(cm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return rm(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Vi(e,a.getInitializer(),s)}}return!1},Ui=(e,t)=>{const s=Qt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Vi(e,s.object)||am(s.object))},lm=new Map([["defineContainer",{keys:Zp,signal:"containerEgressPolicy"}],["defineStep",{keys:nm,signal:"workflowRollback"}],["stream",{keys:sm,signal:"durableStreams"}]]),dm=(e,t)=>{const s=lm.get($i(t));if(s!==void 0)return t.getArguments().some(n=>tm(em(e,n),s.keys))?s.signal:void 0},um=(e,t)=>Jp[$i(t)]??(Ui(e,t)?"deliveryAuthorization":void 0),fm=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Oo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=x(o,d.CallExpression);for(const c of a){const l=dm(o,c)??um(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>qn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Gt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Qe(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Ui(i,o))}return n},gm=(e,t)=>{const s=Ro();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(ko(i,s))return!0}return!1},pm="createWorker",mm="extend",Nn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Pn=e=>{const t=[],s=Nn(L(e,"backupCron"));s!==void 0&&t.push(s);const n=L(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=Nn(i.getNameNode());o!==void 0&&t.push(o)}return t},hm=e=>{const t=T(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===pm)return r.isObjectLiteralExpression(s)?Pn(s):[];if(t!==mm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Dn(s.getBody());return n===void 0?[]:Pn(n)},vm=(e,t)=>{const s=[];for(const{filePath:n}of Xe(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression))s.push(...hm(o))}return[...new Set(s)]},Wi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Wi(e.inner)},Em=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Wi(n);return i!==void 0&&t.has(i)}))},xm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new D("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new D("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Sm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=cd(s,t),a=Xp(s,t),c=vo(s,t),{queues:l,topics:u}=Mo(s,t),f=zo(n),g=Io(s,t);xm(c,g);const m=To(s,t),v=Ko(s,t),B=Co(s,t,c,g),ge=vm(s,t),N=fm(s,t,Do(n)),V=_o(s,t),Y=gm(s,t),I=Fo(s,t);I.browser=I.browser||V.usesSandboxBrowser;const F=Rt(n,e.target),k=$o(I,F,{agents:g.length>0,commitOrderedTables:i.tables.some(_=>_.commitOrdered===!0),cronTriggers:B.length>0,crossShardFanout:i.tables.some(_=>Ho(_)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(_=>_.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(_=>_.sandbox===!0),deliveryAuthorization:N.deliveryAuthorization,durableStreams:N.durableStreams,globalTables:i.tables.some(_=>_.shardMode==="global"),liveContext:N.liveContext,liveStreams:N.liveStreams,typedWebSockets:N.typedWebSockets,queues:l.length>0,relationGraph:Em(i),secretValues:Y,secrets:N.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(_=>_.schedules!==void 0)}),U=k.usage,Z=wo(U),se=k.signals.vectorStore!==!1,ne=k.signals.services===!1?[]:f,ce=Zn(n),$=ce??new Set,P=$.has("lunorash");qp(i,ce,{hasVectors:se,scheduler:U.scheduler||B.length>0,storage:U.storage||v.rules.length>0||Object.keys(ei(i)).length>0,usage:U});const R=z(E(t,"flags.ts")),Ce=z(E(t,"notify.ts"));return{agents:g,capabilities:Z,containers:m,crons:B,dataModelContent:Xo(i),declaredDependencies:ce,dependencies:$,entryCronTriggers:ge,env:a,featureUsage:U,hasFlags:R,hasNotify:Ce,identity:o,platformGate:{...k,diagnostics:[...Bo(n,e.target),...k.diagnostics,...Vo(F,i.vectorIndexes),...N.liveStreams&&N.deliveryAuthorization?[Uo(F)]:[],...N.socketRoutes&&N.deliveryAuthorization?[Wo(F)]:[]]},queues:l,serverContent:Yo({agents:g,capabilities:Z,containers:m,env:a,hasVectors:se,hasFlags:R,hasNotify:Ce,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:v.rules.map(_=>_.bucket),topics:u,useUmbrella:P,workflows:c}),services:ne,storageRulesMetadata:v,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:P,workflows:c}},qi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Am=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},ym=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),bm=/^[\w$]+:[\w$]+$/u,Nm=(e,t)=>{const s=Kn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},wn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Pm=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return wn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Yt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?wn(s):void 0}}},wm=(e,t,s)=>({schedule:{argKeys:Pm(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Im=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(zn.has(s))return Nm(s,n);if((s==="runAfter"||s==="runAt")&&Am(t)){const l=Kn(i)??(r.isStringLiteral(i)&&bm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...wm(s,n,o)}}const a=ym.get(s),c=a===void 0?void 0:qi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Tm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),ji=e=>wr.isOptionalChain(e.compilerNode),Cm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:oe(t)?t.getFirstAncestor(oe)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Tm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&ji(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Bg(s)),Om=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(oe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(oe),i))===!0},km=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),Rm=(e,t)=>{if(ji(e)||t==="schedule"&&Om(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Cm(s,i)){if(!km(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},In=(e,t,s)=>{if(s===void 0)return;const n=Rm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Fm=(e,t)=>[...O(e,t,(s,n)=>In(s,n,Im(s))),...ie(e,t,d.PropertyAccessExpression,(s,n)=>{const i=qi(s,"services");return In(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Lm=new Set(["boolean","number","object","string"]),Dm=e=>{const t=e.getName();if(!Lm.has(t))return;const s=e.getExpression();return Q(s,["flags"])||Q(s,["flags","details"])?t:void 0},Mm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Dm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},_m=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression)){const a=Mm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},zm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||Jo(o))return;const a=e.getSourceFile().getFilePath();if(Zo(i,e,a)){const c=ea(i,e,a,0,new Set);return c===void 0&&ta(o),c}return o},Km=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Wr(t.getNameNode());return s===void 0||s==="namespace"}),$m=(e,t)=>{for(const{filePath:s}of Xe(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of x(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Km(a)))return i}}},Bm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Vm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ae(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Bm}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},Um="room:",Wm="__lunora_socket__:",qm=/^[A-Za-z]\w*$/u,Tn=e=>qm.test(e),jm=e=>`${e}:`.startsWith(Um)||`${e}:`.startsWith(Wm),Hi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Gi=e=>Hi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Cn=e=>A(e),ds=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),de=(e,t)=>{const s=ae(e,`defineLiveStream ${t}`);return new D("LIVE_STREAM_NOT_LITERAL",s.message)},Yi=(e,t,s)=>{const n=ds(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw de(n??e,`needs ${s} so codegen can read its topics`);if(Gi(i))throw de(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Hm=(e,t)=>{const s=Cn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw de(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Gi(n))throw de(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Tn(s)||jm(s))throw new D("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(ds(n,"key")===void 0)return{fields:[],name:s};const a=Yi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Cn(l)),c=a.find(l=>!Tn(l));if(c!==void 0)throw new D("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},Gm=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw de(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Hi(n))throw de(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ds(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw de(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Yi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:w(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Hm(a,l))}},Ym=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new D("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},Qm=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Xm=(e,t)=>x(e,d.CallExpression).filter(s=>qn(s,"defineLiveStream")).map(s=>{const n=Qm(s),i=r.isVariableDeclaration(n)?et(n,"binding"):void 0;if(i===void 0)throw new D("LIVE_STREAM_NOT_EXPORTED",ae(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return Gm(s,i,t)}),Jm=(e,t)=>{const s=y(t).flatMap(n=>Xm(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return Ym(s),s},Zm=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,eh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Zm(e):!0,Qi=(e,t=!1)=>{for(const s of e.getProperties()){if(eh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Qi(n,!0))return!0}return!1},th=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of ti(n))for(const o of es(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Qi(a)))return!0}}return!1},sh=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Ue(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Ue(a);c!==void 0&&s.push({column:c,strategy:Gn(a),table:i})}}return s},nh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of ti(i))for(const a of es(o))for(const c of sh(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},ih=["providerSubscriptionId","state"],rh=["providerEventId","processedAt"],On=(e,t)=>t.every(s=>s in e.shape),oh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&On(t,ih)&&On(s,rh)},ah=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],ch=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},lh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},dh="@lunora/privacy",Xi="userId",kn=new Set(["user","users"]),uh=e=>e.replaceAll("\\","/"),fh="privacy",gh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),rt=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ie=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",us=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),ph=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},ot=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},mh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=ph(s,"tables"),i=rt(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:us(n).map(a=>Ie(a)))t.datasets.set(o,i)},fs=8,he=(e,t=0)=>{if(t>fs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return he(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:he(i,t+1)},hh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:he(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?us(n):[],o=new Set(i.map(a=>Ie(a)));for(const a of ah)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?rt(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ie(a)==="user"&&t.userTables.add(c))}},Rn=(e,t,s)=>{t.datasets.set(rt(e.getArguments()[0])??s,s)},vh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ie(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Ji=(e,t=0)=>{const s=he(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>fs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Ji(i.getExpression(),t+1):[vh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Eh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Ji(t)},xh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:he(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?us(n):[])t.excluded.set(Ie(i),r.isPropertyAssignment(i)?rt(i.getInitializer())??"":"")},Sh=(e,t)=>{switch(ot(e)){case"actionCacheDataset":{Rn(e,t,"actionCache");break}case"authDataset":{hh(e,t);break}case"defineDataset":{mh(e,t);break}case"documentHistoryDataset":{Rn(e,t,"documentHistory");break}}},gs=e=>e!==void 0&&r.isCallExpression(e)&&ot(e)==="defineDataset",Zi=e=>e!==void 0&&r.isCallExpression(e)&&gh.has(ot(e)??""),Ah=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(gs(i)||Zi(i))?n:void 0},er=(e,t,s=0)=>{const n=he(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>fs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!er(i.getExpression(),t,s+1))return!1}else if(!gs(i)&&!Zi(i)){const o=r.isIdentifier(i)?Ah(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},yh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||er(t,s)?s:void 0},bh=(e,t)=>{const s=[];for(const i of x(e,d.CallExpression))if(Sh(i,t),ot(i)==="definePrivacy"){const o=Eh(i);xh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:yh(o)})}return{declared:x(e,d.VariableDeclaration).filter(i=>gs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Nh=(e,t)=>{const s=E(t,"schema.ts"),n=[...y(t),...z(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>uh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Ph=(e,t,s)=>{if(s?.has(dh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:kn};const n={datasets:new Map,excluded:new Map,userTables:new Set(kn)},i=[],o=[];for(const f of Nh(e,t)){const g=bh(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:ch(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},tr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&tr(n,t)),wh=(e,t)=>e.extensionKey!==fh&&(Xi in e.shape||Object.values(e.shape).some(s=>tr(s,t))),Ih=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Xi}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Th=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>wh(o,t.userTables)).map(o=>o.name),[n]=lh(s,t.classifications);if(n!==void 0)throw new D("PRIVACY_COVERAGE",Ih(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new D("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Ch=(e,t)=>{const s=qo(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Oh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Fn=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),kh="",Rh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Fh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Yt.Const?t.getInitializer():void 0},Be=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Be(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Fh(e);if(n!==void 0)return Be(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},Lh=(e,t)=>{if(Oh.has(e))return{method:e,tables:Be(t)??[kh]}},Tt=(e,t,s)=>e===void 0?void 0:{...e,fields:Rh(t,e.method,s)},Dh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Yt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!K(s.getExpression())))return s.getName()},Mh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Dh(n);if(i!==void 0)return Fn.has(s)?Tt({method:s,tables:[i]},e,1):void 0;if(K(n))return Tt(Lh(s,e.getArguments()[0]),e,2);if(Fn.has(s)&&r.isPropertyAccessExpression(n)&&K(n.getExpression()))return Tt({method:s,tables:[n.getName()]},e,1)},_h=(e,t)=>O(e,t,(s,n)=>{const i=Mh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),zh=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Kh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||W(s,"args")===void 0)return!1}return ns(e,t).opaque},$h=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=te(a);c!==void 0&&Kh(a,c.receiver)&&s.push(zh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Bh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...$h(i,w(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Vh=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ye=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),sr=e=>!e.isAny(),nr=e=>{const t=e.getType();if(!sr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Vh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Uh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},ir={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Wh=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),qh={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},jh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Hh={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},Gh=(e,t,s)=>{if(!t.some(i=>_r(i)))return qh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return jh.has(s.typeName)&&!n&&!t.some(i=>da(i))?Hh:ir},rr=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Wh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},Yh=(e,t,s)=>{const n=[];for(const i of J(e)){const o=r.isIdentifier(i.getNameNode())?Ot(i):[i.getName()],c=o.some(u=>Ye(s,t,u))||!Uh(i)?void 0:nr(i),[l=i.getName()]=o;c!==void 0&&n.push(rr(t,l,c,i.getStartLineNumber(),Gh(i,o,c)))}return n},Qh=(e,t,s)=>{if(Ye(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=nr(i.getExpression());o!==void 0&&n.push(rr(t,"default",o,i.getStartLineNumber(),ir))}return n},Xh=(e,t,s)=>[...Yh(e,t,s),...Qh(e,t,s)],Jh=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Ot(n).some(i=>Ye(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Ot(n).find(o=>Ye(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Zh=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),ev=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Xh(c,l,s)),i.push(...Jh(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!sr(a.getType()))&&n.push(Zh(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},tv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},sv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},nv=(e,t)=>O(e,t,(s,n)=>tv(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:sv(s)}:void 0),or=e=>e==="@lunora/workflow",iv=e=>new Set(e.getImportDeclarations().filter(t=>or(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),rv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),ov=(e,t)=>{const s=Un(e,"defineWorkflowEvent",or),n=iv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of x(e,d.CallExpression)){if(!rv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?et(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new D("WORKFLOW_EVENT_NOT_LITERAL",ae(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:w(t,e.getFilePath()),type:l.getLiteralValue()})}return i},av=(e,t)=>{const s=y(t).flatMap(i=>ov(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new D("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Te=(e,t)=>{z(e)&&Qe(e,"utf8")===t||yr(e,t,"utf8")},cv=(e,t)=>{if(t===""){Pe(e,{force:!0});return}Te(e,t)},lv=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Pe(s,{force:!0,recursive:!0});return}if(z(s))for(const n of Ln(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[Ht(e,i)]===void 0&&Pe(i)}for(const[n,i]of Object.entries(t))qt(jt(E(e,n)),{recursive:!0}),Te(E(e,n),i)},dv=(e,t,s)=>{const n=E(e,t);if(Object.keys(s).length===0){Pe(n,{force:!0,recursive:!0});return}if(z(n))for(const i of Ln(n,{recursive:!0,withFileTypes:!0})){const o=E(i.parentPath,i.name);i.isFile()&&s[Ht(n,o)]===void 0&&Pe(o)}for(const[i,o]of Object.entries(s)){const a=E(n,i);qt(jt(a),{recursive:!0}),Te(a,o)}},uv=e=>{try{const t=ga(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ve=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},fv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,gv=(e,t)=>{z(e)||qt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Te(E(e,n.name),n.content),s.push(n.name);break}case"directory":{dv(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{lv(e,n.files),s.push(...Object.keys(n.files));break}default:cv(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},pv=e=>{const t=uv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=ha({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Ea({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
+ `,openApiModuleContent:va(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
+ `,openRpcModuleContent:xa(i)}},mv=".lunora-schema.json",hv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},vv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new D("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new D("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new D("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Ev=8,xv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:v}=e,B=()=>na(()=>{const I=Yr(l,a,{lazyFunctions:o}),F=to(l,a);return{functions:I,httpRoutes:ia(l,a),mutators:F}});let{erased:ge,value:{functions:N,httpRoutes:V,mutators:Y}}=B();Gr(y(a).map(I=>l.getSourceFileOrThrow(I)),I=>Ht(a,I.getFilePath())),yn([...N,...Y].map(I=>I.filePath)),yn(V.filter(I=>I.stream).map(I=>I.filePath),"http-stream");for(let I=1;;I+=1){const F=u?N:N.filter(P=>P.channel?.kind!=="room"&&P.lifecycle!=="socket"),k=Ia({agents:t,functions:F,httpRoutes:V,mutators:Y,useUmbrella:m,workflows:v}),U={agents:t,functions:F,lazyFunctions:o,migrations:c,mutators:Y,shapes:f,useUmbrella:m,usesSandbox:g},Z=Ma(U),se=_a(U),ne=Ta({functions:N,useUmbrella:m}),ce=E(a,"_generated",si),$=[[s,k],[i,ne],[n,Z],...Object.entries(se).map(([P,R])=>[E(ce,P),R])];if(I>=Ev||$.every(([P,R])=>fv(l,P,R)))return{apiContent:k,erased:ge,functions:N,functionModulesContent:se,functionsContent:Z,httpRoutes:V,internalContent:ne,mutators:Y};for(const[P,R]of $)Ve(l,P,R);({erased:ge,value:{functions:N,httpRoutes:V,mutators:Y}}=B())}},Sv=e=>{const t=hv(),s=t?Et.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!z(o))throw new D("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??No(n);jr(zm);const c=ca(a,o,e.projectRoot);Th(c.tables,Ph(a,n,Zn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:B,env:ge,featureUsage:N,hasFlags:V,hasNotify:Y,identity:I,platformGate:F,queues:k,serverContent:U,services:Z,storageRulesMetadata:se,topics:ne,usesSandbox:ce,useUmbrella:$,workflows:P}=Sm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Vm(c,c.jurisdiction===void 0?void 0:$m(a,n));const R=E(n,"_generated"),Ce=E(R,"dataModel.ts"),_=E(R,"server.ts"),ar=E(R,"api.ts"),cr=E(R,"internal.ts"),lr=E(R,"functions.ts");Ve(a,Ce,m),Ve(a,_,U);const ps=Object.fromEntries(Z.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(Qo(p,R))));for(const[p,vt]of Object.entries(ps))Ve(a,E(R,p),vt);const Oe=oa(a,n),le=la(a,n),at=F.signals.typedWebSockets!==!1,{apiContent:ms,erased:dr,functions:q,functionModulesContent:hs,functionsContent:vs,httpRoutes:ct,internalContent:Es,mutators:lt}=xv({agents:l,apiPath:ar,generatedFunctionsPath:lr,internalPath:cr,lazyFunctions:i,roomsSupported:at,lunoraDirectory:n,migrations:Oe,project:a,shapes:le,useUmbrella:$,usesSandbox:ce,workflows:P}),xs=po(a,n),dt=mo(xs,c,[...q,...ct].map(p=>p.filePath)),ke=xs.length>0,ve=e.lint===!1&&!ke?void 0:{callEdges:Fm(a,n),inserts:ra(a,n),queries:$s(a,n,q),tableWrites:_h(a,n),workflowCalls:nv(a,n)},ur=pa(ve?.queries??$s(a,n,q)),Re=e.lint===!1||ve===void 0?void 0:Sp(a,n,{callSites:ve,containers:f,crons:g,functions:q,modules:dt,mutators:lt,queues:k,schema:c,shapes:le,workflows:P,wranglerVariables:e.wranglerVariables}),Ss=Re===void 0?[]:Ip(e.projectRoot,[...br(Re,{source:"static"}),...ev(a,n,{byName:new Set([...P,...k,...l,...f].map(p=>p.exportName)),byPath:new Set([...q,...lt,...le,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Bh(a,n),...sa(dr,n),...Sa(k,e.wranglerQueueProducers)]),fr=aa(a,n),As=nh(a,n);vv(le,As,th(a,n));const gr=V?_m(a,n):[],ut=F.signals.vectorStore!==!1,pr=jo(Rt(e.projectRoot,e.target),"deliveryAuthorization"),Ee=Ch(N,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:oh(c.tables),queueCount:k.length,storageColumnCount:Object.keys(ei(c)).length,storageRuleCount:se.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Rt(e.projectRoot,e.target),vectorStoreSupported:ut,workflowCount:P.length}),ys=t?Et.now():0,ft=ma(c,Oe.map(p=>p.id)),gt=Jm(a,n),bs=Go({advisories:Ss.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Re?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:ge,flagKeys:gr,hasFlags:V,hasNotify:Y,hasIpReaders:q.some(p=>p.readsIp===!0)||le.some(p=>p.readsIp===!0),hasRooms:at&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||q.some(p=>bo(p)),hasSecretValues:F.signals.secretValues===!0,hasSockets:at&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:ut,liveStreamDeclarations:gt,liveStreams:F.signals.liveStreams===!0,maskMetadata:As,mutators:lt,queues:k,rlsMetadata:fr,schema:c,schemaSnapshot:ft,shapes:le,services:Z,storageRules:se,studioFeatures:Ee,topics:ne,useUmbrella:$,workflowEvents:av(a,n),workflows:P}),Ns=Pa(le,v.has("@lunora/db"),$),Ps=Aa(f,c.jurisdiction),ws=ya(P,{lazy:i}),Is=ba(l,{lazy:i}),Ts=Na(k,e.wranglerQueueProducers),Cs=za(gt,$),Os=Ca(g),mr=Oa(Ee.scheduler),hr=ka(c.tables,$,c.jurisdiction),vr=go(e.projectRoot)?Ra($):"",ks=Fa(c.vectorIndexes),Fe=Da(c,$),Rs=wa(v.has("@lunora/seed")),Le=e.apiSpec??"openapi",pt=Le==="openapi"||Le==="both",mt=Le==="openrpc"||Le==="both",Fs=ua(v.has("@lunora/auth")),Ls=fa({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAuth:v.has("@lunora/auth"),hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue")||z(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Xn(p)),hasHyperdriveGlobal:c.tables.some(p=>Jn(p)),hasKvIntrospector:Ee.kv,hasNotify:Y,hasQueue:k.some(p=>p.mode==="push"),liveStreams:F.signals.liveStreams===!0,liveStreamsWithheld:F.liveStreamsWithheld,liveStreamDeclarations:gt,hasScheduler:Ee.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:Ee.storage,hasDeliveryAuthorization:pr,hasVectors:ut,hasWorkflow:P.length>0,identity:I,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,lazyFunctions:i,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:$,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:pt,wantsOpenRpc:mt}),{openApiContent:Ds,openApiModuleContent:Ms,openRpcContent:_s,openRpcModuleContent:zs}=pv({functions:q,httpRoutes:ct,modules:dt,projectRoot:e.projectRoot,wantsArchitecture:ke}),xe=ke&&ve!==void 0?Vp({...ve,crons:g,functions:q,httpRoutes:ct,modules:dt,queues:k,schema:c,services:Z,topics:ne,workflows:P}):void 0,ht=E(n,mv),Er=z(ht),xr=e.dryRun?[]:gv(R,[{content:Ls,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ms,kind:"always",name:"api.ts"},{content:Es,kind:"always",name:"internal.ts"},{content:U,kind:"always",name:"server.ts"},{content:vs,kind:"always",name:"functions.ts"},{files:hs,kind:"directory",name:si},{content:bs,kind:"always",name:"shard.ts"},{content:Os,kind:"always",name:"crons.ts"},{content:ks,kind:"always",name:"vectors.ts"},{content:Fe.global,kind:"always",name:"drizzle.global.ts"},{content:Fe.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ps,kind:"optional",name:"containers.ts"},{content:ws,kind:"optional",name:"workflows.ts"},{content:Is,kind:"optional",name:"agents.ts"},{content:Ts,kind:"optional",name:"queues.ts"},{content:Cs,kind:"optional",name:"live.ts"},{content:mr,kind:"optional",name:"scheduler.ts"},{content:hr,kind:"optional",name:"shardRegistry.ts"},{content:vr,kind:"optional",name:"durableObjects.ts"},{content:Rs,kind:"optional",name:"seed.ts"},{content:Fs,kind:"optional",name:"authModule.ts"},{content:Ns,kind:"optional",name:"collections.ts"},{files:ps,kind:"services"},{content:pt?Ds:"",kind:"optional",name:"openapi.json"},{content:pt?Ms:"",kind:"optional",name:"openapi.ts"},{content:mt?_s:"",kind:"optional",name:"openrpc.json"},{content:mt?zs:"",kind:"optional",name:"openrpc.ts"},{content:xe===void 0?"":`${JSON.stringify(xe,void 0,2)}
31
+ `,kind:"optional",name:"architecture.json"},{content:xe===void 0?"":Up(xe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Er&&Te(ht,Nr(ft)),t){const p=Et.now(),vt=Math.round(p-s),Sr=Math.round(ys-s),Ar=Math.round(p-ys);console.error(`@lunora/codegen: codegen took ${vt.toString()}ms (discovery ${Sr.toString()}ms, emit ${Ar.toString()}ms)`)}return{advisories:Ss,advisorContext:Re,agents:l,architecture:xe,containers:f,cronTriggers:[...new Set([...La(g),...B])],generated:{agents:Is,api:ms,app:Ls,authModule:Fs,collections:Ns,containers:Ps,crons:Os,dataModel:m,drizzleGlobal:Fe.global,drizzleShard:Fe.shard,functionModules:hs,functions:vs,internal:Es,live:Cs,openApi:Ds,openApiModule:Ms,openRpc:_s,openRpcModule:zs,queues:Ts,seed:Rs,server:U,shard:bs,vectors:ks,workflows:ws},migrations:Oe,outputDirectory:R,platformDiagnostics:F.diagnostics,queues:k,indexReferences:ur,schemaSnapshot:ft,schemaSnapshotPath:ht,schemaTables:c.tables,workflows:P,writtenFiles:xr}},zE=e=>Rr(()=>Sv(e));export{mv as SCHEMA_SNAPSHOT_FILENAME,No as createCodegenProject,BE as findTsconfig,VE as refreshCodegenProject,zE as runCodegen,UE as tsconfigFingerprint};
@@ -0,0 +1,2 @@
1
+ const S=(e,t=2166136261)=>{let i=t;for(let r=0;r<e.length;r+=1)i^=e.charCodeAt(r),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},A=e=>`${S(e,2166136261)}${S(e,16777619)}`,N=1;function C(e){const t={},i=Object.keys(e);i.sort();for(const r of i)t[r]=e[r];return t}const R=e=>`${JSON.stringify(e,void 0,2)}
2
+ `,ee=e=>A(R(e)),u=e=>typeof e=="object"&&e!==null,I=e=>u(e)&&u(e.fields)&&u(e.indexes)&&u(e.relations)&&typeof e.shardMode=="string",te=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(r){return{error:`baseline is not valid JSON: ${r instanceof Error?r.message:String(r)}`,status:"invalid"}}if(!u(t)||t.version!==1||!u(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[r,o]of Object.entries(t.tables))if(!I(o))return{error:`baseline table "${r}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},V=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,r)=>i===t.fields[r]),O=e=>e.unique!==void 0,m=({nullable:e,optional:t,refined:i,unique:r,...o})=>JSON.stringify(C(o)),x=e=>({form:JSON.stringify([m(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),F=e=>e.kind==="union"&&e.members?e.members.map(t=>x(t)):[x({...e,nullable:!1,optional:!1})],D=(e,t)=>{if(t.kind!=="union")return!1;const i=F(t);return F(e).every(r=>i.some(o=>o.form===r.form&&(r.refined||!o.refined)))},c=e=>{switch(e.kind){case"array":return`array(${e.of?c(e.of):"?"})`;case"from":return e.output===void 0?"from":`from(${e.output})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?c(e.key):"?"}, ${e.of?c(e.of):"?"})`;case"union":return(e.members??[]).map(t=>c(t)).join(" | ");default:return e.kind}},h=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),p=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),M=(e,t)=>{const i=JSON.stringify(e),r=JSON.stringify(t);return i===r?0:i<r?-1:1},f=e=>({...e,...e.kind==="from"?{output:void 0}:{},...e.fields?{fields:Object.fromEntries(Object.entries(e.fields).map(([t,i])=>[t,f(i)]))}:{},...e.key?{key:f(e.key)}:{},...e.of?{of:f(e.of)}:{},...e.members?{members:e.members.map(t=>f(t)).toSorted(M)}:{}}),j=e=>e.kind==="union"?e.members??[]:[e],L=(e,t)=>{const i=[...e],r=[...t],o=new Set,n=new Set,s=(d,a)=>{for(const[$,w]of i.entries()){if(n.has($))continue;const y=r.findIndex((_,E)=>!o.has(E)&&d(w,_));y!==-1&&(o.add(y),n.add($),a&&([i[$],r[y]]=g(w,r[y])))}};return s((d,a)=>JSON.stringify(d)===JSON.stringify(a),!1),s((d,a)=>m(f(d))===m(f(a)),!0),[i,r]},g=(e,t)=>{if(e.kind==="union"||t.kind==="union"){const[o,n]=L(j(e),j(t)),s=(d,a)=>d.kind==="union"?{...d,members:a.toSorted(M)}:a[0];return[s(e,o),s(t,n)]}if(e.kind!==t.kind)return[e,t];if(e.kind==="from")return e.output===void 0||t.output===void 0?[{...e,output:void 0},{...t,output:void 0}]:[e,t];const i={...e.fields?{fields:{...e.fields}}:{}},r={...t.fields?{fields:{...t.fields}}:{}};for(const o of["key","of"])e[o]&&t[o]&&([i[o],r[o]]=g(e[o],t[o]));for(const o of Object.keys(e.fields??{})){const n=e.fields?.[o],s=t.fields?.[o];n&&s&&i.fields&&r.fields&&([i.fields[o],r.fields[o]]=g(n,s))}return[{...e,...i},{...t,...r}]},P=(e,t,i,r,o)=>{const[n,s]=g(i,r);if(n.kind===s.kind&&(!o||m(n)===m(s)))return;if(o&&D(n,s))return p(e,"widenedFieldShape",`field ${e}.${t} widened: ${c(n)} → ${c(s)} — every stored value stays valid`);if(n.kind!==s.kind)return h(e,"changedFieldKind",`field ${e}.${t} changed type: ${n.kind} → ${s.kind} — add a data migration to convert existing values`);const d=Object.values(s.fields??{});return o&&n.kind==="object"&&Object.keys(n.fields??{}).length===0&&d.length>0&&d.every(a=>a.optional)?p(e,"widenedFieldShape",`field ${e}.${t} now records its optional object shape — stored values stay valid`):h(e,"changedFieldShape",`field ${e}.${t} changed shape: ${c(n)} → ${c(s)} — stored values were written against the old shape; add a data migration to convert them`)},H=(e,t,i,r,o)=>{const n=[];return i.unique!==r.unique&&n.push(r.unique===!0?{...h(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`),field:t,uniqueOn:[t]}:p(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==r.nullable&&n.push(r.nullable===!0?p(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):h(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),o&&i.refined!==r.refined&&n.push(r.refined===!0?h(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):p(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),n},J=(e,t,i,r,o=!0)=>{const n=[],s=O(i)&&O(r),d=P(e,t,i,r,s);return d&&n.push(d),s&&n.push(...H(e,t,i,r,o)),i.optional&&!r.optional?n.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&r.optional&&n.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),n},B=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},G=(e,t)=>t.refinementsRecorded!==!0||e.refinementsRecorded===!0,U=(e,t,i,r)=>{for(const[o,n]of Object.entries(i.fields)){const s=t.fields[o];s===void 0?r.push({...B(e,o,n),field:o}):r.push(...J(e,o,s,n,G(t,i)).map(d=>({...d,field:o})))}for(const o of Object.keys(t.fields))i.fields[o]===void 0&&r.push({field:o,remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},W=(e,t,i,r)=>{for(const[o,n]of Object.entries(i.indexes)){const s=t.indexes[o];if(s===void 0){r.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${o} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex",uniqueOn:n.fields}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}V(s,n)||r.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`index ${o} on ${e} changed shape and is unique — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"changedIndex",uniqueOn:n.fields}:{remediation:"none",scope:"table",severity:"safe",summary:`index ${o} on ${e} changed shape — a query that relied on the old index may need updating`,table:e,type:"changedIndex"})}for(const o of Object.keys(t.indexes))i.indexes[o]===void 0&&r.push({remediation:"none",severity:"safe",index:o,summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` no longer compiles`,table:e,scope:"table",type:"removedIndex"})},K=(e,t,i,r)=>{for(const o of Object.keys(i.relations))t.relations[o]===void 0&&r.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(t.relations))i.relations[o]===void 0&&r.push({remediation:"none",scope:"schema",severity:"safe",summary:`removed relation ${e}.${o} — the stored foreign-key values stay in place, but its \`onDelete\` action no longer runs and a \`with: { ${o} }\` read no longer compiles`,table:e,type:"removedRelation",warning:!0})},b="shardBy:_unknown_",v="global",z=(e,t)=>e===v&&t.startsWith(`${v}:`)||t===v&&e.startsWith(`${v}:`),Q=(e,t,i)=>{if(t===i)return i!==b?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${b}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!z(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode",...i===b?{}:{coverage:{shardMode:i,table:e}}}},T=e=>e.memory!==void 0,q=e=>e.after??0,k=e=>e.after===void 0?`{ field: "${e.field}" }`:`{ after: ${String(e.after)}, field: "${e.field}" }`,l=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,Y=(e,t,i)=>{if(t===void 0&&i===void 0)return;const r=(d,a)=>({coverage:{table:e,ttl:{...a.after===void 0?{}:{after:a.after},field:a.field}},expiry:{...a.after===void 0?{}:{after:a.after},field:a.field,...t===void 0?{}:{previous:{...t.after===void 0?{}:{after:t.after},field:t.field}}},remediation:"backfill",scope:"table",severity:"breaking",summary:d,table:e,type:"changedTtlPolicy"}),o=d=>({remediation:"none",scope:"table",severity:"safe",summary:d,table:e,type:"changedTtlPolicy",warning:!0});if(i===void 0)return o(`table ${e} dropped its TTL policy — its rows are no longer swept, so they stay until something else deletes them`);if(t===void 0)return r(`table ${e} gained a TTL policy ${l(i)} — every row already past the cutoff is deleted on the next alarm sweep; refresh or clear "${i.field}" on the rows that must survive, then declare a migration with covers: { table: "${e}", ttl: ${k(i)} }`,i);if(t.field!==i.field)return r(`table ${e} moved its TTL to a different column: ${l(t)} → ${l(i)} — rows are now expired by a column they were never written against; populate "${i.field}" on the rows that must survive, then declare a migration with covers: { table: "${e}", ttl: ${k(i)} }`,i);const n=q(t),s=q(i);return s<n?r(`table ${e} shortened its TTL: ${l(t)} → ${l(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; refresh "${i.field}" on the rows that must survive, then declare a migration with covers: { table: "${e}", ttl: ${k(i)} }`,i):s>n?o(`table ${e} lengthened its TTL: ${l(t)} → ${l(i)} — every row stays, and expires later than it would have`):void 0},X=(e,t,i)=>{const r=[];return t.memory!==i.memory&&r.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode",coverage:{memory:!0,table:e}}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&r.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering",identityRewrites:!0}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer .commitOrdered() — stored rows are untouched, but new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers`,table:e,type:"changedCommitOrdering",warning:!0}),r},Z=(e,t,i,r)=>{const o=Q(e,t.shardMode,i.shardMode);if(o&&r.push(o),T(t)&&T(i)){r.push(...X(e,t,i));const n=Y(e,t.ttl,i.ttl);n&&r.push(n)}U(e,t,i,r),W(e,t,i,r),K(e,t,i,r)},ie=(e,t)=>{const i=[],r=e?.tables??{};for(const[o,n]of Object.entries(t.tables)){const s=r[o];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}Z(o,s,n,i)}for(const o of Object.keys(r))t.tables[o]===void 0&&i.push({remediation:"none",scope:"table",severity:"safe",summary:`removed table ${o} — its rows are left in place in each shard's SQLite (nothing deletes them) but are unreachable through the schema; export the shard first if the data must be kept, or declare the table again to reach it`,table:o,type:"removedTable",warning:!0});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const o=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (export then import to move it). Revert the change, or declare a migration with covers: { jurisdiction: "${t.jurisdiction??"none"}" } once the data is moved.`,type:"changedJurisdiction",coverage:{jurisdiction:t.jurisdiction??"none"}})}return{changes:i}};export{N as SCHEMA_SNAPSHOT_VERSION,c as describeShape,J as diffExistingField,ie as diffSchemaSnapshots,ee as hashSchemaSnapshot,I as isValidTableSnapshot,te as parseSnapshotJson,R as serializeSchemaSnapshot,C as sortKeys};
@@ -0,0 +1 @@
1
+ import{existsSync as d}from"node:fs";import{join as g}from"node:path";import{SyntaxKind as m,Node as o}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as u}from"./module-specifiers-BctA0m_p.mjs";import{p as h}from"./parse-validator-BisfC8bR.mjs";import{findObjectProperty as c}from"./isTestPath-JdN4KXhV.mjs";import{a as x}from"./attribution-CTMkuBkn.mjs";import{m as f}from"./ip-reads-Dotjify6.mjs";const S="shapes.ts",b=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return u(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},y=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(m.ImportDeclaration);return i!==void 0&&u(i.getModuleSpecifierValue())}return!1},I=r=>{if(o.isIdentifier(r))return b(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&y(t)}return!1},N=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=c(t,"table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},A=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=c(t,"args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:h(i)},E=r=>{const[t]=r.getArguments(),e=o.isObjectLiteralExpression(t)?c(t,"where"):void 0,i=o.isPropertyAssignment(e)?e.getInitializer():void 0;if(e===void 0)return f(r);if(!o.isArrowFunction(i)&&!o.isFunctionExpression(i))return!0;const n=i.getParameters()[0]?.getNameNode();return o.isIdentifier(n)&&n.getText()!=="ctx"&&n.findReferencesAsNodes().length>0||f(r)},P=r=>{const t=[];for(const e of r.getVariableDeclarations()){const i=e.getInitializer();if(i?.getKind()!==m.CallExpression)continue;const n=i,s=n.getExpression();if(!I(s))continue;const a=e.getNameNode();if(!o.isIdentifier(a)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw l(a,"defineShape exports must be plain named exports (no destructuring)")}const p=x(e,"binding");p!==void 0&&t.push({args:A(n),exportName:p,filePath:"shapes",...E(n)?{readsIp:!0}:{},table:N(n)})}return t},V=(r,t)=>{const e=g(t,S);if(!d(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=P(i);return n.sort((s,a)=>s.exportName.localeCompare(a.exportName)),n};export{S as SHAPES_FILENAME,V as discoverShapes};
@@ -1,17 +1,17 @@
1
- import{LunoraError as j}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as v,diffSchemaSnapshots as O,parseSnapshotJson as T}from"./SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs";import{isHyperdriveGlobalTable as R}from"./isD1GlobalTable-udvHAAzD.mjs";const N=e=>{const t=e.shardMode;return t==="global"?`global:${R(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},A=(e,t)=>{const n=JSON.stringify(e),i=JSON.stringify(t);return n===i?0:n<i?-1:1},g=e=>{const t=e.kind==="optional",n=t?e.inner:void 0,i=n??e,s={kind:t?n?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...L[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(s.refined=!0),s},_=e=>{const t={};for(const[n,i]of Object.entries(e))t[n]=g(i);return v(t)},E=/import\(\s*["'`](?:[A-Za-z]:)?[\\/]/u,L={array:e=>e.inner?{of:g(e.inner)}:{},from:e=>e.tsType===void 0||E.test(e.tsType)?{}:{output:e.tsType},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:_(e.shape)}:{},record:e=>({...e.keyType?{key:g(e.keyType)}:{},...e.valueType?{of:g(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>g(t)).toSorted(A)}:{}},C=e=>{const t={};for(const[r,d]of Object.entries(e.shape))t[r]=g(d);const n={};for(const r of e.indexes)n[r.name]={fields:[...r.fields],unique:r.unique??!1};const i={};for(const r of e.relations)i[r.name]=r.through===void 0?{field:r.field,kind:r.kind,table:r.table}:{kind:r.kind,table:r.table,through:{...r.through}};const s={commitOrdered:e.commitOrdered===!0,fields:v(t),indexes:v(n),memory:e.memory===!0,relations:v(i),shardMode:N(e)};return e.ttl&&(s.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),s},W=(e,t)=>{const n={};for(const s of e.tables)n[s.name]=C(s);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:v(n),version:I}};class D extends j{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const Z=e=>{const t=T(e);if(t.status==="invalid")throw new D(t.error);return t.status==="ok"?t.snapshot:void 0},G=e=>e.flatMap(t=>t.index===void 0?[]:[{file:t.file,function:t.scope.kind==="module"?"<module>":t.scope.name,index:t.index.name,line:t.line,table:t.table}]),F=" • For a change you know is safe: pass `--allow-schema-drift` to skip the block for this run. It checks nothing and leaves the baseline unchanged, so the next run drifts again.",q=()=>`${F}
2
- `,k=e=>e.map(t=>` - ${t.summary}`).join(`
3
- `),x=e=>e.remediation==="backfill"&&e.table!==void 0,H=(e,t)=>e===t||e==="global"&&t.startsWith("global:"),M=(e,t)=>{const n=t.coverage,i=e.covers;return n===void 0||i===void 0||n.table!==void 0&&(i.table!==n.table||e.table!==n.table||e.identity===!0)?!1:(n.ttl===void 0||i.ttl?.field===n.ttl.field&&(i.ttl.after??0)===(n.ttl.after??0))&&(n.jurisdiction===void 0||i.jurisdiction===n.jurisdiction)&&(n.memory!==!0||i.memory===!0)&&(n.shardMode===void 0||H(i.shardMode,n.shardMode))},P=(e,t)=>{if(e.type!=="removedIndex"||e.index===void 0)return e;const n=t.filter(s=>(s.table===e.table||s.table==="")&&(s.index===e.index||s.index===void 0));if(n.length===0)return e;const i=n.slice(0,5).map(s=>`${s.function} (${s.file}:${String(s.line)}${s.index===void 0?", index name is not a literal":""})`).join(", ");return{...e,remediation:"code",severity:"breaking",summary:`removed index ${e.index??""} on ${e.table??""} is still used by ${i}${n.length>5?` and ${String(n.length-5)} more`:""} — point the query at another index, or restore the index`}},J=/^[A-Za-z_]\w*$/u,U=e=>` lunora migrate create backfill_${e} --table ${e}`,z=(e,t,n)=>{const{identity:i,unresolved:s}=t,r=[...new Set(e.filter(a=>x(a)&&a.coverage===void 0).flatMap(a=>a.table??[]))],d=[];if(r.length>0){d.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const a=r.filter(l=>J.test(l));a.length>0&&d.push(`
1
+ import{LunoraError as j}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as v,diffSchemaSnapshots as O,parseSnapshotJson as T}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as R}from"./isD1GlobalTable-udvHAAzD.mjs";const N=e=>{const t=e.shardMode;return t==="global"?`global:${R(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},A=(e,t)=>{const n=JSON.stringify(e),i=JSON.stringify(t);return n===i?0:n<i?-1:1},g=e=>{const t=e.kind==="optional",n=t?e.inner:void 0,i=n??e,s={kind:t?n?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...L[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(s.refined=!0),s},_=e=>{const t={};for(const[n,i]of Object.entries(e))t[n]=g(i);return v(t)},E=/import\(\s*["'`](?:[A-Za-z]:)?[\\/]/u,L={array:e=>e.inner?{of:g(e.inner)}:{},from:e=>e.tsType===void 0||E.test(e.tsType)?{}:{output:e.tsType},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:_(e.shape)}:{},record:e=>({...e.keyType?{key:g(e.keyType)}:{},...e.valueType?{of:g(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>g(t)).toSorted(A)}:{}},C=e=>{const t={};for(const[r,d]of Object.entries(e.shape))t[r]=g(d);const n={};for(const r of e.indexes)n[r.name]={fields:[...r.fields],unique:r.unique??!1};const i={};for(const r of e.relations)i[r.name]=r.through===void 0?{field:r.field,kind:r.kind,table:r.table}:{kind:r.kind,table:r.table,through:{...r.through}};const s={commitOrdered:e.commitOrdered===!0,fields:v(t),indexes:v(n),memory:e.memory===!0,relations:v(i),shardMode:N(e)};return e.extensionFromPackage===!0&&(s.refinementsRecorded=!0),e.ttl&&(s.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),s},W=(e,t)=>{const n={};for(const s of e.tables)n[s.name]=C(s);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:v(n),version:I}};class D extends j{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const Z=e=>{const t=T(e);if(t.status==="invalid")throw new D(t.error);return t.status==="ok"?t.snapshot:void 0},G=e=>e.flatMap(t=>t.index===void 0?[]:[{file:t.file,function:t.scope.kind==="module"?"<module>":t.scope.name,index:t.index.name,line:t.line,table:t.table}]),F=" • For a change you know is safe: pass `--allow-schema-drift` to skip the block for this run. It checks nothing and leaves the baseline unchanged, so the next run drifts again.",P=()=>`${F}
2
+ `,w=e=>e.map(t=>` - ${t.summary}`).join(`
3
+ `),x=e=>e.remediation==="backfill"&&e.table!==void 0,q=(e,t)=>e===t||e==="global"&&t.startsWith("global:"),M=(e,t)=>{const n=t.coverage,i=e.covers;return n===void 0||i===void 0||n.table!==void 0&&(i.table!==n.table||e.table!==n.table||e.identity===!0)?!1:(n.ttl===void 0||i.ttl?.field===n.ttl.field&&(i.ttl.after??0)===(n.ttl.after??0))&&(n.jurisdiction===void 0||i.jurisdiction===n.jurisdiction)&&(n.memory!==!0||i.memory===!0)&&(n.shardMode===void 0||q(i.shardMode,n.shardMode))},H=(e,t)=>{if(e.type!=="removedIndex"||e.index===void 0)return e;const n=t.filter(s=>(s.table===e.table||s.table==="")&&(s.index===e.index||s.index===void 0));if(n.length===0)return e;const i=n.slice(0,5).map(s=>`${s.function} (${s.file}:${String(s.line)}${s.index===void 0?", index name is not a literal":""})`).join(", ");return{...e,remediation:"code",severity:"breaking",summary:`removed index ${e.index??""} on ${e.table??""} is still used by ${i}${n.length>5?` and ${String(n.length-5)} more`:""} — point the query at another index, or restore the index`}},J=/^[A-Za-z_]\w*$/u,U=e=>` lunora migrate create backfill_${e} --table ${e}`,z=(e,t,n)=>{const{identity:i,unresolved:s}=t,r=[...new Set(e.filter(a=>x(a)&&a.coverage===void 0).flatMap(a=>a.table??[]))],d=[];if(r.length>0){d.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const a=r.filter(l=>J.test(l));a.length>0&&d.push(`
4
4
  Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
5
5
  ${a.map(l=>U(l)).join(`
6
6
  `)}
7
7
 
8
8
  `)}s.length>0&&d.push(` • Migration(s) ${s.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
9
9
  `),i.length>0&&e.some(a=>a.identityRewrites!==!0)&&d.push(` • Migration(s) ${i.join(", ")} return each document unchanged, so they rewrite no row and cover nothing. Fill in \`up\`.
10
- `),r.length>0&&d.push(" • If the stored rows already fit the new schema, `lunora deploy` goes ahead on its own: it reads the rows of each affected table from the deployed worker (`--migrate-url` or the project link, plus `LUNORA_ADMIN_TOKEN`) and names any row that does not fit.\n");for(const a of e){const{coverage:l}=a;if(l===void 0)continue;const u=l.table??e.find(h=>h.table!==void 0)?.table??"users",f=`{ ${Object.entries(l).toSorted(([h],[p])=>h.localeCompare(p)).map(([h,p])=>`${h}: ${typeof p=="object"?`{ ${Object.entries(p).map(([y,$])=>`${y}: ${JSON.stringify($)}`).join(", ")} }`:JSON.stringify(p)}`).join(", ")} }`,m=l.table===void 0?"":` and iterates \`${l.table}\` with an \`up\` that rewrites rows`,S=a.summary.split(" — ")[0]??"",w=l.ttl===void 0?`Move the rows first (\`lunora export --tables ${u} --out ${u}.ndjson\`, deploy, \`lunora import ${u}.ndjson\`), then declare: `:`Decide which rows must survive and refresh \`${l.ttl.field}\` on them in \`up\`, then declare: `;d.push(` • "${S}" moves, empties or deletes data, so it stays blocked until a new migration declares \`covers: ${f}\`${m}. ${w}\`defineMigration({ id: "rehome_${u}", table: "${l.table??u}", covers: ${f}, up: (doc) => ({ ...doc, tenantId: doc.tenantId ?? "default" }) })\`.
11
- `)}return d.push(q()),[`${n??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,k(e),"",`To fix:
10
+ `),r.length>0&&d.push(" • If the stored rows already fit the new schema, `lunora deploy` goes ahead on its own: it reads the rows of each affected table from the deployed worker (`--migrate-url` or the project link, plus `LUNORA_ADMIN_TOKEN`) and names any row that does not fit.\n");for(const a of e){const{coverage:l}=a;if(l===void 0)continue;const u=l.table??e.find(h=>h.table!==void 0)?.table??"users",f=`{ ${Object.entries(l).toSorted(([h],[p])=>h.localeCompare(p)).map(([h,p])=>`${h}: ${typeof p=="object"?`{ ${Object.entries(p).map(([y,$])=>`${y}: ${JSON.stringify($)}`).join(", ")} }`:JSON.stringify(p)}`).join(", ")} }`,m=l.table===void 0?"":` and iterates \`${l.table}\` with an \`up\` that rewrites rows`,S=a.summary.split(" — ")[0]??"",k=l.ttl===void 0?`Move the rows first (\`lunora export --tables ${u} --out ${u}.ndjson\`, deploy, \`lunora import ${u}.ndjson\`), then declare: `:`Decide which rows must survive and refresh \`${l.ttl.field}\` on them in \`up\`, then declare: `;d.push(` • "${S}" moves, empties or deletes data, so it stays blocked until a new migration declares \`covers: ${f}\`${m}. ${k}\`defineMigration({ id: "rehome_${u}", table: "${l.table??u}", covers: ${f}, up: (doc) => ({ ...doc, tenantId: doc.tenantId ?? "default" }) })\`.
11
+ `)}return d.push(P()),[`${n??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,w(e),"",`To fix:
12
12
  ${d.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
13
- `)},Q=e=>{const{allowDrift:t=!1,baseline:n,command:i,current:s,indexReferences:r=[],migrations:d}=e,a={changes:O(n,s).changes.map(o=>P(o,r))},l=a.changes.filter(o=>o.severity==="breaking"),u=s.migrationIds.filter(o=>!(n?.migrationIds??[]).includes(o)),f=d.filter(o=>u.includes(o.id)),m=(o,c,b=[])=>({blocked:o,changes:a.changes,newMigrationIds:u,reason:c,uncovered:b}),S=new Set(f.filter(o=>o.table!==""&&o.identity!==!0).map(o=>o.table)),w=f.filter(o=>o.table==="").map(o=>o.id),h=f.filter(o=>o.table!==""&&o.identity===!0).map(o=>o.id);if(a.changes.length===0||n===void 0)return m(!1,"");if(l.length===0)return m(!1,`schema drift detected (all additive/safe):
14
- ${k(a.changes)}`);const p=o=>o.coverage!==void 0?f.some(c=>M(c,o)):o.identityRewrites===!0&&o.table!==void 0?f.some(c=>c.table===o.table):x(o)&&S.has(o.table),y=l.filter(o=>!p(o));if(y.length===0){const o=f.filter(c=>l.some(b=>b.coverage===void 0?x(b)&&(c.identity!==!0||b.identityRewrites===!0)&&b.table===c.table:M(c,b))).map(c=>c.id);return m(!1,`breaking schema drift detected, covered by ${String(o.length)} new migration(s) (${o.join(", ")}):
15
- ${k(l)}`)}const $=z(y,{identity:h,unresolved:w},i);return t?m(!1,`${$}
13
+ `)},Q=e=>{const{allowDrift:t=!1,baseline:n,command:i,current:s,indexReferences:r=[],migrations:d}=e,a={changes:O(n,s).changes.map(o=>H(o,r))},l=a.changes.filter(o=>o.severity==="breaking"),u=s.migrationIds.filter(o=>!(n?.migrationIds??[]).includes(o)),f=d.filter(o=>u.includes(o.id)),m=(o,c,b=[])=>({blocked:o,changes:a.changes,newMigrationIds:u,reason:c,uncovered:b}),S=new Set(f.filter(o=>o.table!==""&&o.identity!==!0).map(o=>o.table)),k=f.filter(o=>o.table==="").map(o=>o.id),h=f.filter(o=>o.table!==""&&o.identity===!0).map(o=>o.id);if(a.changes.length===0||n===void 0)return m(!1,"");if(l.length===0)return m(!1,`schema drift detected (all additive/safe):
14
+ ${w(a.changes)}`);const p=o=>o.coverage!==void 0?f.some(c=>M(c,o)):o.identityRewrites===!0&&o.table!==void 0?f.some(c=>c.table===o.table):x(o)&&S.has(o.table),y=l.filter(o=>!p(o));if(y.length===0){const o=f.filter(c=>l.some(b=>b.coverage===void 0?x(b)&&(c.identity!==!0||b.identityRewrites===!0)&&b.table===c.table:M(c,b))).map(c=>c.id);return m(!1,`breaking schema drift detected, covered by ${String(o.length)} new migration(s) (${o.join(", ")}):
15
+ ${w(l)}`)}const $=z(y,{identity:h,unresolved:k},i);return t?m(!1,`${$}
16
16
 
17
17
  (overridden by --allow-schema-drift)`,y):m(!0,$,y)};export{D as SchemaSnapshotParseError,W as buildSchemaSnapshot,Q as evaluateSchemaDrift,G as indexReferencesOf,Z as parseSchemaSnapshot};
@@ -1 +1 @@
1
- import{existsSync as b}from"node:fs";import{join as y}from"node:path";import{LunoraError as w}from"@lunora/errors";import k from"@lunora/scheduler/validate";import{workflowDefaultName as E,workflowClassName as v}from"@lunora/workflow";import{Node as n,VariableDeclarationKind as S,SyntaxKind as x}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as N,findObjectProperty as d,stringPropertyFor as L}from"./isTestPath-JdN4KXhV.mjs";import{a as P}from"./attribution-DUbGYT4N.mjs";import{r as $}from"./handler-reference-D1wpw_qR.mjs";const A="workflows.ts",W=new Set(["do","sleep","sleepUntil","waitForEvent"]),C=o=>{const e=o.getSymbol();if(!e)return o.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(n.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},m=L("workflow"),O=(o,e,t)=>{if(n.isNumericLiteral(o))return o.getLiteralValue();throw c(o,`workflow "${e}": \`${t}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},f=(o,e)=>{const t=d(o,e);return t&&n.isPropertyAssignment(t)?t.getInitializerOrThrow():void 0},g=(o,e,t)=>{if(n.isObjectLiteralExpression(o))return o;throw c(o,`workflow "${e}": \`${t}\` must be an inline object literal — it is deploy configuration codegen writes into wrangler.jsonc`)},D=(o,e)=>{if(!n.isArrayLiteralExpression(o)||o.getElements().length===0)throw c(o,`workflow "${e}": \`schedules\` must be a non-empty inline array of cron expression string literals`);return o.getElements().map(t=>{const r=m(t,e,"schedules[]");if(!k(r))throw c(t,`workflow "${e}": schedule "${r}" is not a valid cron expression`);return r})},I=(o,e)=>{const t={},r=f(o,"schedules");r!==void 0&&(t.schedules=D(r,e));const s=f(o,"limits");if(s!==void 0){const i=f(g(s,e,"limits"),"steps");if(i===void 0)t.limits={};else{const l=O(i,e,"limits.steps");if(!Number.isInteger(l)||l<=0)throw c(i,`workflow "${e}": \`limits.steps\` must be a positive integer (got ${String(l)})`);t.limits={steps:l}}}const a=f(o,"defaultRetention");if(a!==void 0){const i=g(a,e,"defaultRetention"),l={};for(const u of["errorRetention","successRetention"]){const p=f(i,u);p!==void 0&&(l[u]=m(p,e,`defaultRetention.${u}`))}t.defaultRetention=l}return t},F=o=>{const e=o.getExpression();if(!n.isPropertyAccessExpression(e)||!W.has(e.getName()))return!1;const t=e.getExpression();return n.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:n.isIdentifier(t)&&t.getText()==="step"},T=o=>{if(!o)return[];const e=[];for(const t of o.getDescendantsOfKind(x.CallExpression)){if(!F(t))continue;const r=t.getArguments()[0];!r||!(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))||e.push({line:t.getStartLineNumber(),method:t.getExpression().getName(),name:r.getLiteralValue()})}return e},h=o=>{let e=o;for(;e&&(n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},R=o=>{const e=h(o);if(e&&n.isObjectLiteralExpression(e))return e;if(!(!e||!n.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const s=n.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===S.Const?h(t.getInitializer()):void 0;if(s&&n.isObjectLiteralExpression(s))return s}},j=(o,e)=>{const t=d(o,"handler"),r=$(t,e);return r!==void 0?r:{body:t!==void 0&&n.isPropertyAssignment(t)?t.getInitializer():t}},K=(o,e,t)=>{const r=R(o.getArguments()[0]);if(!r)throw c(o,`workflow "${e}": defineWorkflow's argument must be an object literal, or a local \`const\` holding one — codegen reads \`name\` and the \`ctx.step.*\` calls out of it statically. Keep the handler wherever you like and pass it through: \`const config = { handler: myHandler }; export const ${e} = defineWorkflow(config);\`.`);const s=j(r,t),a={className:v(e),exportName:e,name:E(e),steps:T(s.body),...s.file===void 0?{}:{handlerFile:s.file},...s.site===void 0?{}:{handlerSite:s.site}},i=d(r,"name");return i&&n.isPropertyAssignment(i)&&(a.name=m(i.getInitializerOrThrow(),e,"name")),{...a,...I(r,e)}},V=(o,e)=>{const t=[];for(const r of o.getVariableDeclarations()){const s=N(r.getInitializer());if(!s)continue;const a=s.getExpression();if(!n.isIdentifier(a)||!C(a))continue;const i=r.getNameNode();if(!n.isIdentifier(i)){if(r.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw c(i,"defineWorkflow exports must be plain named exports (no destructuring)")}const l=P(r,"binding");l!==void 0&&t.push(K(s,l,e))}return t},z=o=>{const e=new Map,t=new Map;for(const r of o){const s=e.get(r.name);if(s!==void 0)throw new w("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${r.name}": produced by both "${s}" and "${r.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(r.name,r.exportName);const a=t.get(r.className);if(a!==void 0)throw new w("DUPLICATE_WORKFLOW_CLASS",`Duplicate workflow class "${r.className}": produced by both "${a}" and "${r.exportName}". Workflow export names must yield unique generated class names.`,{status:500});t.set(r.className,r.exportName)}},Y=(o,e)=>{const t=y(e,A);if(!b(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),s=V(r,e);return s.sort((a,i)=>a.exportName.localeCompare(i.exportName)),z(s),s};export{A as WORKFLOWS_FILENAME,Y as discoverWorkflows};
1
+ import{existsSync as b}from"node:fs";import{join as y}from"node:path";import{LunoraError as w}from"@lunora/errors";import k from"@lunora/scheduler/validate";import{workflowDefaultName as E,workflowClassName as v}from"@lunora/workflow";import{Node as n,VariableDeclarationKind as S,SyntaxKind as x}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as N,findObjectProperty as d,stringPropertyFor as L}from"./isTestPath-JdN4KXhV.mjs";import{a as P}from"./attribution-CTMkuBkn.mjs";import{r as $}from"./handler-reference-90LXJART.mjs";const A="workflows.ts",W=new Set(["do","sleep","sleepUntil","waitForEvent"]),C=o=>{const e=o.getSymbol();if(!e)return o.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(n.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},m=L("workflow"),O=(o,e,t)=>{if(n.isNumericLiteral(o))return o.getLiteralValue();throw c(o,`workflow "${e}": \`${t}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},f=(o,e)=>{const t=d(o,e);return t&&n.isPropertyAssignment(t)?t.getInitializerOrThrow():void 0},g=(o,e,t)=>{if(n.isObjectLiteralExpression(o))return o;throw c(o,`workflow "${e}": \`${t}\` must be an inline object literal — it is deploy configuration codegen writes into wrangler.jsonc`)},D=(o,e)=>{if(!n.isArrayLiteralExpression(o)||o.getElements().length===0)throw c(o,`workflow "${e}": \`schedules\` must be a non-empty inline array of cron expression string literals`);return o.getElements().map(t=>{const r=m(t,e,"schedules[]");if(!k(r))throw c(t,`workflow "${e}": schedule "${r}" is not a valid cron expression`);return r})},I=(o,e)=>{const t={},r=f(o,"schedules");r!==void 0&&(t.schedules=D(r,e));const s=f(o,"limits");if(s!==void 0){const i=f(g(s,e,"limits"),"steps");if(i===void 0)t.limits={};else{const l=O(i,e,"limits.steps");if(!Number.isInteger(l)||l<=0)throw c(i,`workflow "${e}": \`limits.steps\` must be a positive integer (got ${String(l)})`);t.limits={steps:l}}}const a=f(o,"defaultRetention");if(a!==void 0){const i=g(a,e,"defaultRetention"),l={};for(const u of["errorRetention","successRetention"]){const p=f(i,u);p!==void 0&&(l[u]=m(p,e,`defaultRetention.${u}`))}t.defaultRetention=l}return t},F=o=>{const e=o.getExpression();if(!n.isPropertyAccessExpression(e)||!W.has(e.getName()))return!1;const t=e.getExpression();return n.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:n.isIdentifier(t)&&t.getText()==="step"},T=o=>{if(!o)return[];const e=[];for(const t of o.getDescendantsOfKind(x.CallExpression)){if(!F(t))continue;const r=t.getArguments()[0];!r||!(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))||e.push({line:t.getStartLineNumber(),method:t.getExpression().getName(),name:r.getLiteralValue()})}return e},h=o=>{let e=o;for(;e&&(n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},R=o=>{const e=h(o);if(e&&n.isObjectLiteralExpression(e))return e;if(!(!e||!n.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const s=n.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===S.Const?h(t.getInitializer()):void 0;if(s&&n.isObjectLiteralExpression(s))return s}},j=(o,e)=>{const t=d(o,"handler"),r=$(t,e);return r!==void 0?r:{body:t!==void 0&&n.isPropertyAssignment(t)?t.getInitializer():t}},K=(o,e,t)=>{const r=R(o.getArguments()[0]);if(!r)throw c(o,`workflow "${e}": defineWorkflow's argument must be an object literal, or a local \`const\` holding one — codegen reads \`name\` and the \`ctx.step.*\` calls out of it statically. Keep the handler wherever you like and pass it through: \`const config = { handler: myHandler }; export const ${e} = defineWorkflow(config);\`.`);const s=j(r,t),a={className:v(e),exportName:e,name:E(e),steps:T(s.body),...s.file===void 0?{}:{handlerFile:s.file},...s.site===void 0?{}:{handlerSite:s.site}},i=d(r,"name");return i&&n.isPropertyAssignment(i)&&(a.name=m(i.getInitializerOrThrow(),e,"name")),{...a,...I(r,e)}},V=(o,e)=>{const t=[];for(const r of o.getVariableDeclarations()){const s=N(r.getInitializer());if(!s)continue;const a=s.getExpression();if(!n.isIdentifier(a)||!C(a))continue;const i=r.getNameNode();if(!n.isIdentifier(i)){if(r.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw c(i,"defineWorkflow exports must be plain named exports (no destructuring)")}const l=P(r,"binding");l!==void 0&&t.push(K(s,l,e))}return t},z=o=>{const e=new Map,t=new Map;for(const r of o){const s=e.get(r.name);if(s!==void 0)throw new w("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${r.name}": produced by both "${s}" and "${r.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(r.name,r.exportName);const a=t.get(r.className);if(a!==void 0)throw new w("DUPLICATE_WORKFLOW_CLASS",`Duplicate workflow class "${r.className}": produced by both "${a}" and "${r.exportName}". Workflow export names must yield unique generated class names.`,{status:500});t.set(r.className,r.exportName)}},Y=(o,e)=>{const t=y(e,A);if(!b(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),s=V(r,e);return s.sort((a,i)=>a.exportName.localeCompare(i.exportName)),z(s),s};export{A as WORKFLOWS_FILENAME,Y as discoverWorkflows};