callback-synthesizer.ts 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818
  1. /**
  2. * Callback / observer edge synthesis — Phase 1 + 2.
  3. *
  4. * Closes dynamic-dispatch holes where a dispatcher invokes callbacks registered
  5. * elsewhere. Two channel shapes:
  6. *
  7. * (1) Field-backed observer (Phase 1):
  8. * onUpdate(cb) { this.callbacks.add(cb); } // registrar
  9. * triggerUpdate() { for (cb of this.callbacks) cb(); } // dispatcher
  10. * scene.onUpdate(this.triggerRender) // registration
  11. * → synthesize triggerUpdate → triggerRender
  12. *
  13. * (2) String-keyed EventEmitter (Phase 2):
  14. * this.on('mount', function onmount(){...}) // registration
  15. * fn.emit('mount', this) // dispatch
  16. * → synthesize (method containing emit('mount')) → onmount
  17. *
  18. * Whole-graph pass after base resolution. High-precision/low-recall by design:
  19. * named callbacks only; field channels paired by file+field; EventEmitter
  20. * channels capped by event fan-out (generic names like 'error' skipped — they
  21. * need receiver-type matching, deferred to Phase 3). All synthesized edges are
  22. * tagged `provenance:'heuristic'`. See docs/design/callback-edge-synthesis.md.
  23. */
  24. import type { Edge, Node, NodeKind } from '../types';
  25. import type { QueryBuilder } from '../db/queries';
  26. import type { ResolutionContext } from './types';
  27. import { isGeneratedFile } from '../extraction/generated-detection';
  28. import { stripCommentsForRegex } from './strip-comments';
  29. import { cFnPointerDispatchEdges } from './c-fnptr-synthesizer';
  30. import { goframeRouteEdges } from './goframe-synthesizer';
  31. import { expoRouterReturnEdges } from './expo-router-synthesizer';
  32. import { nextLinkEdges } from './next-router-synthesizer';
  33. import { reactRouterLinkEdges } from './react-router-synthesizer';
  34. import { tanstackLinkEdges } from './tanstack-router-synthesizer';
  35. import { vueRouterLinkEdges } from './vue-router-synthesizer';
  36. import { svelteKitLinkEdges, svelteKitPageComponentEdges } from './sveltekit-synthesizer';
  37. import { createYielder, type MaybeYield } from './cooperative-yield';
  38. import { crossTierEdges } from './tier-synthesizer';
  39. import { enclosingFn, makeLineAt } from './synth-utils';
  40. const REGISTRAR_NAME = /^(on[A-Z]\w*|subscribe|addListener|addEventListener|register|watch|listen|addCallback)$/;
  41. const DISPATCHER_NAME = /(emit|trigger|notify|dispatch|fire|publish|flush)/i;
  42. const MAX_CALLBACKS_PER_CHANNEL = 40;
  43. const EVENT_FANOUT_CAP = 6; // skip events with more handlers/dispatchers than this (too generic without type info)
  44. const ON_RE = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*(?:function\s+(\w+)|(?:this\.)?(\w+))/g;
  45. const EMIT_RE = /\.(?:emit|fire|dispatchEvent)\(\s*['"]([^'"]+)['"]/g;
  46. const SETSTATE_RE = /this\.setState\s*\(/;
  47. const FLUTTER_SETSTATE_RE = /\bsetState\s*\(/; // Flutter: setState((){…}) / this.setState
  48. const JSX_TAG_RE = /<([A-Z][A-Za-z0-9_]*)[\s/>]/g;
  49. const MAX_JSX_CHILDREN = 30;
  50. // Vue SFC templates: kebab-case child components (<el-button> → ElButton) and
  51. // event bindings (@click="fn" / v-on:click="fn"). PascalCase children (<VPNav/>)
  52. // are already caught by JSX_TAG_RE via the SFC component node.
  53. const VUE_KEBAB_RE = /<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)[\s/>]/g;
  54. // PascalCase component tags — `<MediaCard ...>`, `<NavBar/>`. HTML elements are
  55. // lowercase, so an uppercase-initial tag is a component usage; built-ins
  56. // (`<NuxtLink>`, `<Transition>`) simply resolve to nothing and emit no edge.
  57. const VUE_PASCAL_RE = /<([A-Z][A-Za-z0-9]*)[\s/>]/g;
  58. const VUE_HANDLER_RE = /(?:@|v-on:)([a-zA-Z][\w-]*)(?:\.[\w]+)*\s*=\s*"([^"]+)"/g;
  59. // Composable/hook destructure: `const { close: closeSidebar } = useSidebarControl()`.
  60. // Captures the destructure body + the called composable; only `use*` calls qualify.
  61. const VUE_DESTRUCTURE_RE = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*(\w+)\s*\(/g;
  62. // Closure-collection dynamic dispatch (language-agnostic, Swift-first). A method
  63. // appends a closure to a collection property; another method iterates that
  64. // property *invoking each element* (`coll.forEach { $0() }` / `{ it() }`). The
  65. // element-invoke (`$0(` / `it(`) PROVES the collection holds closures, so pairing
  66. // a dispatcher to same-named registrars (`.append`/`.add`/`.push`/`.insert`,
  67. // incl. Swift `prop.write { $0.append }`) is high-precision. Cross-file/class by
  68. // design: Alamofire appends in `DataRequest.validate` but iterates in the base
  69. // `Request.didCompleteTask` — neither same-file nor same-class pairing reaches it.
  70. const CC_DISPATCH_RE = /(\w+)\.forEach\s*\{\s*(?:\$0|it)\s*\(/g;
  71. const CC_APPEND_WRITE_RE = /(\w+)\.write\s*\{\s*\$0(?:\.(\w+))?\.(?:append|add|push|insert)\s*\(/g;
  72. const CC_APPEND_DIRECT_RE = /(\w+)\.(?:append|add|push|insert)\s*\(/g;
  73. const CC_FANOUT_CAP = 8; // skip a field name with more dispatchers/registrars than this (too generic to pair confidently)
  74. // The dispatcher gate — `{ $0( ` / `{ it( ` element-invocation — is Swift/Kotlin
  75. // trailing-closure syntax, so ONLY those languages can ever contribute a
  76. // dispatcher, and a cross-language registrar pairing (a JS `.push(` against a
  77. // Swift dispatcher's field name) would be a wrong edge, not a missed one.
  78. // Gating both sides here isn't just precision: `.push(`/`.add(` is everywhere
  79. // in JS/PHP, so an ungated scan slices + regexes nearly every function on repos
  80. // where the pass cannot emit a single edge — on a 12k-file PHP/JS app that was
  81. // 20+ minutes of the "Resolving refs" tail and a #850 watchdog kill (#1235).
  82. const CC_LANGUAGES = new Set(['swift', 'kotlin']);
  83. function kebabToPascal(s: string): string {
  84. return s.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
  85. }
  86. /**
  87. * Nuxt auto-import name for a component, derived from its path UNDER `components/`:
  88. * `components/media/Card.vue` → `MediaCard`, `components/base/foo/Bar.vue` →
  89. * `BaseFooBar`. Each directory segment and the filename is PascalCased and
  90. * concatenated; a directory whose PascalCase name prefixes the next segment is
  91. * collapsed (Nuxt's de-dup: `base/BaseButton.vue` → `BaseButton`, not
  92. * `BaseBaseButton`). Returns null for a flat component (`components/NavBar.vue`)
  93. * — its node is already named by basename, so a direct tag match finds it.
  94. */
  95. function nuxtComponentName(filePath: string): string | null {
  96. const marker = filePath.lastIndexOf('components/');
  97. if (marker === -1) return null;
  98. const rel = filePath.slice(marker + 'components/'.length).replace(/\.(vue|ts|tsx|js|jsx)$/i, '');
  99. const segs = rel.split('/').filter(Boolean).map(kebabToPascal);
  100. if (segs.length < 2) return null;
  101. const out: string[] = [];
  102. for (const s of segs) {
  103. const prev = out[out.length - 1];
  104. if (prev && s.startsWith(prev)) out[out.length - 1] = s;
  105. else out.push(s);
  106. }
  107. return out.join('');
  108. }
  109. function sliceLines(content: string, startLine?: number, endLine?: number): string | null {
  110. if (!startLine || !endLine) return null;
  111. return content.split('\n').slice(startLine - 1, endLine).join('\n');
  112. }
  113. function registrarField(src: string): string | null {
  114. const m = src.match(/this\.(\w+)\.(?:add|push|set)\(/);
  115. return m ? m[1]! : null;
  116. }
  117. function dispatcherField(src: string): string | null {
  118. const forOf = src.match(/\bof\s+(?:Array\.from\(\s*)?this\.(\w+)/);
  119. if (forOf && /\b\w+\s*\(/.test(src)) return forOf[1]!;
  120. const forEach = src.match(/this\.(\w+)\.forEach\(/);
  121. if (forEach) return forEach[1]!;
  122. return null;
  123. }
  124. /**
  125. * Stream method + function nodes lazily. The synthesizers only scan-and-filter
  126. * down to a tiny matched subset, so materializing every function/method (which
  127. * is gigabytes on a symbol-dense project) just to iterate it once is what OOM'd
  128. * #610. Iterating keeps memory O(1) in the node count.
  129. */
  130. function* methodAndFunctionNodes(queries: QueryBuilder): IterableIterator<Node> {
  131. yield* queries.iterateNodesByKind('method');
  132. yield* queries.iterateNodesByKind('function');
  133. }
  134. /** Phase 1: field-backed observer channels (registrar/dispatcher share a store). */
  135. async function fieldChannelEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  136. const registrars: Array<{ node: Node; field: string }> = [];
  137. const dispatchers: Array<{ node: Node; field: string }> = [];
  138. let scanned = 0;
  139. for (const m of methodAndFunctionNodes(queries)) {
  140. if ((++scanned & 255) === 0) await onYield(); // #1091: yield mid-scan on huge graphs
  141. const isReg = REGISTRAR_NAME.test(m.name);
  142. const isDisp = DISPATCHER_NAME.test(m.name);
  143. if (!isReg && !isDisp) continue;
  144. const content = ctx.readFile(m.filePath);
  145. const src = content && sliceLines(content, m.startLine, m.endLine);
  146. if (!src) continue;
  147. if (isReg) { const f = registrarField(src); if (f) registrars.push({ node: m, field: f }); }
  148. if (isDisp) { const f = dispatcherField(src); if (f) dispatchers.push({ node: m, field: f }); }
  149. }
  150. const edges: Edge[] = [];
  151. const seen = new Set<string>();
  152. for (const reg of registrars) {
  153. const chDispatchers = dispatchers.filter(
  154. (d) => d.node.filePath === reg.node.filePath && d.field === reg.field
  155. );
  156. if (chDispatchers.length === 0) continue;
  157. const argRe = new RegExp(`${reg.node.name}\\s*\\(\\s*(?:this\\.)?(\\w+)`);
  158. let added = 0;
  159. for (const e of queries.getIncomingEdges(reg.node.id, ['calls'])) {
  160. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  161. if (!e.line) continue;
  162. const caller = queries.getNodeById(e.source);
  163. if (!caller) continue;
  164. const line = ctx.readFile(caller.filePath)?.split('\n')[e.line - 1];
  165. const am = line?.match(argRe);
  166. if (!am) continue;
  167. const fn = ctx.getNodesByName(am[1]!).find((n) => n.kind === 'method' || n.kind === 'function');
  168. if (!fn) continue;
  169. for (const disp of chDispatchers) {
  170. if (disp.node.id === fn.id) continue;
  171. const key = `${disp.node.id}>${fn.id}`;
  172. if (seen.has(key)) continue;
  173. seen.add(key);
  174. edges.push({
  175. source: disp.node.id, target: fn.id, kind: 'calls', line: disp.node.startLine,
  176. provenance: 'heuristic',
  177. metadata: {
  178. synthesizedBy: 'callback', via: reg.node.name, field: reg.field,
  179. // Where the callback was wired up (`scene.onUpdate(this.triggerRender)`).
  180. // This is the #1 thing an agent reads/greps to explain the flow — surface
  181. // it so node/trace/context can show it without a callers() + Read round-trip.
  182. registeredAt: `${caller.filePath}:${e.line}`,
  183. },
  184. });
  185. added++;
  186. }
  187. }
  188. }
  189. return edges;
  190. }
  191. /**
  192. * Closure-collection dispatch: dispatcher iterates a closure-collection property
  193. * invoking each element; registrar appends a closure to the same-named property.
  194. * Emits dispatcher → registrar so a flow reaches the registration site (where the
  195. * appended closure's body — and its callers — live). High-precision: the
  196. * dispatcher's element-invoke is the gate (a `.forEach` that does NOT invoke its
  197. * element is ignored), so a repo with no closure-collection dispatch yields zero
  198. * edges regardless of how many `.append`/`.push` sites it has.
  199. *
  200. * Pairs globally by field name (cross-file/class is required — see Alamofire's
  201. * base-class `Request.didCompleteTask` iterating `validators` appended by the
  202. * subclass `DataRequest.validate`), bounded by a fan-out cap so a generic field
  203. * name shared across unrelated classes can't fan out into noise.
  204. */
  205. async function closureCollectionEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  206. const dispatchers = new Map<string, Array<{ node: Node; line: number }>>(); // field → dispatcher methods + forEach line
  207. const registrars = new Map<string, Array<{ node: Node; line: number }>>(); // field → registrar methods + append line
  208. const addReg = (field: string | undefined, node: Node, absLine: number) => {
  209. if (!field || /^\d+$/.test(field)) return; // `$0.append` mis-captures the `0`; the write-RE owns that field
  210. const arr = registrars.get(field) ?? [];
  211. if (!arr.some((r) => r.node.id === node.id)) arr.push({ node, line: absLine });
  212. registrars.set(field, arr);
  213. };
  214. // Slices EVERY Swift/Kotlin method/function's source (no cheap name-gate), so
  215. // on a repo with a huge file this is the heaviest synthesis pass — yield
  216. // mid-scan (and mid-match-loop below: a single generated function dense with
  217. // matches must not starve the watchdog either) so it can't wedge the #850
  218. // watchdog on its own (#1091, #1235).
  219. let scanned = 0;
  220. let matchTick = 0;
  221. for (const m of methodAndFunctionNodes(queries)) {
  222. if ((++scanned & 127) === 0) await onYield();
  223. if (!CC_LANGUAGES.has(m.language)) continue;
  224. const content = ctx.readFile(m.filePath);
  225. const src = content && sliceLines(content, m.startLine, m.endLine);
  226. if (!src) continue;
  227. const hasForEach = src.includes('.forEach');
  228. const hasAppend = src.includes('.append(') || src.includes('.add(') || src.includes('.push(') || src.includes('.insert(');
  229. if (!hasForEach && !hasAppend) continue;
  230. const lineAt = makeLineAt(src, m.startLine ?? 1);
  231. if (hasForEach) {
  232. CC_DISPATCH_RE.lastIndex = 0;
  233. let d: RegExpExecArray | null;
  234. while ((d = CC_DISPATCH_RE.exec(src))) {
  235. if ((++matchTick & 255) === 0) await onYield();
  236. const arr = dispatchers.get(d[1]!) ?? [];
  237. if (!arr.some((n) => n.node.id === m.id)) arr.push({ node: m, line: lineAt(d.index) });
  238. dispatchers.set(d[1]!, arr);
  239. }
  240. }
  241. if (hasAppend) {
  242. CC_APPEND_WRITE_RE.lastIndex = 0;
  243. let w: RegExpExecArray | null;
  244. while ((w = CC_APPEND_WRITE_RE.exec(src))) {
  245. if ((++matchTick & 255) === 0) await onYield();
  246. addReg(w[2] || w[1], m, lineAt(w.index)); // nested `$0.streams` else the `.write` receiver
  247. }
  248. CC_APPEND_DIRECT_RE.lastIndex = 0;
  249. let a: RegExpExecArray | null;
  250. while ((a = CC_APPEND_DIRECT_RE.exec(src))) {
  251. if ((++matchTick & 255) === 0) await onYield();
  252. addReg(a[1], m, lineAt(a.index));
  253. }
  254. }
  255. }
  256. const edges: Edge[] = [];
  257. const seen = new Set<string>();
  258. for (const [field, disps] of dispatchers) {
  259. const regs = registrars.get(field);
  260. if (!regs || regs.length === 0) continue;
  261. if (disps.length > CC_FANOUT_CAP || regs.length > CC_FANOUT_CAP) continue; // generic field — can't pair confidently
  262. for (const disp of disps) for (const reg of regs) {
  263. if (disp.node.id === reg.node.id) continue;
  264. const key = `${disp.node.id}>${reg.node.id}`;
  265. if (seen.has(key)) continue;
  266. seen.add(key);
  267. edges.push({
  268. source: disp.node.id, target: reg.node.id, kind: 'calls', line: disp.line,
  269. provenance: 'heuristic',
  270. metadata: { synthesizedBy: 'closure-collection', field, registeredAt: `${reg.node.filePath}:${reg.line}` },
  271. });
  272. }
  273. }
  274. return edges;
  275. }
  276. /** Phase 2: string-keyed EventEmitter channels (on('e', fn) ↔ emit('e')). */
  277. async function eventEmitterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  278. let scannedFiles = 0;
  279. const emitsByEvent = new Map<string, Set<string>>(); // event → dispatcher node ids
  280. const handlersByEvent = new Map<string, Map<string, string>>(); // event → handler id → registration site (file:line)
  281. let scanned = 0;
  282. for (const file of ctx.getAllFiles()) {
  283. if ((++scannedFiles & 15) === 0) await onYield();
  284. if ((++scanned & 255) === 0) await onYield(); // #1091: yield mid-scan on huge graphs
  285. const content = ctx.readFile(file);
  286. if (!content) continue;
  287. const hasEmit = content.includes('.emit(') || content.includes('.fire(') || content.includes('.dispatchEvent(');
  288. const hasOn = content.includes('.on(') || content.includes('.once(') || content.includes('.addListener(');
  289. if (!hasEmit && !hasOn) continue;
  290. const nodesInFile = ctx.getNodesInFile(file);
  291. const lineOf = makeLineAt(content, 1);
  292. if (hasEmit) {
  293. EMIT_RE.lastIndex = 0;
  294. let m: RegExpExecArray | null;
  295. while ((m = EMIT_RE.exec(content))) {
  296. const disp = enclosingFn(nodesInFile, lineOf(m.index));
  297. if (!disp) continue;
  298. const set = emitsByEvent.get(m[1]!) ?? new Set<string>();
  299. set.add(disp.id); emitsByEvent.set(m[1]!, set);
  300. }
  301. }
  302. if (hasOn) {
  303. ON_RE.lastIndex = 0;
  304. let m: RegExpExecArray | null;
  305. while ((m = ON_RE.exec(content))) {
  306. const handlerName = m[2] || m[3];
  307. if (!handlerName) continue;
  308. const handler = ctx.getNodesByName(handlerName).find((n) => n.kind === 'function' || n.kind === 'method');
  309. if (!handler) continue;
  310. const map = handlersByEvent.get(m[1]!) ?? new Map<string, string>();
  311. map.set(handler.id, `${file}:${lineOf(m.index)}`); handlersByEvent.set(m[1]!, map);
  312. }
  313. }
  314. }
  315. const edges: Edge[] = [];
  316. const seen = new Set<string>();
  317. for (const [event, dispatchers] of emitsByEvent) {
  318. const handlers = handlersByEvent.get(event);
  319. if (!handlers) continue;
  320. // Precision guard: a generic event name with many handlers/dispatchers can't
  321. // be matched without receiver-type info (Phase 3) — skip rather than over-link.
  322. if (dispatchers.size > EVENT_FANOUT_CAP || handlers.size > EVENT_FANOUT_CAP) continue;
  323. for (const d of dispatchers) for (const [h, registeredAt] of handlers) {
  324. if (d === h) continue;
  325. const key = `${d}>${h}`;
  326. if (seen.has(key)) continue;
  327. seen.add(key);
  328. edges.push({ source: d, target: h, kind: 'calls', provenance: 'heuristic', metadata: { synthesizedBy: 'event-emitter', event, registeredAt } });
  329. }
  330. }
  331. return edges;
  332. }
  333. /**
  334. * Phase 4: React class-component re-render. `this.setState(...)` re-runs the
  335. * component's `render()`, but that hop is React-internal — no static edge — so a
  336. * flow like "mutation → setState → canvas repaint" dead-ends at setState even
  337. * though `render → getRenderableElements → …` is fully call-connected after it.
  338. * Bridge it: for each class that has a `render` method, link every sibling method
  339. * whose body calls `this.setState(` → `render`. The setState gate keeps this to
  340. * React class components (a non-React class with a `render` method won't call
  341. * `this.setState`). Over-approximation (all setState methods reach render) is
  342. * accepted — it's reachability-correct, like the callback channels.
  343. */
  344. async function reactRenderEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  345. let scanned255 = 0;
  346. const edges: Edge[] = [];
  347. const seen = new Set<string>();
  348. // A class can only emit here if it CONTAINS a method named `render` — so one
  349. // indexed name lookup bounds the candidate set up front, and the class scan
  350. // below skips everything else before its per-class edge/node queries. On a
  351. // repo with few/no render methods (any non-React codebase) this collapses
  352. // the pass from every-class fan-out to ~zero DB work, with identical output:
  353. // the skipped classes fail the same `render` check today, just after paying
  354. // for their children. (Not a language gate: `render` + `this.setState(` in
  355. // Java — e.g. Litho — legitimately matches today and still does.)
  356. const renderOwners = new Set<string>();
  357. for (const n of ctx.getNodesByName('render')) {
  358. if (n.kind !== 'method') continue;
  359. for (const e of queries.getIncomingEdges(n.id, ['contains'])) renderOwners.add(e.source);
  360. }
  361. if (renderOwners.size === 0) return edges;
  362. for (const cls of queries.iterateNodesByKind('class')) {
  363. if ((++scanned255 & 63) === 0) await onYield();
  364. if (!renderOwners.has(cls.id)) continue;
  365. const children = queries.getOutgoingEdges(cls.id, ['contains'])
  366. .map((e) => queries.getNodeById(e.target))
  367. .filter((n): n is Node => !!n && n.kind === 'method');
  368. const render = children.find((n) => n.name === 'render');
  369. if (!render) continue;
  370. let added = 0;
  371. for (const m of children) {
  372. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  373. if (m.id === render.id) continue;
  374. const content = ctx.readFile(m.filePath);
  375. const src = content && sliceLines(content, m.startLine, m.endLine);
  376. if (!src || !SETSTATE_RE.test(src)) continue;
  377. const key = `${m.id}>${render.id}`;
  378. if (seen.has(key)) continue;
  379. seen.add(key);
  380. edges.push({
  381. source: m.id, target: render.id, kind: 'calls', line: m.startLine,
  382. provenance: 'heuristic',
  383. metadata: { synthesizedBy: 'react-render', via: 'setState', registeredAt: `${render.filePath}:${render.startLine}` },
  384. });
  385. added++;
  386. }
  387. }
  388. return edges;
  389. }
  390. /**
  391. * Phase 4b: Flutter setState → build (the Dart analog of react-render). In a
  392. * StatefulWidget's State class, `setState(() {…})` re-runs `build(context)`, but
  393. * that hop is framework-internal (Flutter calls build), so a flow like
  394. * "onPressed → _increment → setState → rebuilt UI" dead-ends at setState. Bridge
  395. * it: for each Dart class with a `build` method, link every sibling method whose
  396. * body calls `setState(` → `build`. The setState gate + `.dart` file keep this to
  397. * Flutter State classes. Over-approximation accepted (reachability-correct).
  398. */
  399. async function flutterBuildEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  400. let scanned255 = 0;
  401. const edges: Edge[] = [];
  402. const seen = new Set<string>();
  403. for (const cls of queries.iterateNodesByKind('class')) {
  404. if ((++scanned255 & 63) === 0) await onYield();
  405. const children = queries.getOutgoingEdges(cls.id, ['contains'])
  406. .map((e) => queries.getNodeById(e.target))
  407. .filter((n): n is Node => !!n && n.kind === 'method');
  408. const build = children.find((n) => n.name === 'build');
  409. if (!build || !build.filePath.endsWith('.dart')) continue;
  410. let added = 0;
  411. for (const m of children) {
  412. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  413. if (m.id === build.id) continue;
  414. const content = ctx.readFile(m.filePath);
  415. const src = content && sliceLines(content, m.startLine, m.endLine);
  416. if (!src || !FLUTTER_SETSTATE_RE.test(src)) continue;
  417. const key = `${m.id}>${build.id}`;
  418. if (seen.has(key)) continue;
  419. seen.add(key);
  420. edges.push({
  421. source: m.id, target: build.id, kind: 'calls', line: m.startLine,
  422. provenance: 'heuristic',
  423. metadata: { synthesizedBy: 'flutter-build', via: 'setState', registeredAt: `${build.filePath}:${build.startLine}` },
  424. });
  425. added++;
  426. }
  427. }
  428. return edges;
  429. }
  430. /**
  431. * Reactive ArkUI property decorators: assigning a property carrying one of
  432. * these re-runs the owning struct's `build()`. Covers both state models —
  433. * V1 (`@Component`: State/Prop/Link/Provide/Consume/Storage*) and V2
  434. * (`@ComponentV2`: Local/Provider/Consumer; `@Param` is read-only in V2 so
  435. * the assignment gate never fires on it, and `@Trace` lives on `@ObservedV2`
  436. * data classes, not struct properties).
  437. */
  438. const ARKUI_REACTIVE_DECORATORS = new Set([
  439. 'State', 'Prop', 'Link', 'Provide', 'Consume', 'StorageLink', 'StorageProp',
  440. 'LocalStorageLink', 'LocalStorageProp', 'ObjectLink',
  441. 'Local', 'Provider', 'Consumer',
  442. ]);
  443. /** ArkUI-observed array mutators — `this.todos.push(x)` re-renders like an assignment. */
  444. const ARKUI_ARRAY_MUTATORS = 'push|pop|shift|unshift|splice|sort|reverse|fill';
  445. /**
  446. * Phase 4b-ets: ArkUI state → build (the ArkTS analog of react-render /
  447. * flutter-build). Assigning a reactive-decorated property (`@State count`,
  448. * `@Link selected`, …) re-runs the `@Component struct`'s `build()`, but that
  449. * hop is framework-internal — no static edge — so "onClick → markAllDone →
  450. * this.todos = […] → rebuilt list" dead-ends at the assignment. Bridge it:
  451. * for each arkts struct with a `build()` method and at least one reactive
  452. * property, link every sibling method whose body ASSIGNS (or array-mutates)
  453. * one of those properties → `build`. Assignment-gated on the struct's OWN
  454. * reactive property names — a method that merely reads state, or a struct
  455. * with no reactive properties, gets nothing (this is the precision line the
  456. * all-sibling-methods design would erase).
  457. */
  458. async function arkuiStateBuildEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  459. let scanned255 = 0;
  460. const edges: Edge[] = [];
  461. const seen = new Set<string>();
  462. for (const struct of queries.iterateNodesByKind('struct')) {
  463. if ((++scanned255 & 63) === 0) await onYield();
  464. if (struct.language !== 'arkts') continue;
  465. const children = queries.getOutgoingEdges(struct.id, ['contains'])
  466. .map((e) => queries.getNodeById(e.target))
  467. .filter((n): n is Node => !!n);
  468. const build = children.find((n) => n.kind === 'method' && n.name === 'build');
  469. if (!build) continue;
  470. const reactiveProps = children.filter(
  471. (n) => n.kind === 'property' && (n.decorators ?? []).some((d) => ARKUI_REACTIVE_DECORATORS.has(d))
  472. );
  473. if (reactiveProps.length === 0) continue;
  474. const propAlternation = reactiveProps
  475. .map((p) => p.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  476. .join('|');
  477. // `this.count = …` / `+=` / `++` / `--` / `this.todos.push(…)`. The
  478. // `=(?!=)` keeps `this.done == x` comparisons out.
  479. const mutationRe = new RegExp(
  480. `this\\.(?:${propAlternation})\\s*(?:=(?!=)|\\+\\+|--|[+\\-*/%&|^]=|\\.(?:${ARKUI_ARRAY_MUTATORS})\\s*\\()`
  481. );
  482. let added = 0;
  483. for (const m of children) {
  484. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  485. if (m.kind !== 'method' || m.id === build.id) continue;
  486. const content = ctx.readFile(m.filePath);
  487. const src = content && sliceLines(content, m.startLine, m.endLine);
  488. if (!src || !mutationRe.test(stripCommentsForRegex(src, 'typescript'))) continue;
  489. const key = `${m.id}>${build.id}`;
  490. if (seen.has(key)) continue;
  491. seen.add(key);
  492. edges.push({
  493. source: m.id, target: build.id, kind: 'calls', line: m.startLine,
  494. provenance: 'heuristic',
  495. metadata: { synthesizedBy: 'arkui-state', via: 'state assignment', registeredAt: `${build.filePath}:${build.startLine}` },
  496. });
  497. added++;
  498. }
  499. }
  500. return edges;
  501. }
  502. /** Emit/subscribe call sites of HarmonyOS's `@ohos.events.emitter` bus. */
  503. const ARKUI_EMITTER_CALL_RE = /\bemitter\s*\.\s*(emit|on|once)\s*\(\s*([A-Za-z_$][\w$.]*|\{[^)]{0,120}?\beventId\s*:\s*[^,}]+[^)]*?\})/g;
  504. /** Cap per event bucket — a generic key with many parties is dynamic routing, not a static pair. */
  505. const ARKUI_EMITTER_FANOUT_CAP = 8;
  506. /**
  507. * Phase 4b-ets2: HarmonyOS `@ohos.events.emitter` bridge. The cross-component
  508. * bus — `emitter.emit(eventId)` fires `emitter.on(eventId, cb)` — is
  509. * framework-internal, so an order flow riding it (OrangeShopping's
  510. * add-to-cart) dead-ends at the emit. Link emit-site enclosing
  511. * function/method → on/once-site enclosing function/method when both
  512. * reference the SAME statically-recoverable event key.
  513. *
  514. * Key recovery, per call site (comment-stripped enclosing-file source): the
  515. * first argument is an `{ eventId: K }` literal, a `Names.Dotted` constant, or
  516. * a local whose same-file declaration is `new EventsId(K)` / `= K` — chase one
  517. * level. Precision scoping learned from the samples monorepo (thousands of
  518. * unrelated samples, most using eventId 1): NUMERIC keys pair within the same
  519. * FILE only; NAMED keys pair within the same workspace module directory (or
  520. * the whole project when it declares no modules — the single-app case), both
  521. * behind a fan-out cap. Inline `on(id, (e) => {…})` arrows need no special
  522. * handling — their bodies' calls already attribute to the registering method,
  523. * so targeting that method keeps the chain connected.
  524. */
  525. async function arkuiEmitterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  526. let scannedFiles = 0;
  527. interface Site { nodeId: string; file: string; line: number }
  528. // bucket key -> emit sites / handler sites
  529. const emits = new Map<string, Site[]>();
  530. const handlers = new Map<string, Site[]>();
  531. const moduleDirs = (() => {
  532. const ws = ctx.getWorkspacePackages?.();
  533. return ws ? [...new Set(ws.byName.values())].sort((a, b) => b.length - a.length) : [];
  534. })();
  535. const moduleScopeOf = (file: string): string => {
  536. for (const dir of moduleDirs) {
  537. if (file === dir || file.startsWith(dir + '/')) return dir;
  538. }
  539. return '';
  540. };
  541. for (const file of ctx.getAllFiles()) {
  542. if ((++scannedFiles & 15) === 0) await onYield();
  543. if (!file.endsWith('.ets')) continue;
  544. const content = ctx.readFile(file);
  545. if (!content || !content.includes('emitter.')) continue;
  546. const safe = stripCommentsForRegex(content, 'typescript');
  547. const nodes = ctx.getNodesInFile(file)
  548. .filter((n) => n.kind === 'method' || n.kind === 'function');
  549. ARKUI_EMITTER_CALL_RE.lastIndex = 0;
  550. let m: RegExpExecArray | null;
  551. while ((m = ARKUI_EMITTER_CALL_RE.exec(safe))) {
  552. const verb = m[1]!;
  553. const arg = m[2]!.trim();
  554. const line = safe.slice(0, m.index).split('\n').length;
  555. const encl = nodes
  556. .filter((n) => n.startLine <= line && n.endLine >= line)
  557. .sort((a, b) => (a.endLine - a.startLine) - (b.endLine - b.startLine))[0];
  558. if (!encl) continue;
  559. // Recover the event key from the first argument.
  560. let key: string | null = null;
  561. const idLit = arg.startsWith('{') ? arg.match(/\beventId\s*:\s*([\w$.]+)/)?.[1] : undefined;
  562. const token = idLit ?? arg;
  563. if (token !== undefined) {
  564. if (/^\d+$/.test(token)) {
  565. key = `num:${file}:${token}`; // numeric: same-file only
  566. } else if (token.includes('.')) {
  567. key = `name:${moduleScopeOf(file)}:${token}`;
  568. } else {
  569. // Local variable — chase its same-file declaration one level:
  570. // `let x = new EventsId(K)` / `const x = K`.
  571. const declRe = new RegExp(
  572. `\\b${token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b\\s*(?::[^=\\n]+)?=\\s*(?:new\\s+[\\w$.]+\\(\\s*([^)\\n]+?)\\s*\\)|([\\w$.]+))`
  573. );
  574. const decl = safe.match(declRe);
  575. const inner = (decl?.[1] ?? decl?.[2])?.trim();
  576. if (inner && /^\d+$/.test(inner)) key = `num:${file}:${inner}`;
  577. else if (inner && /^[\w$.]+$/.test(inner)) key = `name:${moduleScopeOf(file)}:${inner}`;
  578. }
  579. }
  580. if (!key) continue;
  581. const site: Site = { nodeId: encl.id, file, line };
  582. if (verb === 'emit') {
  583. (emits.get(key) ?? emits.set(key, []).get(key)!).push(site);
  584. } else {
  585. (handlers.get(key) ?? handlers.set(key, []).get(key)!).push(site);
  586. }
  587. }
  588. }
  589. const edges: Edge[] = [];
  590. const seen = new Set<string>();
  591. for (const [key, emitSites] of emits) {
  592. const handlerSites = handlers.get(key);
  593. if (!handlerSites) continue;
  594. if (emitSites.length > ARKUI_EMITTER_FANOUT_CAP || handlerSites.length > ARKUI_EMITTER_FANOUT_CAP) continue;
  595. const eventLabel = key.slice(key.lastIndexOf(':') + 1);
  596. for (const e of emitSites) for (const h of handlerSites) {
  597. if (e.nodeId === h.nodeId) continue;
  598. const dedupe = `${e.nodeId}>${h.nodeId}`;
  599. if (seen.has(dedupe)) continue;
  600. seen.add(dedupe);
  601. edges.push({
  602. source: e.nodeId, target: h.nodeId, kind: 'calls', line: e.line,
  603. provenance: 'heuristic',
  604. metadata: { synthesizedBy: 'arkui-emitter', event: eventLabel, registeredAt: `${h.file}:${h.line}` },
  605. });
  606. }
  607. }
  608. return edges;
  609. }
  610. /** `router.pushUrl({ url: 'pages/Detail' })` / replaceUrl — literal urls only. */
  611. const ARKUI_ROUTER_RE = /\brouter\s*\.\s*(?:pushUrl|replaceUrl)\s*\(\s*\{[^)]{0,200}?\burl\s*:\s*['"]([\w\-./]+)['"]/g;
  612. /**
  613. * Phase 4b-ets3: HarmonyOS page navigation. `router.pushUrl({ url:
  614. * 'pages/Detail' })` reaches the `@Entry struct` of
  615. * `<module>/src/main/ets/pages/Detail.ets`, but the hop is a string — no
  616. * static edge — so "tap → openDetail → ???" ends at the router call. Bridge
  617. * literal urls to the page struct: the url resolves against the standard
  618. * `src/main/ets/` layout (what main_pages.json entries name); candidates
  619. * prefer the caller's own workspace module (routes are module-scoped), and
  620. * anything still ambiguous is dropped rather than guessed. Only `@Entry`
  621. * structs qualify as targets — the decorator is what makes a file a page.
  622. */
  623. async function arkuiRouterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  624. const edges: Edge[] = [];
  625. const seen = new Set<string>();
  626. const allFiles = ctx.getAllFiles();
  627. const moduleDirs = (() => {
  628. const ws = ctx.getWorkspacePackages?.();
  629. return ws ? [...new Set(ws.byName.values())].sort((a, b) => b.length - a.length) : [];
  630. })();
  631. const moduleScopeOf = (file: string): string => {
  632. for (const dir of moduleDirs) {
  633. if (file === dir || file.startsWith(dir + '/')) return dir;
  634. }
  635. return '';
  636. };
  637. let scannedFiles = 0;
  638. for (const file of allFiles) {
  639. if ((++scannedFiles & 15) === 0) await onYield();
  640. if (!file.endsWith('.ets')) continue;
  641. const content = ctx.readFile(file);
  642. if (!content || !content.includes('router.')) continue;
  643. const safe = stripCommentsForRegex(content, 'typescript');
  644. const nodes = ctx.getNodesInFile(file)
  645. .filter((n) => n.kind === 'method' || n.kind === 'function');
  646. ARKUI_ROUTER_RE.lastIndex = 0;
  647. let m: RegExpExecArray | null;
  648. while ((m = ARKUI_ROUTER_RE.exec(safe))) {
  649. const url = m[1]!;
  650. const line = safe.slice(0, m.index).split('\n').length;
  651. const encl = nodes
  652. .filter((n) => n.startLine <= line && n.endLine >= line)
  653. .sort((a, b) => (a.endLine - a.startLine) - (b.endLine - b.startLine))[0];
  654. if (!encl) continue;
  655. const suffix = `/src/main/ets/${url}.ets`;
  656. let candidates = allFiles.filter((f) => f.endsWith(suffix));
  657. if (candidates.length > 1) {
  658. const scope = moduleScopeOf(file);
  659. const sameModule = candidates.filter((f) => moduleScopeOf(f) === scope);
  660. if (sameModule.length > 0) candidates = sameModule;
  661. }
  662. if (candidates.length !== 1) continue; // ambiguous or unresolved — never guess
  663. const page = ctx.getNodesInFile(candidates[0]!).find(
  664. (n) => n.kind === 'struct' && (n.decorators ?? []).includes('Entry')
  665. );
  666. if (!page) continue;
  667. const key = `${encl.id}>${page.id}`;
  668. if (seen.has(key)) continue;
  669. seen.add(key);
  670. edges.push({
  671. source: encl.id, target: page.id, kind: 'calls', line,
  672. provenance: 'heuristic',
  673. metadata: { synthesizedBy: 'arkui-route', event: url, registeredAt: `${candidates[0]}:${page.startLine}` },
  674. });
  675. }
  676. }
  677. return edges;
  678. }
  679. /**
  680. * Phase 4c: C++ virtual override. A call through a base/interface pointer
  681. * (`db->Get(...)`, `iter->Next()`) dispatches at runtime to a subclass override,
  682. * but that hop is a vtable indirection — no static call edge — so a flow stops at
  683. * the abstract base method. Bridge it like react-render: for each C++ class that
  684. * `extends` a base, link each base method → the subclass method of the same name
  685. * (the override), so trace/callees from the interface method reach the
  686. * implementation(s). Over-approximation accepted (reachability-correct); capped
  687. * per class and gated to C++ to avoid touching other languages' dispatch.
  688. */
  689. async function cppOverrideEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  690. let scanned255 = 0;
  691. const edges: Edge[] = [];
  692. const seen = new Set<string>();
  693. const methodsOf = (classId: string): Node[] =>
  694. queries
  695. .getOutgoingEdges(classId, ['contains'])
  696. .map((e) => queries.getNodeById(e.target))
  697. .filter((n): n is Node => !!n && n.kind === 'method');
  698. for (const cls of queries.iterateNodesByKind('class')) {
  699. if ((++scanned255 & 63) === 0) await onYield();
  700. const subMethods = methodsOf(cls.id).filter((n) => n.language === 'cpp');
  701. if (subMethods.length === 0) continue;
  702. for (const ext of queries.getOutgoingEdges(cls.id, ['extends'])) {
  703. const base = queries.getNodeById(ext.target);
  704. if (!base || base.language !== 'cpp' || base.id === cls.id) continue;
  705. const baseMethods = new Map(methodsOf(base.id).map((m) => [m.name, m]));
  706. let added = 0;
  707. for (const m of subMethods) {
  708. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  709. const bm = baseMethods.get(m.name);
  710. if (!bm || bm.id === m.id) continue;
  711. const key = `${bm.id}>${m.id}`;
  712. if (seen.has(key)) continue;
  713. seen.add(key);
  714. edges.push({
  715. source: bm.id,
  716. target: m.id,
  717. kind: 'calls',
  718. line: bm.startLine,
  719. provenance: 'heuristic',
  720. metadata: { synthesizedBy: 'cpp-override', via: m.name, registeredAt: `${m.filePath}:${m.startLine}` },
  721. });
  722. added++;
  723. }
  724. }
  725. }
  726. return edges;
  727. }
  728. /**
  729. * Phase 5.5: interface / abstract dispatch (Java, Kotlin). A call through an
  730. * injected interface (`@Autowired FooService svc; svc.list()`) or an abstract
  731. * base dispatches at runtime to the implementing class's override — a vtable
  732. * indirection with no static call edge — so a request→service flow stops at the
  733. * interface method. Bridge it like cpp-override: for each class that
  734. * `implements` an interface (or `extends` an abstract base), link each
  735. * base/interface method → the class's same-name method (the override) so
  736. * trace/callees reach the implementation. Over-approximation accepted
  737. * (reachability-correct); capped per class, gated to JVM languages.
  738. */
  739. // Languages whose static `implements`/`extends` edges should bridge an
  740. // interface (or abstract base) method to the matching concrete-class method.
  741. // The set is "languages with explicit nominal subtyping and a single class
  742. // kind that holds methods" — i.e. the shape this loop expects. Swift and
  743. // Scala fit shape-wise (Swift `protocol`/`class`, Scala `trait`/`class`)
  744. // and are added below; their concrete-side nodes can be a `struct` (Swift)
  745. // or an `object` (Scala) so the loop also iterates those kinds.
  746. const IFACE_OVERRIDE_LANGS = new Set([
  747. 'java', 'kotlin', 'csharp', 'typescript', 'javascript', 'swift', 'scala', 'go', 'rust',
  748. 'arkts',
  749. ]);
  750. /**
  751. * Go implicit interface satisfaction (#584). Go has no `implements` keyword — a
  752. * struct satisfies an interface structurally when its method set covers the
  753. * interface's. Synthesize the missing `implements` edge (struct → interface) by
  754. * matching method-NAME sets, so impl-navigation works and the interface-dispatch
  755. * bridge ({@link interfaceOverrideEdges}, now 'go'-enabled) can link an interface
  756. * method call to the concrete overrides.
  757. *
  758. * Name-only matching (signatures ignored) — over-approximation accepted, in line
  759. * with the other dispatch synthesizers; capped per interface. Empty interfaces
  760. * (`any`) are skipped so they don't match every struct.
  761. */
  762. async function goImplementsEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  763. let scanned255 = 0;
  764. const edges: Edge[] = [];
  765. const seen = new Set<string>();
  766. const methodNameSet = (id: string): Set<string> =>
  767. new Set(
  768. queries
  769. .getOutgoingEdges(id, ['contains'])
  770. .map((e) => queries.getNodeById(e.target))
  771. .filter((n): n is Node => !!n && n.kind === 'method')
  772. .map((n) => n.name),
  773. );
  774. // Materializes GO structs only (the pass is language-gated by the caller),
  775. // never the whole struct kind — that array is O(nodes) on struct-heavy
  776. // repos like the Linux kernel (#1212).
  777. const goStructs: Node[] = [];
  778. for (const s of queries.iterateNodesByKind('struct')) {
  779. if ((++scanned255 & 63) === 0) await onYield();
  780. if (s.language === 'go') goStructs.push(s);
  781. }
  782. const structMethods = new Map<string, Set<string>>();
  783. for (const s of goStructs) structMethods.set(s.id, methodNameSet(s.id));
  784. for (const iface of queries.iterateNodesByKind('interface')) {
  785. if ((++scanned255 & 63) === 0) await onYield();
  786. if ((++scanned255 & 63) === 0) await onYield();
  787. if (iface.language !== 'go') continue;
  788. const want = methodNameSet(iface.id);
  789. if (want.size === 0) continue; // empty interface (`any`) — would match everything
  790. let added = 0;
  791. for (const s of goStructs) {
  792. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  793. const have = structMethods.get(s.id);
  794. if (!have || have.size < want.size) continue;
  795. let all = true;
  796. for (const m of want) {
  797. if (!have.has(m)) { all = false; break; }
  798. }
  799. if (!all) continue;
  800. const key = `${s.id}>${iface.id}`;
  801. if (seen.has(key)) continue;
  802. seen.add(key);
  803. edges.push({
  804. source: s.id,
  805. target: iface.id,
  806. kind: 'implements',
  807. line: s.startLine,
  808. provenance: 'heuristic',
  809. metadata: { synthesizedBy: 'go-implements', via: iface.name, registeredAt: `${s.filePath}:${s.startLine}` },
  810. });
  811. added++;
  812. }
  813. }
  814. return edges;
  815. }
  816. /**
  817. * Cross-file Go method → receiver-type `contains` edges. In Go a type's methods
  818. * are commonly declared in a different file from the `type` declaration itself
  819. * (`type User struct{…}` in `user.go`, `func (u *User) Save()` in
  820. * `user_store.go`). Extraction attaches the struct→method `contains` edge only
  821. * when the receiver type is in the SAME file — the owner lookup in
  822. * `tree-sitter.ts` is scoped to the file being parsed — so a cross-file method
  823. * is left orphaned from its type (it's still `contains`ed by its file, just not
  824. * its struct). That breaks `codegraph_node` member outlines, any
  825. * callers/callees/impact traversal that goes through the type's `contains`
  826. * edges, and the {@link goImplementsEdges} method-set computation (which derives
  827. * a struct's method set from those same edges, so it under-counts interfaces a
  828. * cross-file struct satisfies).
  829. *
  830. * Go guarantees a method's receiver type is declared in the SAME PACKAGE as the
  831. * method, and a Go package is a single directory — so this is a deterministic
  832. * structural link, not a heuristic: find the same-named type in the method's own
  833. * directory and add the missing `contains` edge (no `provenance: 'heuristic'`,
  834. * matching the same-file edges extraction already emits). Skips methods that
  835. * already have a type parent (the same-file case). (#583, cross-file half)
  836. */
  837. async function goCrossFileMethodContainsEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  838. let scanned255 = 0;
  839. const edges: Edge[] = [];
  840. const seen = new Set<string>();
  841. const TYPE_KINDS = new Set<NodeKind>(['struct', 'class', 'interface', 'enum', 'type_alias']);
  842. const dirOf = (p: string): string => {
  843. const i = p.replace(/\\/g, '/').lastIndexOf('/');
  844. return i >= 0 ? p.slice(0, i) : '';
  845. };
  846. for (const method of queries.iterateNodesByKind('method')) {
  847. if ((++scanned255 & 63) === 0) await onYield();
  848. if ((++scanned255 & 63) === 0) await onYield();
  849. if (method.language !== 'go') continue;
  850. // The receiver type is encoded in the method's qualifiedName as `Recv::name`
  851. // (extraction sets `${receiverType}::${name}` for receiver methods).
  852. const qn = method.qualifiedName;
  853. if (!qn) continue;
  854. const sep = qn.lastIndexOf('::');
  855. if (sep <= 0) continue;
  856. const receiver = qn.slice(0, sep);
  857. if (!receiver) continue;
  858. // Already attached to its type (same-file case handled at extraction)?
  859. const hasTypeParent = queries
  860. .getIncomingEdges(method.id, ['contains'])
  861. .some((e) => {
  862. const src = queries.getNodeById(e.source);
  863. return src != null && TYPE_KINDS.has(src.kind);
  864. });
  865. if (hasTypeParent) continue;
  866. // Find the receiver type in the SAME directory (= same Go package). Go forbids
  867. // duplicate type names within a package, so a same-name same-dir match is
  868. // unambiguous; scoping to the directory avoids linking to a same-named type
  869. // in another package.
  870. const dir = dirOf(method.filePath);
  871. const owner = queries
  872. .getNodesByName(receiver)
  873. .find((n) => n.language === 'go' && TYPE_KINDS.has(n.kind) && dirOf(n.filePath) === dir);
  874. if (!owner) continue;
  875. const key = `${owner.id}>${method.id}`;
  876. if (seen.has(key)) continue;
  877. seen.add(key);
  878. edges.push({ source: owner.id, target: method.id, kind: 'contains', line: method.startLine });
  879. }
  880. return edges;
  881. }
  882. /**
  883. * Kotlin Multiplatform `expect`/`actual` linking. A `common` source set declares
  884. * `expect fun foo()` / `expect class Bar`; each platform source set (jvm, native,
  885. * js, …) provides an `actual` implementation with the IDENTICAL fully-qualified
  886. * name in a different file. Callers in common code resolve to the `expect`
  887. * declaration, so every `actual` impl ends up with zero dependents — invisible to
  888. * impact/affected even though editing it can break every caller of the API.
  889. *
  890. * Synthesize a `calls` edge from the common declaration to each platform `actual`
  891. * (mirroring the interface-impl bridge: abstract → concrete), so editing a
  892. * platform impl surfaces the common `expect` and its callers, and the impl file
  893. * participates in the graph.
  894. *
  895. * `expect`/`actual` are captured onto the node's `decorators` list at extraction
  896. * (kotlin.ts `extractModifiers`). Members of an `expect class` are NOT themselves
  897. * keyword-marked, so the declaration side is matched as the same-FQN, same-kind
  898. * node that is NOT marked `actual`. Requiring an `actual`-marked counterpart also
  899. * gates out plain cross-file overloads (neither side is marked).
  900. */
  901. // Kinds that an `expect`/`actual` pair may legitimately straddle. `expect class`
  902. // is routinely fulfilled by an `actual typealias` (e.g. `actual typealias
  903. // CancellationException = …`, `actual typealias SchedulerTask = Task`), so a
  904. // strict kind match would miss those one-line alias files. Same-FQN + the
  905. // `actual` marker already gates out unrelated symbols, so widening to the
  906. // type-like kinds is safe.
  907. const KMP_TYPE_KINDS = new Set(['class', 'interface', 'struct', 'enum', 'type_alias']);
  908. function kmpKindsCompatible(a: string, b: string): boolean {
  909. return a === b || (KMP_TYPE_KINDS.has(a) && KMP_TYPE_KINDS.has(b));
  910. }
  911. async function kotlinExpectActualEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  912. let scanned255 = 0;
  913. const edges: Edge[] = [];
  914. const seen = new Set<string>();
  915. // SQL-side language+decorator pre-filter, streamed. The old
  916. // `getAllNodes().filter(...)` hydrated the ENTIRE node table into one array
  917. // just to find kotlin `actual` declarations — on a 2M-node graph that alone
  918. // exceeded Node's default heap and killed the index (#1212). The LIKE
  919. // pre-filter can over-match (substring), so the exact decorator check stays.
  920. for (const act of queries.iterateNodesByLanguageWithDecorator('kotlin', 'actual')) {
  921. if ((++scanned255 & 63) === 0) await onYield();
  922. if (!act.decorators?.includes('actual')) continue;
  923. let added = 0;
  924. for (const cand of queries.getNodesByQualifiedNameExact(act.qualifiedName)) {
  925. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  926. // The declaration side: same FQN + compatible kind, a different file, NOT
  927. // itself an `actual` (that would be a sibling platform impl, not the decl).
  928. if (cand.language !== 'kotlin' || cand.id === act.id) continue;
  929. if (!kmpKindsCompatible(cand.kind, act.kind) || cand.filePath === act.filePath) continue;
  930. if (cand.decorators?.includes('actual')) continue;
  931. const key = `${cand.id}>${act.id}`;
  932. if (seen.has(key)) continue;
  933. seen.add(key);
  934. edges.push({
  935. source: cand.id,
  936. target: act.id,
  937. kind: 'calls',
  938. line: cand.startLine,
  939. provenance: 'heuristic',
  940. metadata: {
  941. synthesizedBy: 'kotlin-expect-actual',
  942. via: act.name,
  943. registeredAt: `${act.filePath}:${act.startLine}`,
  944. },
  945. });
  946. added++;
  947. }
  948. }
  949. return edges;
  950. }
  951. async function interfaceOverrideEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  952. let scanned255 = 0;
  953. const edges: Edge[] = [];
  954. const seen = new Set<string>();
  955. // Memoized: a popular base interface's method list is otherwise re-fetched
  956. // once per implementer (dubbo-style hub interfaces have hundreds), and the
  957. // memo only ever serves reads. Same rows, same order — byte-identical.
  958. const methodsMemo = new Map<string, Node[]>();
  959. const methodsOf = (classId: string): Node[] => {
  960. const hit = methodsMemo.get(classId);
  961. if (hit) return hit;
  962. const methods = queries
  963. .getOutgoingEdges(classId, ['contains'])
  964. .map((e) => queries.getNodeById(e.target))
  965. .filter((n): n is Node => !!n && n.kind === 'method');
  966. methodsMemo.set(classId, methods);
  967. return methods;
  968. };
  969. // Concrete-side kinds vary by language: `class` covers Java / Kotlin /
  970. // C# / TS / Swift-classes / Scala-classes; `struct` covers Swift value
  971. // types that conform to protocols. Iterate both.
  972. const concreteKinds = ['class', 'struct', 'union'] as const;
  973. for (const kind of concreteKinds) {
  974. for (const cls of queries.iterateNodesByKind(kind)) {
  975. if ((++scanned255 & 63) === 0) await onYield();
  976. // A class can only emit here if it HAS a supertype edge — check that
  977. // (one edge query) before materializing its methods: most classes in a
  978. // typical graph extend/implement nothing and skip in one hop.
  979. const sups = queries.getOutgoingEdges(cls.id, ['implements', 'extends']);
  980. if (sups.length === 0) continue;
  981. const implMethods = methodsOf(cls.id).filter((n) => IFACE_OVERRIDE_LANGS.has(n.language));
  982. if (implMethods.length === 0) continue;
  983. for (const sup of sups) {
  984. const base = queries.getNodeById(sup.target);
  985. if (!base || !IFACE_OVERRIDE_LANGS.has(base.language) || base.id === cls.id) continue;
  986. // Group impl methods by name to handle OVERLOADS: an interface `list()` and
  987. // `list(params)` are distinct nodes and a call may resolve to either, so
  988. // link every base overload → every same-name impl overload (keying by name
  989. // alone would drop all but one and miss the resolved overload).
  990. const implByName = new Map<string, Node[]>();
  991. for (const m of implMethods) {
  992. const arr = implByName.get(m.name);
  993. if (arr) arr.push(m); else implByName.set(m.name, [m]);
  994. }
  995. let added = 0;
  996. for (const bm of methodsOf(base.id)) {
  997. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  998. for (const m of implByName.get(bm.name) ?? []) {
  999. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  1000. if (bm.id === m.id) continue;
  1001. const key = `${bm.id}>${m.id}`;
  1002. if (seen.has(key)) continue;
  1003. seen.add(key);
  1004. edges.push({
  1005. source: bm.id,
  1006. target: m.id,
  1007. kind: 'calls',
  1008. line: bm.startLine,
  1009. provenance: 'heuristic',
  1010. metadata: { synthesizedBy: 'interface-impl', via: m.name, registeredAt: `${m.filePath}:${m.startLine}` },
  1011. });
  1012. added++;
  1013. }
  1014. }
  1015. }
  1016. }
  1017. }
  1018. return edges;
  1019. }
  1020. /**
  1021. * Go gRPC stub → impl bridge. The protoc-gen-go-grpc codegen emits an
  1022. * `UnimplementedXxxServer` struct in `*_grpc.pb.go` carrying one method
  1023. * per service RPC; the real handler is a hand-written struct in another
  1024. * file (`x/bank/keeper/msg_server.go::msgServer.Send` in cosmos-sdk).
  1025. * Go's structural typing means no `implements` edge exists for our
  1026. * resolver to follow, so `trace("Send","SendCoins")` lands on the
  1027. * empty stub and reports "no path" (validated empirically — the cosmos
  1028. * Q1 r1 trace failure that drove this work).
  1029. *
  1030. * Bridge: for each `UnimplementedXxxServer` whose RPC-method names are
  1031. * a SUBSET of some other Go struct's method names, emit `calls` edges
  1032. * `stub.method → impl.method` (paired by name). Excludes the gRPC
  1033. * internal markers `mustEmbedUnimplementedXxxServer` and
  1034. * `testEmbeddedByValue`, and skips candidate impls that themselves
  1035. * live in a generated file (their `xxxClient` / sibling stubs would
  1036. * otherwise look like impls).
  1037. *
  1038. * Multiple candidates is allowed and capped at MAX_CALLBACKS_PER_CHANNEL —
  1039. * a service often has both a production impl and one or more test
  1040. * mocks; linking to all preserves trace utility without false-favoring.
  1041. *
  1042. * Provenance: `heuristic`, `synthesizedBy: 'go-grpc-stub-impl'`. The
  1043. * stub's source line is the wiring site shown in the trace trail.
  1044. */
  1045. async function goGrpcStubImplEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  1046. let scanned255 = 0;
  1047. const edges: Edge[] = [];
  1048. const seen = new Set<string>();
  1049. const STUB_RE = /^Unimplemented.*Server$/;
  1050. // gRPC internal-helper methods that appear on every Unimplemented*Server;
  1051. // not part of the service contract, so exclude when computing the RPC-method
  1052. // signature used to match impls.
  1053. const isInternalMarker = (n: string) => n.startsWith('mustEmbed') || n === 'testEmbeddedByValue';
  1054. // Methods directly contained by each Go struct, name-only. Built once.
  1055. const methodNamesByStruct = new Map<string, Set<string>>();
  1056. const methodNodesByStruct = new Map<string, Node[]>();
  1057. const goStructs: Node[] = [];
  1058. for (const s of queries.iterateNodesByKind('struct')) {
  1059. if ((++scanned255 & 63) === 0) await onYield();
  1060. if (s.language !== 'go') continue;
  1061. goStructs.push(s);
  1062. const ms = queries
  1063. .getOutgoingEdges(s.id, ['contains'])
  1064. .map((e) => queries.getNodeById(e.target))
  1065. .filter((n): n is Node => !!n && n.kind === 'method');
  1066. methodNodesByStruct.set(s.id, ms);
  1067. methodNamesByStruct.set(s.id, new Set(ms.map((m) => m.name)));
  1068. }
  1069. for (const stub of goStructs) {
  1070. if (!STUB_RE.test(stub.name)) continue;
  1071. // The stub MUST live in a generated file — that's what tells us this is
  1072. // a protoc-emitted scaffold rather than someone naming a struct
  1073. // `UnimplementedXxxServer` by hand. Without this gate we'd also bridge
  1074. // such hand-written structs and create misleading edges.
  1075. if (!isGeneratedFile(stub.filePath)) continue;
  1076. const stubMethods = (methodNodesByStruct.get(stub.id) ?? []).filter(
  1077. (m) => !isInternalMarker(m.name),
  1078. );
  1079. if (stubMethods.length === 0) continue;
  1080. const stubMethodNames = stubMethods.map((m) => m.name);
  1081. for (const cand of goStructs) {
  1082. if (cand.id === stub.id) continue;
  1083. // Skip generated-file candidates — they're siblings (msgClient,
  1084. // UnsafeMsgServer, …) whose method sets coincidentally match.
  1085. if (isGeneratedFile(cand.filePath)) continue;
  1086. const candNames = methodNamesByStruct.get(cand.id);
  1087. if (!candNames) continue;
  1088. // Subset: every RPC method must exist on the candidate by name.
  1089. // Signature-level match would tighten this further, but name-match
  1090. // alone already gives one-to-one pairing in real codebases because
  1091. // gRPC method-name sets are highly distinctive (Send + MultiSend +
  1092. // UpdateParams + SetSendEnabled is unique to bank's MsgServer).
  1093. if (!stubMethodNames.every((n) => candNames.has(n))) continue;
  1094. const candMethods = methodNodesByStruct.get(cand.id) ?? [];
  1095. let added = 0;
  1096. for (const sm of stubMethods) {
  1097. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  1098. for (const cm of candMethods) {
  1099. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  1100. if (cm.name !== sm.name) continue;
  1101. const key = `${sm.id}>${cm.id}`;
  1102. if (seen.has(key)) continue;
  1103. seen.add(key);
  1104. edges.push({
  1105. source: sm.id,
  1106. target: cm.id,
  1107. kind: 'calls',
  1108. line: sm.startLine,
  1109. provenance: 'heuristic',
  1110. metadata: {
  1111. synthesizedBy: 'go-grpc-stub-impl',
  1112. via: cm.name,
  1113. registeredAt: `${cm.filePath}:${cm.startLine}`,
  1114. },
  1115. });
  1116. added++;
  1117. }
  1118. }
  1119. }
  1120. }
  1121. return edges;
  1122. }
  1123. /**
  1124. * Phase 5: React JSX child rendering. A component that returns `<Child .../>`
  1125. * mounts Child — React calls it — but JSX instantiation isn't a static call edge,
  1126. * so a render tree (App.render → StaticCanvas → renderStaticScene) breaks at the
  1127. * JSX hop. Link parent → each capitalized JSX child it renders. File-oriented
  1128. * (read each JSX file once). Precision gate: the child name must resolve to a
  1129. * component/function/class node — TS generics like `Array<Foo>` resolve to a type
  1130. * (or nothing) and are dropped.
  1131. */
  1132. async function reactJsxChildEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1133. let scannedFiles = 0;
  1134. const edges: Edge[] = [];
  1135. const seen = new Set<string>();
  1136. const PARENT_KINDS = new Set(['method', 'function', 'component']);
  1137. let scanned = 0;
  1138. for (const file of ctx.getAllFiles()) {
  1139. if ((++scannedFiles & 15) === 0) await onYield();
  1140. if ((++scanned & 255) === 0) await onYield(); // #1091: yield mid-scan on huge graphs
  1141. const content = ctx.readFile(file);
  1142. if (!content || (!content.includes('</') && !content.includes('/>'))) continue; // JSX-file gate
  1143. // File-level language gate, not merely a project-level one: mixed C/JS
  1144. // monorepos must not interpret `"<Foo/>"` inside C as JSX (#1560).
  1145. const parents = ctx.getNodesInFile(file).filter(
  1146. (n) => PARENT_KINDS.has(n.kind) && JS_FAMILY.includes(n.language)
  1147. );
  1148. if (parents.length === 0) continue;
  1149. for (const parent of parents) {
  1150. const src = sliceLines(content, parent.startLine, parent.endLine);
  1151. if (!src || (!src.includes('</') && !src.includes('/>'))) continue;
  1152. const names = new Set<string>();
  1153. JSX_TAG_RE.lastIndex = 0;
  1154. let m: RegExpExecArray | null;
  1155. while ((m = JSX_TAG_RE.exec(src))) names.add(m[1]!);
  1156. let added = 0;
  1157. for (const name of names) {
  1158. if (added >= MAX_JSX_CHILDREN) break;
  1159. const child = ctx.getNodesByName(name).find(
  1160. (n) => n.kind === 'component' || n.kind === 'function' || n.kind === 'class'
  1161. );
  1162. if (!child || child.id === parent.id) continue;
  1163. const key = `${parent.id}>${child.id}`;
  1164. if (seen.has(key)) continue;
  1165. seen.add(key);
  1166. edges.push({
  1167. source: parent.id, target: child.id, kind: 'calls', line: parent.startLine,
  1168. provenance: 'heuristic',
  1169. metadata: { synthesizedBy: 'jsx-render', via: name },
  1170. });
  1171. added++;
  1172. }
  1173. }
  1174. }
  1175. return edges;
  1176. }
  1177. /**
  1178. * Phase 6: Vue SFC templates. The `.vue` extractor only parses `<script>`, so
  1179. * template usage is invisible — child components and event handlers used ONLY in
  1180. * the template have no edge to them. PascalCase children (`<VPNav/>`) are already
  1181. * caught by reactJsxChildEdges (which scans the SFC component node), so this adds
  1182. * the two Vue-specific shapes:
  1183. * - kebab-case children: `<el-button>` → `ElButton` component (renders).
  1184. * - event bindings: `@click="onClick"` / `v-on:submit="save"` → handler method.
  1185. * Scoped to the `<template>` block of `.vue` files; resolution gate (kebab→
  1186. * component, handler→function/method) keeps precision; inline arrows / `$emit`
  1187. * skipped.
  1188. */
  1189. async function vueTemplateEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1190. let scannedFiles = 0;
  1191. let scanned255 = 0;
  1192. const edges: Edge[] = [];
  1193. const seen = new Set<string>();
  1194. const COMPONENT_KINDS = new Set(['component', 'function', 'class']);
  1195. const HANDLER_KINDS = new Set(['method', 'function']);
  1196. // A composable's returned member may be a fn (`function close(){}`) or an
  1197. // arrow assigned to a const (`const close = () => {}`).
  1198. const RETURN_KINDS = new Set(['method', 'function', 'variable', 'constant']);
  1199. // Nuxt auto-imports nested components by a DIRECTORY-PREFIXED name —
  1200. // `components/media/Card.vue` is used as `<MediaCard/>`, not `<Card/>` — but
  1201. // the component node is named by basename (`Card`), so a direct tag match
  1202. // misses it (flat components match by basename and don't need this). Map each
  1203. // nested component's Nuxt name → node so those template usages resolve.
  1204. const nuxtComponents = new Map<string, Node>();
  1205. for (const c of (ctx.iterateNodesByKind?.('component') ?? ctx.getNodesByKind('component'))) {
  1206. if ((++scanned255 & 63) === 0) await onYield();
  1207. const nn = nuxtComponentName(c.filePath);
  1208. if (nn && !nuxtComponents.has(nn)) nuxtComponents.set(nn, c);
  1209. }
  1210. for (const file of ctx.getAllFiles()) {
  1211. if ((++scannedFiles & 15) === 0) await onYield();
  1212. if (!file.endsWith('.vue')) continue;
  1213. const content = ctx.readFile(file);
  1214. const tpl = content && content.match(/<template[^>]*>([\s\S]*)<\/template>/i)?.[1];
  1215. if (!tpl) continue;
  1216. const comp = ctx.getNodesInFile(file).find((n) => n.kind === 'component');
  1217. if (!comp) continue;
  1218. // Composable-destructure map: alias → { composable, key }. Lets us resolve a
  1219. // template handler that isn't a local function but a destructured composable
  1220. // return (`@click="closeSidebar"` ← `const { close: closeSidebar } = useSidebarControl()`).
  1221. const script = content.match(/<script[^>]*>([\s\S]*?)<\/script>/i)?.[1] ?? '';
  1222. const destructured = new Map<string, { composable: string; key: string }>();
  1223. VUE_DESTRUCTURE_RE.lastIndex = 0;
  1224. let dm: RegExpExecArray | null;
  1225. while ((dm = VUE_DESTRUCTURE_RE.exec(script))) {
  1226. if (!/^use[A-Z]/.test(dm[2]!)) continue; // composables / hooks only
  1227. for (const part of dm[1]!.split(',')) {
  1228. const pm = part.trim().match(/^(\w+)\s*(?::\s*(\w+))?$/); // key | key: alias
  1229. if (pm) destructured.set(pm[2] || pm[1]!, { composable: dm[2]!, key: pm[1]! });
  1230. }
  1231. }
  1232. let added = 0;
  1233. const addEdge = (target: Node | undefined, meta: Record<string, unknown>) => {
  1234. if (added >= MAX_JSX_CHILDREN || !target || target.id === comp.id) return;
  1235. const k = `${comp.id}>${target.id}>${meta.synthesizedBy}`;
  1236. if (seen.has(k)) return;
  1237. seen.add(k);
  1238. edges.push({ source: comp.id, target: target.id, kind: 'calls', line: comp.startLine, provenance: 'heuristic', metadata: meta });
  1239. added++;
  1240. };
  1241. // Prefer a target in THIS SFC (handlers live in the same file's script) —
  1242. // avoids cross-file mis-match when a name repeats across a monorepo.
  1243. const resolve = (name: string, kinds: Set<string>): Node | undefined => {
  1244. const matches = ctx.getNodesByName(name).filter((n) => kinds.has(n.kind));
  1245. return matches.find((n) => n.filePath === file) ?? matches[0];
  1246. };
  1247. let m: RegExpExecArray | null;
  1248. VUE_KEBAB_RE.lastIndex = 0;
  1249. while ((m = VUE_KEBAB_RE.exec(tpl))) {
  1250. const tag = kebabToPascal(m[1]!);
  1251. addEdge(resolve(tag, COMPONENT_KINDS) ?? nuxtComponents.get(tag), { synthesizedBy: 'jsx-render', via: m[1] });
  1252. }
  1253. // PascalCase component tags. Try a direct name match first (flat components
  1254. // and explicit registrations), then the Nuxt dir-prefixed auto-import name
  1255. // (`<MediaCard>` → components/media/Card.vue). Built-ins match neither → no edge.
  1256. VUE_PASCAL_RE.lastIndex = 0;
  1257. while ((m = VUE_PASCAL_RE.exec(tpl))) {
  1258. const tag = m[1]!;
  1259. addEdge(resolve(tag, COMPONENT_KINDS) ?? nuxtComponents.get(tag), { synthesizedBy: 'jsx-render', via: tag });
  1260. }
  1261. VUE_HANDLER_RE.lastIndex = 0;
  1262. while ((m = VUE_HANDLER_RE.exec(tpl))) {
  1263. const event = m[1]!;
  1264. const expr = m[2]!.trim();
  1265. if (expr.includes('=>') || expr.startsWith('$')) continue; // inline arrow / $emit
  1266. const name = expr.match(/^([A-Za-z_]\w*)/)?.[1];
  1267. if (!name) continue;
  1268. const direct = resolve(name, HANDLER_KINDS);
  1269. if (direct) { addEdge(direct, { synthesizedBy: 'vue-handler', event }); continue; }
  1270. // Composable-destructure handler → resolve to the composable's returned fn.
  1271. const d = destructured.get(name);
  1272. if (!d) continue;
  1273. const composable = resolve(d.composable, HANDLER_KINDS);
  1274. // Resolve to the SPECIFIC returned member (e.g. `close`) defined in the
  1275. // composable's file. No fallback to the composable itself — the component
  1276. // already has a static `useX()` call edge, so that would just be redundant
  1277. // and less precise.
  1278. const keyFn = composable
  1279. ? ctx.getNodesByName(d.key).find((n) => RETURN_KINDS.has(n.kind) && n.filePath === composable.filePath)
  1280. : undefined;
  1281. if (keyFn) addEdge(keyFn, { synthesizedBy: 'vue-handler', event, via: d.composable });
  1282. }
  1283. }
  1284. return edges;
  1285. }
  1286. /**
  1287. * React Native cross-language event channel (Phase 3 of the mixed-iOS/RN
  1288. * bridging effort). Same shape as `eventEmitterEdges` but cross-language:
  1289. *
  1290. * Native (ObjC, on RCTEventEmitter subclass):
  1291. * [self sendEventWithName:@"locationUpdate" body:@{...}];
  1292. *
  1293. * Native (Java/Kotlin, via the JS module dispatcher):
  1294. * emitter.emit("locationUpdate", body);
  1295. * reactContext.getJSModule(RCTDeviceEventEmitter.class).emit("locationUpdate", body);
  1296. *
  1297. * JS (subscriber):
  1298. * new NativeEventEmitter(NativeModules.Geo).addListener("locationUpdate", handler);
  1299. * DeviceEventEmitter.addListener("locationUpdate", handler);
  1300. *
  1301. * Synthesize: native dispatch site → JS handler, keyed by the literal
  1302. * event name. A NAMED handler (`addListener('x', handleX)`) is the target
  1303. * when it is a node; an unnamed one — a parameter passed through, or an
  1304. * inline `(data) => {…}` written in a `useEffect` — is attributed to the
  1305. * enclosing function, where the event demonstrably lands. (The in-language
  1306. * synthesizer stays named-only; this channel pairs across a language
  1307. * boundary on a literal, which is the evidence that makes the wider
  1308. * attribution safe.)
  1309. *
  1310. * Provenance `'heuristic'`, synthesizedBy `'rn-event-channel'`.
  1311. */
  1312. // ObjC's `[self sendEventWithName:@"X" body:...]` shape (bracket syntax,
  1313. // `@` string literals).
  1314. const RN_OBJC_SEND_RE = /\bsendEventWithName\s*:\s*@"([^"]+)"/g;
  1315. // Swift's `sendEvent(withName: "X", body: ...)` shape — same RCTEventEmitter
  1316. // method, different call syntax. Both Objective-C and Swift subclass
  1317. // RCTEventEmitter so this catches the Swift-side equivalent emission sites
  1318. // (e.g. RNFusedLocation.swift's `sendEvent(withName: "geolocationDidChange",
  1319. // body: locationData)`).
  1320. const RN_SWIFT_SEND_RE = /\bsendEvent\s*\(\s*withName\s*:\s*"([^"]+)"/g;
  1321. // JVM-side emitter calls: `emitter.emit("X", body)`. Matches both Java
  1322. // and Kotlin syntax because the call form is identical. Restricted to
  1323. // JVM source files in the consumer so we don't re-process JS emits
  1324. // (which `eventEmitterEdges` already handles).
  1325. const RN_JVM_EMIT_RE = /\.emit\s*\(\s*"([^"]+)"\s*,/g;
  1326. // Custom `sendEvent(reactContext, "X", body)` wrapper — extremely common
  1327. // (react-native-device-info and many libs wrap `DeviceEventManagerModule…emit`
  1328. // behind a helper whose `.emit(eventName, …)` uses a VARIABLE, so RN_JVM_EMIT_RE
  1329. // misses it; the literal lives in the wrapper CALL instead). Captures the first
  1330. // string literal inside a `sendEvent(...)` call. `[^;{}]*?` keeps it on one
  1331. // statement and stops at a block boundary, so the wrapper DEFINITION (whose `(`
  1332. // is followed by `… ) {`) never matches. Multi-line tolerant. (java/kotlin/swift)
  1333. const RN_NATIVE_SENDEVENT_RE = /\bsendEvent\s*\([^;{}]*?"([^"]+)"/g;
  1334. async function rnEventEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1335. let scannedFiles = 0;
  1336. // Native dispatchers (source = the native method whose body sends the
  1337. // event) and JS handlers (target = the function/method registered as
  1338. // the listener) keyed by event name.
  1339. const nativeDispatchersByEvent = new Map<string, Set<string>>();
  1340. const jsHandlersByEvent = new Map<string, Map<string, string>>();
  1341. for (const file of ctx.getAllFiles()) {
  1342. if ((++scannedFiles & 15) === 0) await onYield();
  1343. const content = ctx.readFile(file);
  1344. if (!content) continue;
  1345. const nodesInFile = ctx.getNodesInFile(file);
  1346. const lineOf = makeLineAt(content, 1);
  1347. const addDispatcher = (event: string, line: number) => {
  1348. const disp = enclosingFn(nodesInFile, line);
  1349. if (!disp) return;
  1350. const set = nativeDispatchersByEvent.get(event) ?? new Set<string>();
  1351. set.add(disp.id);
  1352. nativeDispatchersByEvent.set(event, set);
  1353. };
  1354. // ObjC side: `sendEventWithName:@"X"` only fires inside `.m`/`.mm`
  1355. // files (RCTEventEmitter subclasses).
  1356. if (file.endsWith('.m') || file.endsWith('.mm')) {
  1357. RN_OBJC_SEND_RE.lastIndex = 0;
  1358. let m: RegExpExecArray | null;
  1359. while ((m = RN_OBJC_SEND_RE.exec(content))) {
  1360. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1361. }
  1362. }
  1363. // Swift side: same RCTEventEmitter method, parens/named-args syntax.
  1364. if (file.endsWith('.swift')) {
  1365. RN_SWIFT_SEND_RE.lastIndex = 0;
  1366. let m: RegExpExecArray | null;
  1367. while ((m = RN_SWIFT_SEND_RE.exec(content))) {
  1368. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1369. }
  1370. RN_NATIVE_SENDEVENT_RE.lastIndex = 0;
  1371. while ((m = RN_NATIVE_SENDEVENT_RE.exec(content))) {
  1372. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1373. }
  1374. }
  1375. // JVM side: `.emit("X", …)` in Java/Kotlin, plus the common
  1376. // `sendEvent(ctx, "X", body)` wrapper. (We pattern-match anywhere in the
  1377. // file; the JS in-language path uses a separate emitter object pattern and
  1378. // is already handled by eventEmitterEdges.)
  1379. if (file.endsWith('.java') || file.endsWith('.kt')) {
  1380. let m: RegExpExecArray | null;
  1381. RN_JVM_EMIT_RE.lastIndex = 0;
  1382. while ((m = RN_JVM_EMIT_RE.exec(content))) {
  1383. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1384. }
  1385. RN_NATIVE_SENDEVENT_RE.lastIndex = 0;
  1386. while ((m = RN_NATIVE_SENDEVENT_RE.exec(content))) {
  1387. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1388. }
  1389. }
  1390. // JS subscribers (.addListener("X", handler)). Restrict to JS-family
  1391. // files so a native file's `addListener:` (the ObjC method) doesn't
  1392. // get mistaken for a JS subscription — they're entirely different
  1393. // things despite sharing a name.
  1394. if (
  1395. file.endsWith('.js') ||
  1396. file.endsWith('.jsx') ||
  1397. file.endsWith('.ts') ||
  1398. file.endsWith('.tsx') ||
  1399. file.endsWith('.mjs') ||
  1400. file.endsWith('.cjs')
  1401. ) {
  1402. // Match BOTH the named-handler form (`.addListener('x', fn)`) and
  1403. // an unnamed-handler form (`.addListener('x', listener)` where
  1404. // `listener` is a parameter — common in RN wrapper APIs like
  1405. // RNFirebase's `messaging().onMessageReceived(listener)`). For the
  1406. // unnamed case we attribute the subscription to the ENCLOSING JS
  1407. // function (the abstraction layer), giving a reachability-correct
  1408. // hop even when the actual user-side handler lives one call up.
  1409. const ADDLISTENER_ANY = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*([A-Za-z_][\w.]*)/g;
  1410. // The inline form: `.addListener('x', (data) => {…})` / `function () {…}`.
  1411. const ADDLISTENER_INLINE =
  1412. /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*(?:async\s*)?(?:\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>|function\s*\()/g;
  1413. ADDLISTENER_ANY.lastIndex = 0;
  1414. let m: RegExpExecArray | null;
  1415. while ((m = ADDLISTENER_ANY.exec(content))) {
  1416. const event = m[1];
  1417. const arg = m[2];
  1418. if (!event || !arg) continue;
  1419. const bareName = arg.includes('.') ? arg.slice(arg.lastIndexOf('.') + 1) : arg;
  1420. // Try a named-symbol match first (matches the in-language semantic).
  1421. const namedHandler = ctx
  1422. .getNodesByName(bareName)
  1423. .find((n) => n.kind === 'function' || n.kind === 'method');
  1424. let targetId: string | null = namedHandler?.id ?? null;
  1425. if (!targetId) {
  1426. // Fall back to the enclosing function — the subscribe-wrapper
  1427. // pattern means the event fires THROUGH this function on its
  1428. // way to user code. Reachability-correct attribution.
  1429. const enclosing = enclosingFn(nodesInFile, lineOf(m.index));
  1430. targetId = enclosing?.id ?? null;
  1431. }
  1432. if (!targetId) {
  1433. // Broader fallback for JS object-literal API shape
  1434. // (`const Foo = { watchX(...) { … addListener(...) … } }`):
  1435. // method shorthand inside an object literal isn't extracted
  1436. // as a method node, so enclosingFn returns null. Attribute to
  1437. // the smallest enclosing `constant` / `variable` node — that's
  1438. // the API surface a downstream caller would `import` and
  1439. // invoke. Reachability-correct.
  1440. const line = lineOf(m.index);
  1441. let smallest: typeof nodesInFile[number] | null = null;
  1442. for (const n of nodesInFile) {
  1443. if (n.kind !== 'constant' && n.kind !== 'variable') continue;
  1444. const end = n.endLine ?? n.startLine;
  1445. if (n.startLine <= line && end >= line) {
  1446. if (!smallest || n.startLine >= smallest.startLine) smallest = n;
  1447. }
  1448. }
  1449. targetId = smallest?.id ?? null;
  1450. }
  1451. if (!targetId) continue;
  1452. const map = jsHandlersByEvent.get(event) ?? new Map<string, string>();
  1453. map.set(targetId, `${file}:${lineOf(m.index)}`);
  1454. jsHandlersByEvent.set(event, map);
  1455. }
  1456. // Inline listeners — the shape a React component registers inside a
  1457. // `useEffect`: `nativeEmitter.addListener('onCaptureComplete', (data) =>
  1458. // { … router.push('/review') })`. There is no handler symbol to name,
  1459. // so the subscription is attributed to the enclosing function exactly
  1460. // as the unnamed-argument form above is: the native event lands in that
  1461. // component, and its body is where a reader looks next. This channel
  1462. // only — the in-language synthesizer keeps its named-handler policy.
  1463. ADDLISTENER_INLINE.lastIndex = 0;
  1464. while ((m = ADDLISTENER_INLINE.exec(content))) {
  1465. const event = m[1];
  1466. if (!event) continue;
  1467. const enclosing = enclosingFn(nodesInFile, lineOf(m.index));
  1468. if (!enclosing) continue;
  1469. const map = jsHandlersByEvent.get(event) ?? new Map<string, string>();
  1470. if (!map.has(enclosing.id)) map.set(enclosing.id, `${file}:${lineOf(m.index)}`);
  1471. jsHandlersByEvent.set(event, map);
  1472. }
  1473. }
  1474. }
  1475. const edges: Edge[] = [];
  1476. const seen = new Set<string>();
  1477. for (const [event, dispatchers] of nativeDispatchersByEvent) {
  1478. const handlers = jsHandlersByEvent.get(event);
  1479. if (!handlers) continue;
  1480. // Same fan-out guard as the in-language channel: generic event names
  1481. // (e.g. 'change', 'error', 'data') with many handlers/dispatchers
  1482. // can't be matched precisely without receiver-type info.
  1483. if (dispatchers.size > EVENT_FANOUT_CAP || handlers.size > EVENT_FANOUT_CAP) continue;
  1484. for (const d of dispatchers) {
  1485. for (const [h, registeredAt] of handlers) {
  1486. if (d === h) continue;
  1487. const key = `${d}>${h}`;
  1488. if (seen.has(key)) continue;
  1489. seen.add(key);
  1490. edges.push({
  1491. source: d,
  1492. target: h,
  1493. kind: 'calls',
  1494. provenance: 'heuristic',
  1495. metadata: { synthesizedBy: 'rn-event-channel', event, registeredAt },
  1496. });
  1497. }
  1498. }
  1499. }
  1500. return edges;
  1501. }
  1502. /**
  1503. * Phase 6 — React Native Fabric/Codegen view component bridge.
  1504. *
  1505. * The Fabric framework extractor (`frameworks/fabric.ts`) emits
  1506. * `component` nodes named after the JS-visible component (e.g.
  1507. * `RNSScreenStack`) from each `codegenNativeComponent<Props>('Name')`
  1508. * spec declaration. The native implementation lives in an ObjC++/.mm or
  1509. * Kotlin/Java class whose name follows one of RN's conventions:
  1510. *
  1511. * - Exact: `RNSScreenStack`
  1512. * - With suffix: `RNSScreenStackView`, `RNSScreenStackViewManager`,
  1513. * `RNSScreenStackComponentView`, `RNSScreenStackManager`
  1514. *
  1515. * This synthesizer walks every Fabric component node and looks for a
  1516. * native class matching one of those names; when found, emits a
  1517. * `calls` edge `component → native class` (provenance `'heuristic'`,
  1518. * `synthesizedBy:'fabric-native-impl'`) so trace from JSX usage of the
  1519. * component continues into native.
  1520. *
  1521. * The convention-based suffix lookup is precise: there's no name
  1522. * collision in RN view-manager codebases by design (Codegen output would
  1523. * conflict otherwise).
  1524. */
  1525. const FABRIC_NATIVE_SUFFIXES = ['', 'View', 'ViewManager', 'ComponentView', 'Manager'];
  1526. /**
  1527. * Expo Modules cross-platform pairing. An Expo Module exposes the SAME
  1528. * JS-visible method (`AsyncFunction("getBatteryLevelAsync")`) from BOTH an iOS
  1529. * (Swift) and an Android (Kotlin) implementation. A JS callsite name-resolves to
  1530. * only ONE of them, so the other platform's impl looked like nothing called it
  1531. * (and editing it showed no blast radius). Link the iOS and Android impls of the
  1532. * same `<module>.<method>` to each other (both directions), so a JS call that
  1533. * reaches one platform reaches the other, and editing either surfaces the JS
  1534. * caller. The Expo method nodes are id-prefixed `expo-module:` and qualified
  1535. * `<file>::<module>.<method>` by the framework extractor.
  1536. */
  1537. async function expoCrossPlatformEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  1538. let scanned255 = 0;
  1539. const edges: Edge[] = [];
  1540. const seen = new Set<string>();
  1541. const byKey = new Map<string, Node[]>();
  1542. for (const m of queries.iterateNodesByKind('method')) {
  1543. if ((++scanned255 & 63) === 0) await onYield();
  1544. if (!m.id.startsWith('expo-module:')) continue;
  1545. const key = m.qualifiedName.split('::').pop(); // `<module>.<method>`
  1546. if (!key) continue;
  1547. const arr = byKey.get(key);
  1548. if (arr) arr.push(m);
  1549. else byKey.set(key, [m]);
  1550. }
  1551. for (const group of byKey.values()) {
  1552. if (group.length < 2) continue;
  1553. for (const a of group) {
  1554. for (const b of group) {
  1555. if (a.id === b.id || a.language === b.language) continue; // cross-platform only
  1556. const key = `${a.id}>${b.id}`;
  1557. if (seen.has(key)) continue;
  1558. seen.add(key);
  1559. edges.push({
  1560. source: a.id,
  1561. target: b.id,
  1562. kind: 'calls',
  1563. line: a.startLine,
  1564. provenance: 'heuristic',
  1565. metadata: { synthesizedBy: 'expo-cross-platform', via: a.name },
  1566. });
  1567. }
  1568. }
  1569. }
  1570. return edges;
  1571. }
  1572. /**
  1573. * Classic React Native NativeModules cross-platform pairing. A native module
  1574. * method (`@ReactMethod` on Android, `RCT_EXPORT_METHOD` on iOS) is implemented
  1575. * on BOTH platforms, but a JS callsite name-resolves to only ONE — so the other
  1576. * platform's impl looked like nothing called it. A native method that HAS a JS
  1577. * caller is a confirmed bridge method; link it to the same-named native method
  1578. * in another language (the other platform's impl) so a JS call reaching one
  1579. * platform reaches the other, and editing either surfaces the JS caller.
  1580. *
  1581. * Names are normalized to the first selector keyword (`getFreeDiskStorage:` →
  1582. * `getFreeDiskStorage`) — that's the JS-visible name, and how the iOS selector
  1583. * lines up with the bare Android method name.
  1584. */
  1585. async function rnCrossPlatformEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  1586. let scanned255 = 0;
  1587. const edges: Edge[] = [];
  1588. const seen = new Set<string>();
  1589. const NATIVE = new Set(['java', 'kotlin', 'objc', 'cpp']);
  1590. const JS = new Set(['typescript', 'tsx', 'javascript', 'jsx']);
  1591. // RN module INFRASTRUCTURE methods exist on every native module (called by the
  1592. // RN runtime, not user JS), so pairing them by name would cross-link unrelated
  1593. // modules in a multi-module repo. Skip them — they aren't user-facing methods.
  1594. const RN_INFRA = new Set([
  1595. 'addListener', 'removeListeners', 'getConstants', 'constantsToExport', 'getName',
  1596. 'invalidate', 'initialize', 'getDefaultEventTypes', 'supportedEvents',
  1597. 'requiresMainQueueSetup', 'methodQueue',
  1598. ]);
  1599. const norm = (name: string): string => {
  1600. const i = name.indexOf(':');
  1601. return i >= 0 ? name.slice(0, i) : name;
  1602. };
  1603. // Index native methods by their JS-visible (normalized) name. Only names with
  1604. // impls in ≥2 native languages can pair, so the per-method JS-caller check
  1605. // below only runs for genuine cross-platform candidates.
  1606. const byName = new Map<string, Node[]>();
  1607. for (const m of queries.iterateNodesByKind('method')) {
  1608. if ((++scanned255 & 63) === 0) await onYield();
  1609. if (!NATIVE.has(m.language)) continue;
  1610. const key = norm(m.name);
  1611. const arr = byName.get(key);
  1612. if (arr) arr.push(m);
  1613. else byName.set(key, [m]);
  1614. }
  1615. for (const [groupName, group] of byName) {
  1616. if (RN_INFRA.has(groupName)) continue;
  1617. const langs = new Set(group.map((m) => m.language));
  1618. if (langs.size < 2) continue; // single-platform — nothing to pair
  1619. for (const m of group) {
  1620. // Is m a bridge method? (a JS-language `calls` edge points at it)
  1621. const incoming = queries.getIncomingEdges(m.id, ['calls']);
  1622. if (incoming.length === 0) continue;
  1623. const sources = queries.getNodesByIds(incoming.map((e) => e.source));
  1624. const isBridge = incoming.some((e) => {
  1625. const s = sources.get(e.source);
  1626. return !!s && JS.has(s.language);
  1627. });
  1628. if (!isBridge) continue;
  1629. // Link to the other-platform impls (both directions).
  1630. for (const sib of group) {
  1631. if (sib.id === m.id || sib.language === m.language) continue;
  1632. for (const [a, b] of [[m, sib], [sib, m]] as const) {
  1633. const key = `${a.id}>${b.id}`;
  1634. if (seen.has(key)) continue;
  1635. seen.add(key);
  1636. edges.push({
  1637. source: a.id,
  1638. target: b.id,
  1639. kind: 'calls',
  1640. line: a.startLine,
  1641. provenance: 'heuristic',
  1642. metadata: { synthesizedBy: 'rn-cross-platform', via: norm(m.name) },
  1643. });
  1644. }
  1645. }
  1646. }
  1647. }
  1648. return edges;
  1649. }
  1650. async function fabricNativeImplEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1651. let scanned255 = 0;
  1652. const edges: Edge[] = [];
  1653. const seen = new Set<string>();
  1654. // The Fabric extractor IDs are prefixed `fabric-component:` so we can
  1655. // filter to just those while streaming — never materializing the whole
  1656. // `component` kind (#1212).
  1657. const components: Node[] = [];
  1658. for (const n of (ctx.iterateNodesByKind?.('component') ?? ctx.getNodesByKind('component'))) {
  1659. if ((++scanned255 & 63) === 0) await onYield();
  1660. if (n.id.startsWith('fabric-component:')) components.push(n);
  1661. }
  1662. if (components.length === 0) return edges;
  1663. // Pre-index native classes by name for O(1) lookup.
  1664. const nativeClassesByName = new Map<string, Node[]>();
  1665. for (const n of (ctx.iterateNodesByKind?.('class') ?? ctx.getNodesByKind('class'))) {
  1666. if ((++scanned255 & 63) === 0) await onYield();
  1667. if (n.language !== 'objc' && n.language !== 'kotlin' && n.language !== 'java' && n.language !== 'cpp') continue;
  1668. const arr = nativeClassesByName.get(n.name);
  1669. if (arr) arr.push(n);
  1670. else nativeClassesByName.set(n.name, [n]);
  1671. }
  1672. for (const component of components) {
  1673. for (const suffix of FABRIC_NATIVE_SUFFIXES) {
  1674. const candidate = component.name + suffix;
  1675. const matches = nativeClassesByName.get(candidate);
  1676. if (!matches || matches.length === 0) continue;
  1677. // Link the component node to every matching native class (iOS +
  1678. // Android each have one).
  1679. for (const native of matches) {
  1680. const key = `${component.id}>${native.id}`;
  1681. if (seen.has(key)) continue;
  1682. seen.add(key);
  1683. edges.push({
  1684. source: component.id,
  1685. target: native.id,
  1686. kind: 'calls',
  1687. provenance: 'heuristic',
  1688. metadata: {
  1689. synthesizedBy: 'fabric-native-impl',
  1690. viaSuffix: suffix || '(exact)',
  1691. componentName: component.name,
  1692. },
  1693. });
  1694. }
  1695. }
  1696. }
  1697. return edges;
  1698. }
  1699. /**
  1700. * MyBatis: link a Java mapper interface method to the XML statement that holds
  1701. * its SQL. The XML extractor (`src/extraction/mybatis-extractor.ts`) qualifies
  1702. * each `<select|insert|update|delete|sql id="X">` as `<namespace>::<id>` where
  1703. * `<namespace>` is the Java FQN of the mapper interface. A Java method's
  1704. * qualifiedName ends with `<ClassName>::<methodName>`, so we suffix-match the
  1705. * last two segments of the XML qualified name to find a unique Java method by
  1706. * `<ClassName>::<methodName>` (`ClassName` = last dotted segment of the XML
  1707. * namespace). Cross-mapper `<include refid="other.X">` references go through
  1708. * the normal qualified-name resolver — only the Java↔XML bridge is synthetic.
  1709. *
  1710. * Precision over recall: ambiguous mappers (multiple Java classes with the
  1711. * same simple name) are dropped. We need-not bridge by package because Java
  1712. * mapper interfaces are typically uniquely named within a project.
  1713. */
  1714. async function mybatisJavaXmlEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  1715. let scanned255 = 0;
  1716. const edges: Edge[] = [];
  1717. const seen = new Set<string>();
  1718. // Collect the XML side FIRST (mapper `<select id=…>` statements extracted as
  1719. // xml-language method nodes): if the project has none — every Java+XML repo
  1720. // that doesn't use MyBatis — return before paying the full java-method
  1721. // stream below. Same rowid stream order as matching inline, so the edge
  1722. // output is byte-identical when mappers do exist.
  1723. const xmlMethods: Node[] = [];
  1724. for (const m of queries.iterateNodesByKind('method')) {
  1725. if ((++scanned255 & 63) === 0) await onYield();
  1726. if (m.language === 'xml') xmlMethods.push(m);
  1727. }
  1728. if (xmlMethods.length === 0) return edges;
  1729. // Index Java methods by `<ClassName>::<methodName>` for O(1) lookup.
  1730. const javaIndex = new Map<string, Node[]>();
  1731. for (const m of queries.iterateNodesByKind('method')) {
  1732. if ((++scanned255 & 63) === 0) await onYield();
  1733. if (m.language !== 'java' && m.language !== 'kotlin') continue;
  1734. const parts = m.qualifiedName.split('::');
  1735. const last = parts[parts.length - 1];
  1736. const cls = parts[parts.length - 2];
  1737. if (!last || !cls) continue;
  1738. const key = `${cls}::${last}`;
  1739. const arr = javaIndex.get(key);
  1740. if (arr) arr.push(m); else javaIndex.set(key, [m]);
  1741. }
  1742. for (const xml of xmlMethods) {
  1743. if ((++scanned255 & 63) === 0) await onYield();
  1744. // Qualified name: `<namespace>::<id>`. Extract the simple class name.
  1745. const colonIdx = xml.qualifiedName.lastIndexOf('::');
  1746. if (colonIdx < 0) continue;
  1747. const namespace = xml.qualifiedName.slice(0, colonIdx);
  1748. const id = xml.qualifiedName.slice(colonIdx + 2);
  1749. if (!namespace || !id) continue;
  1750. const dotIdx = namespace.lastIndexOf('.');
  1751. const className = dotIdx >= 0 ? namespace.slice(dotIdx + 1) : namespace;
  1752. const candidates = javaIndex.get(`${className}::${id}`);
  1753. if (!candidates || candidates.length === 0) continue;
  1754. // Drop ambiguous matches (multiple same-name classes); the user can
  1755. // disambiguate by adding the package-suffix match in a future enhancement.
  1756. if (candidates.length > 1) continue;
  1757. const java = candidates[0]!;
  1758. const key = `${java.id}>${xml.id}`;
  1759. if (seen.has(key)) continue;
  1760. seen.add(key);
  1761. edges.push({
  1762. source: java.id,
  1763. target: xml.id,
  1764. kind: 'calls',
  1765. line: java.startLine,
  1766. provenance: 'heuristic',
  1767. metadata: {
  1768. synthesizedBy: 'mybatis-java-xml',
  1769. via: `${className}.${id}`,
  1770. registeredAt: `${xml.filePath}:${xml.startLine}`,
  1771. },
  1772. });
  1773. }
  1774. return edges;
  1775. }
  1776. /**
  1777. * Gin middleware chain. Gin runs its entire handler chain through one dynamic
  1778. * line in `(*Context).Next`:
  1779. * for c.index < len(c.handlers) { c.handlers[c.index](c); c.index++ }
  1780. * `c.handlers` is a `HandlersChain` (`[]HandlerFunc`) assembled at registration
  1781. * time by `combineHandlers` from the funcs passed to `r.Use(...)` /
  1782. * `r.GET("/path", h...)` / `r.Handle(...)`. Because the call is a computed index
  1783. * into a runtime-built slice, tree-sitter resolves `c.handlers[c.index](c)` to
  1784. * NOTHING — so `callees(Next)` is just the `len()` helper and the flow
  1785. * `ServeHTTP → handleHTTPRequest → Next` dead-ends at the exact symbol the
  1786. * "how do requests flow through the middleware chain" question is about. The
  1787. * agent then re-queries Next and falls back to Read/grep (validated: the gin
  1788. * WITH-arm rabbit-holed on precisely this dead-end).
  1789. *
  1790. * Bridge it: find the chain DISPATCHER (a Go method whose body invokes a
  1791. * `handlers` slice by index) and link it → every HandlerFunc registered via a
  1792. * gin registration call, so `callees(Next)` and `trace(ServeHTTP, <handler>)`
  1793. * connect end-to-end. Named handlers only (`gin.Logger()` → `Logger`,
  1794. * `authMiddleware`); inline closures are anonymous and skipped. Like
  1795. * react-render / interface-impl this is a deliberate over-approximation —
  1796. * reachability-correct (any registered handler CAN run for some route), capped,
  1797. * and gated on the dispatcher existing so it never runs on non-gin Go repos.
  1798. * Provenance `heuristic`, `synthesizedBy:'gin-middleware-chain'`; `registeredAt`
  1799. * is the `.Use`/`.GET` site an agent would otherwise grep for.
  1800. */
  1801. const GIN_DISPATCH_RE = /\.handlers\s*\[[^\]]*\]\s*\(/; // c.handlers[c.index](c)
  1802. const GIN_REG_RE = /\.(?:Use|GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|Any|Handle)\s*\(/g;
  1803. /** Balanced `(...)` body starting at the '(' index; null if unbalanced. */
  1804. function goBalancedArgs(s: string, openIdx: number): string | null {
  1805. let depth = 0;
  1806. for (let i = openIdx; i < s.length; i++) {
  1807. const c = s[i];
  1808. if (c === '(') depth++;
  1809. else if (c === ')') { depth--; if (depth === 0) return s.slice(openIdx + 1, i); }
  1810. }
  1811. return null;
  1812. }
  1813. /** Split a top-level comma list, respecting nested () [] {}. */
  1814. function goSplitArgs(args: string): string[] {
  1815. const out: string[] = [];
  1816. let depth = 0, cur = '';
  1817. for (const c of args) {
  1818. if (c === '(' || c === '[' || c === '{') { depth++; cur += c; }
  1819. else if (c === ')' || c === ']' || c === '}') { depth--; cur += c; }
  1820. else if (c === ',' && depth === 0) { out.push(cur); cur = ''; }
  1821. else cur += c;
  1822. }
  1823. if (cur.trim()) out.push(cur);
  1824. return out;
  1825. }
  1826. /** Tail ident of a handler arg: `gin.Logger()`→`Logger`, `mw`→`mw`; null for string paths / closures. */
  1827. function goHandlerIdent(expr: string): string | null {
  1828. const cleaned = expr.trim().replace(/\(\s*\)$/, ''); // drop a trailing call ()
  1829. if (!cleaned || cleaned.startsWith('"') || cleaned.startsWith('`') || cleaned.startsWith('func')) return null;
  1830. const m = cleaned.match(/(?:\.|^)([A-Za-z_]\w*)$/);
  1831. return m ? m[1]! : null;
  1832. }
  1833. async function ginMiddlewareChainEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1834. let scanned255 = 0;
  1835. let scannedFiles = 0;
  1836. // 1. Find the chain dispatcher(s): a Go method that invokes a `handlers` slice by index.
  1837. const dispatchers: Node[] = [];
  1838. for (const n of queries.iterateNodesByKind('method')) {
  1839. if ((++scanned255 & 63) === 0) await onYield();
  1840. if (n.language !== 'go') continue;
  1841. const content = ctx.readFile(n.filePath);
  1842. const src = content && sliceLines(content, n.startLine, n.endLine);
  1843. if (src && GIN_DISPATCH_RE.test(src)) dispatchers.push(n);
  1844. }
  1845. if (dispatchers.length === 0) return []; // not a gin repo — bail
  1846. // 2. Collect handler identifiers registered via gin registration calls
  1847. // (.Use / .GET / … / .Handle). String args (paths/methods) and inline
  1848. // closures are dropped by goHandlerIdent; the rest are HandlerFuncs.
  1849. const registered = new Map<string, string>(); // name → registeredAt (file:line)
  1850. for (const file of ctx.getAllFiles()) {
  1851. if ((++scannedFiles & 15) === 0) await onYield();
  1852. if (!file.endsWith('.go')) continue;
  1853. const content = ctx.readFile(file);
  1854. if (!content || (!content.includes('.Use(') && !/\.(?:GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|Any|Handle)\(/.test(content))) continue;
  1855. const safe = stripCommentsForRegex(content, 'go');
  1856. GIN_REG_RE.lastIndex = 0;
  1857. let m: RegExpExecArray | null;
  1858. while ((m = GIN_REG_RE.exec(safe))) {
  1859. const parenIdx = m.index + m[0].length - 1;
  1860. const argStr = goBalancedArgs(safe, parenIdx);
  1861. if (!argStr) continue;
  1862. const line = safe.slice(0, m.index).split('\n').length;
  1863. for (const arg of goSplitArgs(argStr)) {
  1864. const name = goHandlerIdent(arg);
  1865. if (name && !registered.has(name)) registered.set(name, `${file}:${line}`);
  1866. }
  1867. }
  1868. }
  1869. if (registered.size === 0) return [];
  1870. // 3. Link each dispatcher → each registered handler node (dedup, capped).
  1871. const edges: Edge[] = [];
  1872. const seen = new Set<string>();
  1873. for (const disp of dispatchers) {
  1874. let added = 0;
  1875. for (const [name, registeredAt] of registered) {
  1876. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  1877. const handler = ctx.getNodesByName(name).find(
  1878. (n) => (n.kind === 'function' || n.kind === 'method') && n.language === 'go'
  1879. );
  1880. if (!handler || handler.id === disp.id) continue;
  1881. const key = `${disp.id}>${handler.id}`;
  1882. if (seen.has(key)) continue;
  1883. seen.add(key);
  1884. edges.push({
  1885. source: disp.id, target: handler.id, kind: 'calls', line: disp.startLine,
  1886. provenance: 'heuristic',
  1887. metadata: { synthesizedBy: 'gin-middleware-chain', via: name, registeredAt },
  1888. });
  1889. added++;
  1890. }
  1891. }
  1892. return edges;
  1893. }
  1894. /**
  1895. * Delphi form code-behind: a form unit `UFRMAbout.pas` owns its visual form
  1896. * definition `UFRMAbout.dfm` (VCL) / `.fmx` (FireMonkey) — paired by basename in
  1897. * the same directory, wired by the `{$R *.dfm}` directive rather than a `uses`
  1898. * clause. Link the unit → its form so a `.dfm`/`.fmx` used only as a form
  1899. * definition isn't orphaned, and editing the form surfaces its code-behind unit.
  1900. */
  1901. async function pascalFormEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1902. let scannedFiles = 0;
  1903. const edges: Edge[] = [];
  1904. const allFiles = new Set(ctx.getAllFiles());
  1905. for (const file of allFiles) {
  1906. if ((++scannedFiles & 255) === 0) await onYield();
  1907. if (!/\.(dfm|fmx)$/i.test(file)) continue;
  1908. const pasFile = file.replace(/\.(dfm|fmx)$/i, '.pas');
  1909. if (!allFiles.has(pasFile)) continue;
  1910. const formNode = ctx.getNodesInFile(file).find((n) => n.kind === 'file');
  1911. const unitNode = ctx.getNodesInFile(pasFile).find((n) => n.kind === 'file');
  1912. if (!formNode || !unitNode) continue;
  1913. edges.push({
  1914. source: unitNode.id,
  1915. target: formNode.id,
  1916. kind: 'references',
  1917. line: unitNode.startLine,
  1918. provenance: 'heuristic',
  1919. metadata: { synthesizedBy: 'pascal-form', registeredAt: pasFile },
  1920. });
  1921. }
  1922. return edges;
  1923. }
  1924. /**
  1925. * SvelteKit file-convention data flow. A route directory's `+page.svelte` (a
  1926. * `component` node) receives its `data` from the sibling `+page.server.{ts,js}`
  1927. * / `+page.{ts,js}` `load` function and posts forms to its `actions` — wired by
  1928. * the framework BY FILE PATH, with no static import between them. So editing a
  1929. * `load` shows no impact on the page it feeds, and the page looks like it has no
  1930. * server-side dependency. Link the page component to its sibling loader's
  1931. * `load` / `actions` (same for `+layout`). The pairing is path-deterministic
  1932. * (same directory, matching `+page`/`+layout` prefix), so it's precise — but
  1933. * it's a framework-convention edge, so provenance stays `heuristic`.
  1934. *
  1935. * Direction: page → load, so `getImpactRadius(load)` surfaces the page (editing
  1936. * a loader's data shows the page it feeds) and the page's dependencies include
  1937. * its loader.
  1938. */
  1939. async function svelteKitLoadEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1940. let scannedFiles = 0;
  1941. const edges: Edge[] = [];
  1942. const allFiles = new Set(ctx.getAllFiles());
  1943. const HOOKS = new Set(['load', 'actions']);
  1944. const HOOK_KINDS = new Set(['function', 'method', 'constant', 'variable']);
  1945. for (const file of allFiles) {
  1946. if ((++scannedFiles & 255) === 0) await onYield();
  1947. const m = file.match(/(.*\/)(\+(?:page|layout))\.svelte$/);
  1948. if (!m) continue;
  1949. const dir = m[1]!;
  1950. const prefix = m[2]!;
  1951. const page = ctx.getNodesInFile(file).find((n) => n.kind === 'component');
  1952. if (!page) continue;
  1953. for (const ext of ['.server.ts', '.server.js', '.ts', '.js']) {
  1954. const loaderFile = `${dir}${prefix}${ext}`;
  1955. if (!allFiles.has(loaderFile)) continue;
  1956. for (const hook of ctx.getNodesInFile(loaderFile)) {
  1957. // `load` and `actions` by name, and every function the loader file
  1958. // declares — a form action is an arrow inside `actions`, and it is a
  1959. // node of its own (`default`, `logout`), where the redirect that ends
  1960. // the submission is actually written.
  1961. const named = HOOK_KINDS.has(hook.kind) && HOOKS.has(hook.name);
  1962. if (!named && hook.kind !== 'function' && hook.kind !== 'method') continue;
  1963. edges.push({
  1964. source: page.id,
  1965. target: hook.id,
  1966. kind: 'calls',
  1967. line: page.startLine,
  1968. provenance: 'heuristic',
  1969. metadata: {
  1970. synthesizedBy: 'sveltekit-load',
  1971. via: hook.name,
  1972. registeredAt: `${loaderFile}:${hook.startLine ?? 0}`,
  1973. },
  1974. });
  1975. }
  1976. }
  1977. }
  1978. return edges;
  1979. }
  1980. /**
  1981. * Redux-thunk dispatch chain. `export const X = createAsyncThunk(prefix, async (a, api) => {...})`
  1982. * (or a wrapper like trezor's `createThunk(...)`) passes the async body as an ARGUMENT, so
  1983. * tree-sitter never extracts it as a function node: `X` is a `constant` whose body's calls are
  1984. * ORPHANED. The `dispatch(nextThunk(...))` calls that drive a thunk chain forward therefore produce
  1985. * no edges, so `callees(X)` is empty and a flow `dispatch(X(...)) → X → nextThunk` dead-ends at the
  1986. * constant (validated on trezor-suite: the signXxxThunk constants had ZERO outgoing edges). Bridge
  1987. * it: body-scan each thunk constant for `dispatch(Y(...))` and link `X → Y`, so the dispatch chain
  1988. * connects. High-precision — the `dispatch(` keyword plus `Y` must resolve to a function/constant/
  1989. * method node; capped; gated on thunk constants existing so it never runs on non-RTK repos.
  1990. * Cross-file by design (a suite thunk dispatches a wallet-core thunk). Provenance `heuristic`,
  1991. * `synthesizedBy:'redux-thunk'`; `registeredAt` is the dispatch site.
  1992. */
  1993. const THUNK_DECL_RE = /create(?:Async)?Thunk/;
  1994. const THUNK_DISPATCH_RE = /\bdispatch\s*\(\s*([A-Za-z_]\w*)\s*[(),]/g;
  1995. const THUNK_FANOUT_CAP = 24;
  1996. async function reduxThunkEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  1997. let scanned255 = 0;
  1998. const edges: Edge[] = [];
  1999. const seen = new Set<string>();
  2000. for (const node of queries.iterateNodesByKind('constant')) {
  2001. if ((++scanned255 & 63) === 0) await onYield();
  2002. // Cheap gate: the initializer (captured in `signature`) must be a create(Async)Thunk call —
  2003. // avoids reading every constant's body on a large repo.
  2004. if (!node.signature || !THUNK_DECL_RE.test(node.signature)) continue;
  2005. const content = ctx.readFile(node.filePath);
  2006. const src = content && sliceLines(content, node.startLine, node.endLine);
  2007. if (!src) continue;
  2008. // Thunks are TS/JS-family (same // and /* */ comment syntax); map to a CommentLang.
  2009. const safe = stripCommentsForRegex(src, node.language === 'javascript' || node.language === 'jsx' ? 'javascript' : 'typescript');
  2010. THUNK_DISPATCH_RE.lastIndex = 0;
  2011. let m: RegExpExecArray | null;
  2012. let added = 0;
  2013. while ((m = THUNK_DISPATCH_RE.exec(safe)) && added < THUNK_FANOUT_CAP) {
  2014. const name = m[1]!;
  2015. if (name === node.name) continue; // self-dispatch (recursive thunk) — skip
  2016. // Resolve the dispatched name, PREFERRING the thunk/action-creator over a same-named
  2017. // service function. `dispatch(X(...))` dispatches a thunk or an action-creator (both
  2018. // `constant`s) — never an unrelated helper that merely shares the name. On octo-call,
  2019. // `leaveCall` is BOTH a `createAsyncThunk` const AND a service function, and the bare
  2020. // `.find()` picked the function (wrong). Order: thunk const > other const > same-file
  2021. // callable > first match. A single candidate (no collision) is unaffected.
  2022. const cands = ctx
  2023. .getNodesByName(name)
  2024. .filter((n) => n.kind === 'constant' || n.kind === 'function' || n.kind === 'method');
  2025. const target =
  2026. cands.find((n) => !!n.signature && THUNK_DECL_RE.test(n.signature)) ??
  2027. cands.find((n) => n.kind === 'constant') ??
  2028. cands.find((n) => n.filePath === node.filePath) ??
  2029. cands[0];
  2030. if (!target || target.id === node.id) continue;
  2031. const key = `${node.id}>${target.id}`;
  2032. if (seen.has(key)) continue;
  2033. seen.add(key);
  2034. const line = node.startLine + safe.slice(0, m.index).split('\n').length - 1;
  2035. edges.push({
  2036. source: node.id,
  2037. target: target.id,
  2038. kind: 'calls',
  2039. line,
  2040. provenance: 'heuristic',
  2041. metadata: { synthesizedBy: 'redux-thunk', via: name, registeredAt: `${node.filePath}:${line}` },
  2042. });
  2043. added++;
  2044. }
  2045. }
  2046. return edges;
  2047. }
  2048. // ── Object-literal registry dispatch ─────────────────────────────────────────
  2049. // A command/handler registry maps string keys → handler class/function symbols in an
  2050. // object literal, then dispatches by a RUNTIME key static parsing can't follow:
  2051. // this.commands = { [Cmd.ADD]: AddObjectCommand, ... } // registration
  2052. // new this.commands[command](args).execute() // dynamic dispatch
  2053. // Bridge it like gin-middleware-chain: link each dispatching function → each registered
  2054. // handler's callable entry (a class's execute/run/handle/… method — preferring the method
  2055. // chained at the dispatch site — or the function value). Scoped to a registry + dispatch in
  2056. // the SAME file (the cross-file barrel-namespace variant, e.g. trezor's getMethod, is
  2057. // deferred). Gated on a real object literal with ≥2 entries that RESOLVE to callables (a
  2058. // `{ width: 5 }` literal resolves to nothing → no edges); fan-out capped.
  2059. const REGISTRY_ASSIGN_RE = /(?:(?:const|let|var)\s+([A-Za-z_$][\w$]*)|((?:this\.)?[A-Za-z_$][\w$]*))\s*=\s*\{/g;
  2060. const REGISTRY_DISPATCH_RE = /(?:\bnew\s+)?((?:this\.)?[A-Za-z_$][\w$]*)\s*\[\s*([A-Za-z_$][\w$.]*)\s*\]\s*(?:\(|\.[A-Za-z_$])/g;
  2061. const REGISTRY_MIN_ENTRIES = 2;
  2062. const REGISTRY_FANOUT_CAP = 40;
  2063. const REGISTRY_CLASS_ENTRY = new Set(['execute', 'run', 'handle', 'perform', 'process', 'call', 'apply', 'dispatch']);
  2064. const REGISTRY_JS_EXT = /\.(?:ts|tsx|js|jsx|mjs|cjs)$/;
  2065. /** From the index of an opening `{`, return the brace-balanced body up to its matching `}`. */
  2066. function braceBody(src: string, openIdx: number): string | null {
  2067. let depth = 0;
  2068. for (let i = openIdx; i < src.length; i++) {
  2069. if (src[i] === '{') depth++;
  2070. else if (src[i] === '}' && --depth === 0) return src.slice(openIdx + 1, i);
  2071. }
  2072. return null;
  2073. }
  2074. /** Top-level `key: Identifier` entries of an object-literal body. DEPTH-AWARE: only depth-0
  2075. * segments are considered, so method-shorthand bodies (`number(a,b){…}`), arrow values
  2076. * (`x: () => …`), and nested objects (`x: { … }`) don't leak their inner `k: v` pairs as
  2077. * bogus handlers. The per-segment anchor (`^… key: Ident …$`) keeps only pure identifier
  2078. * values — a data value (`x: 5`), call, or arrow fails to match. */
  2079. function registryEntryNames(body: string): string[] {
  2080. const segs: string[] = [];
  2081. let depth = 0;
  2082. let start = 0;
  2083. for (let i = 0; i < body.length; i++) {
  2084. const c = body[i];
  2085. if (c === '{' || c === '(' || c === '[') depth++;
  2086. else if (c === '}' || c === ')' || c === ']') depth--;
  2087. else if (c === ',' && depth === 0) { segs.push(body.slice(start, i)); start = i + 1; }
  2088. }
  2089. segs.push(body.slice(start));
  2090. const names: string[] = [];
  2091. for (const seg of segs) {
  2092. const m = /^\s*(?:\[[^\]]+\]|['"]?[\w$]+['"]?)\s*:\s*([A-Za-z_$][\w$]*)\s*$/.exec(seg);
  2093. if (m && m[1]!.length >= 3 && !names.includes(m[1]!)) names.push(m[1]!);
  2094. }
  2095. return names;
  2096. }
  2097. /** Resolve a registered handler name to its callable entry: a function value, or a class's
  2098. * `execute`-like method (preferring the method chained at the dispatch site), else the class. */
  2099. function resolveRegistryHandler(ctx: ResolutionContext, name: string, chained: string | null): Node | null {
  2100. const cands = ctx.getNodesByName(name);
  2101. const fn = cands.find((n) => n.kind === 'function');
  2102. if (fn) return fn;
  2103. const cls = cands.find((n) => n.kind === 'class' || n.kind === 'struct');
  2104. if (cls) {
  2105. const methods = ctx
  2106. .getNodesInFile(cls.filePath)
  2107. .filter((n) => n.kind === 'method' && n.startLine >= cls.startLine && n.startLine <= (cls.endLine ?? cls.startLine));
  2108. const want = chained && REGISTRY_CLASS_ENTRY.has(chained) ? chained : null;
  2109. const entry =
  2110. (want && methods.find((m) => m.name === want)) ||
  2111. methods.find((m) => REGISTRY_CLASS_ENTRY.has(m.name)) ||
  2112. methods.find((m) => m.name === 'constructor');
  2113. return entry ?? cls;
  2114. }
  2115. // Require a CALLABLE target — a registry dispatched as `reg[k](…)` invokes a function/
  2116. // method, never a data `constant` (dropping it removes false positives like a `{ x: URL }`
  2117. // entry resolving to the global URL constant).
  2118. return cands.find((n) => n.kind === 'method') ?? null;
  2119. }
  2120. async function objectRegistryEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2121. let scannedFiles = 0;
  2122. const edges: Edge[] = [];
  2123. const seen = new Set<string>();
  2124. let scanned = 0;
  2125. for (const file of ctx.getAllFiles()) {
  2126. if ((++scannedFiles & 15) === 0) await onYield();
  2127. if ((++scanned & 255) === 0) await onYield(); // #1091: yield mid-scan on huge graphs
  2128. if (!REGISTRY_JS_EXT.test(file)) continue;
  2129. const content = ctx.readFile(file);
  2130. // Cheap pre-filter: a computed member access BY NAME (`ident[ident`) — the dispatch shape.
  2131. if (!content || !/[\w$]\s*\[\s*[A-Za-z_$]/.test(content)) continue;
  2132. // Skip minified/generated bundles (draco, three.min, base64…): their pervasive `h[x](...)`
  2133. // calls + single-letter `{a:b}` literals are a false-positive minefield. Average line
  2134. // length is the reliable tell — real source ~30–80, minified in the hundreds/thousands.
  2135. const newlines = (content.match(/\n/g)?.length ?? 0) + 1;
  2136. if (content.length / newlines > 200) continue;
  2137. const safe = stripCommentsForRegex(content, /\.(?:jsx?|mjs|cjs)$/.test(file) ? 'javascript' : 'typescript');
  2138. // 1. Dispatch sites: `(new )?<ref>[<ident-key>]` followed by a call or a chained method.
  2139. // A quoted-string key (`['save']`) does NOT match — that's a static access, not dispatch.
  2140. REGISTRY_DISPATCH_RE.lastIndex = 0;
  2141. const dispatches: Array<{ ref: string; line: number; chained: string | null }> = [];
  2142. let dm: RegExpExecArray | null;
  2143. while ((dm = REGISTRY_DISPATCH_RE.exec(safe))) {
  2144. const win = safe.slice(dm.index, dm.index + 160);
  2145. const cm = /\]\s*\([^)]*\)\s*\.\s*([A-Za-z_$][\w$]*)/.exec(win) || /\]\s*\.\s*([A-Za-z_$][\w$]*)/.exec(win);
  2146. dispatches.push({ ref: dm[1]!, line: safe.slice(0, dm.index).split('\n').length, chained: cm ? cm[1]! : null });
  2147. }
  2148. if (!dispatches.length) continue;
  2149. // Normalize a leading `this.` so a class FIELD-INITIALIZER registry (`commands = {…}`)
  2150. // matches a `this.commands[k]` dispatch, not just the constructor form `this.commands = {…}`.
  2151. const norm = (r: string) => r.replace(/^this\./, '');
  2152. const refs = new Set(dispatches.map((d) => norm(d.ref)));
  2153. // 2. Registries: an object literal assigned to a dispatched ref, ≥2 entries resolving to callables.
  2154. REGISTRY_ASSIGN_RE.lastIndex = 0;
  2155. const registries = new Map<string, { names: string[]; line: number }>();
  2156. let am: RegExpExecArray | null;
  2157. while ((am = REGISTRY_ASSIGN_RE.exec(safe))) {
  2158. const lhs = norm(am[1] ?? am[2]!);
  2159. if (!refs.has(lhs) || registries.has(lhs)) continue;
  2160. const body = braceBody(safe, am.index + am[0].length - 1);
  2161. if (!body) continue;
  2162. const names = registryEntryNames(body); // depth-0 `key: Identifier` entries only
  2163. if (names.length >= REGISTRY_MIN_ENTRIES) {
  2164. registries.set(lhs, { names, line: safe.slice(0, am.index).split('\n').length });
  2165. }
  2166. }
  2167. if (!registries.size) continue;
  2168. // 3. Link each dispatcher → each registered handler's callable entry.
  2169. const nodesInFile = ctx.getNodesInFile(file);
  2170. for (const d of dispatches) {
  2171. const reg = registries.get(norm(d.ref));
  2172. if (!reg) continue;
  2173. const disp = enclosingFn(nodesInFile, d.line);
  2174. if (!disp) continue;
  2175. let added = 0;
  2176. for (const name of reg.names) {
  2177. if (added >= REGISTRY_FANOUT_CAP) break;
  2178. const target = resolveRegistryHandler(ctx, name, d.chained);
  2179. if (!target || target.id === disp.id) continue;
  2180. const key = `${disp.id}>${target.id}`;
  2181. if (seen.has(key)) continue;
  2182. seen.add(key);
  2183. edges.push({
  2184. source: disp.id,
  2185. target: target.id,
  2186. kind: 'calls',
  2187. line: d.line,
  2188. provenance: 'heuristic',
  2189. metadata: { synthesizedBy: 'object-registry', via: name, registeredAt: `${file}:${reg.line}` },
  2190. });
  2191. added++;
  2192. }
  2193. }
  2194. }
  2195. return edges;
  2196. }
  2197. // ── RTK Query generated-hook → endpoint ──────────────────────────────────────
  2198. // RTK Query generates one `useGetXQuery`/`useUpdateYMutation` hook per endpoint
  2199. // (`createApi({ endpoints: b => ({ getX: b.query(...) }) })`). Components call the
  2200. // hook; the fetch logic lives in the endpoint's queryFn. The hook↔endpoint link is
  2201. // pure NAMING CONVENTION (no static edge): strip `use` + the optional `Lazy`
  2202. // variant + the `Query|Mutation` suffix, lowercase the head → the endpoint key.
  2203. // Both are extracted as function nodes (the hook from its `export const {…}=api`
  2204. // binding, carrying a sentinel signature; the endpoint from the createApi object),
  2205. // so bridging hook→endpoint connects `component → useGetXQuery → getX → queryFn`.
  2206. // Gated on the extraction sentinel so it only ever fires on genuinely-generated
  2207. // hooks (never a hand-written `useFooQuery`), and on a SAME-FILE endpoint (RTK
  2208. // colocates the hooks and their api in one module) — 0 on any non-RTK repo.
  2209. const RTK_HOOK_DERIVE_RE = /^use([A-Z][A-Za-z0-9]*?)(?:Query|Mutation)$/;
  2210. // MUST match the signature set in tree-sitter.ts `extractRtkHookBindings`.
  2211. const RTK_GENERATED_HOOK_SIGNATURE = '= RTK Query generated hook';
  2212. /** Derive the endpoint key from a generated-hook name (`useLazyGetRecordsQuery`
  2213. * → `getRecords`), or null if it doesn't fit the convention. */
  2214. function rtkEndpointNameFromHook(hook: string): string | null {
  2215. const m = RTK_HOOK_DERIVE_RE.exec(hook);
  2216. if (!m) return null;
  2217. let mid = m[1]!;
  2218. if (mid.startsWith('Lazy')) mid = mid.slice(4); // useLazyGetX → getX (same endpoint)
  2219. if (!mid) return null;
  2220. return mid.charAt(0).toLowerCase() + mid.slice(1);
  2221. }
  2222. async function rtkQueryEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2223. let scanned255 = 0;
  2224. const edges: Edge[] = [];
  2225. const seen = new Set<string>();
  2226. for (const hook of queries.iterateNodesByKind('function')) {
  2227. if ((++scanned255 & 63) === 0) await onYield();
  2228. // Only our extracted generated-hook bindings (sentinel) — not a real hook fn.
  2229. if (hook.signature !== RTK_GENERATED_HOOK_SIGNATURE) continue;
  2230. const endpointName = rtkEndpointNameFromHook(hook.name);
  2231. if (!endpointName) continue;
  2232. // The endpoint is a same-file function by the derived name (RTK colocates the
  2233. // api definition and its generated-hook exports in one module).
  2234. const target = ctx
  2235. .getNodesByName(endpointName)
  2236. .find((n) => n.kind === 'function' && n.filePath === hook.filePath);
  2237. if (!target || target.id === hook.id) continue;
  2238. const key = `${hook.id}>${target.id}`;
  2239. if (seen.has(key)) continue;
  2240. seen.add(key);
  2241. edges.push({
  2242. source: hook.id,
  2243. target: target.id,
  2244. kind: 'calls',
  2245. line: hook.startLine,
  2246. provenance: 'heuristic',
  2247. metadata: { synthesizedBy: 'rtk-query', via: endpointName, registeredAt: `${hook.filePath}:${hook.startLine}` },
  2248. });
  2249. }
  2250. return edges;
  2251. }
  2252. // ── Pinia useStore().action() dispatch bridge ────────────────────────────────
  2253. // A Pinia store factory `export const useXStore = defineStore(...)` exposes its
  2254. // actions as methods on the store instance; a consumer does `const s = useXStore()`
  2255. // then `s.action()`. The call is a method-on-instance with no static edge to the
  2256. // action (which lives in the store's module). Bridge it: map each factory → its
  2257. // file, bind `const <var> = useXStore()` per consumer file, and link the enclosing
  2258. // function → the `<var>.method()` action node IN THE STORE'S FILE. The same-store-
  2259. // file gate keeps it precise (a Pinia built-in like `$patch` or an unrelated
  2260. // same-named method resolves to nothing). Covers both the options and setup store
  2261. // forms uniformly (the action is a function node in the store file either way).
  2262. const PINIA_CONSUMER_EXT = /\.(?:ts|tsx|js|jsx|mjs|cjs|vue)$/;
  2263. const PINIA_FACTORY_RE = /\b(?:export\s+)?const\s+(\w+)\s*=\s*defineStore\s*\(/g;
  2264. const PINIA_BIND_RE = /\bconst\s+(\w+)\s*=\s*(?:await\s+)?(\w+)\s*\(/g;
  2265. const PINIA_CALL_RE = /(\w+)\s*\.\s*(\w+)\s*\(/g;
  2266. const PINIA_FANOUT_CAP = 80;
  2267. async function piniaStoreEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2268. let scannedFiles = 0;
  2269. // 1. Map each `const useXStore = defineStore(...)` factory → its store file.
  2270. const factoryFile = new Map<string, string>();
  2271. for (const file of ctx.getAllFiles()) {
  2272. if ((++scannedFiles & 15) === 0) await onYield();
  2273. if (!PINIA_CONSUMER_EXT.test(file)) continue;
  2274. const content = ctx.readFile(file);
  2275. if (!content || !content.includes('defineStore')) continue;
  2276. PINIA_FACTORY_RE.lastIndex = 0;
  2277. let m: RegExpExecArray | null;
  2278. while ((m = PINIA_FACTORY_RE.exec(content))) factoryFile.set(m[1]!, file);
  2279. }
  2280. if (!factoryFile.size) return [];
  2281. const edges: Edge[] = [];
  2282. const seen = new Set<string>();
  2283. for (const file of ctx.getAllFiles()) {
  2284. if ((++scannedFiles & 15) === 0) await onYield();
  2285. if (!PINIA_CONSUMER_EXT.test(file)) continue;
  2286. const content = ctx.readFile(file);
  2287. if (!content || !content.includes('Store')) continue;
  2288. const safe = stripCommentsForRegex(content, /\.(?:jsx?|mjs|cjs)$/.test(file) ? 'javascript' : 'typescript');
  2289. // 2. Bind store vars in this file: `const <var> = <known-factory>(...)`.
  2290. const varStore = new Map<string, string>();
  2291. PINIA_BIND_RE.lastIndex = 0;
  2292. let bm: RegExpExecArray | null;
  2293. while ((bm = PINIA_BIND_RE.exec(safe))) {
  2294. const sf = factoryFile.get(bm[2]!);
  2295. if (sf) varStore.set(bm[1]!, sf);
  2296. }
  2297. if (!varStore.size) continue;
  2298. // 3. Link `<var>.<method>(` → the action function node in the store's file.
  2299. const nodesInFile = ctx.getNodesInFile(file);
  2300. const fallbackDispatcher = nodesInFile.find((n) => n.kind === 'component'); // .vue top-level setup
  2301. PINIA_CALL_RE.lastIndex = 0;
  2302. let cm: RegExpExecArray | null;
  2303. let added = 0;
  2304. while ((cm = PINIA_CALL_RE.exec(safe)) && added < PINIA_FANOUT_CAP) {
  2305. const storeFile = varStore.get(cm[1]!);
  2306. if (!storeFile) continue;
  2307. const method = cm[2]!;
  2308. const line = safe.slice(0, cm.index).split('\n').length;
  2309. const disp = enclosingFn(nodesInFile, line) ?? fallbackDispatcher;
  2310. if (!disp) continue;
  2311. const target = ctx
  2312. .getNodesByName(method)
  2313. .find((n) => n.kind === 'function' && n.filePath === storeFile);
  2314. if (!target || target.id === disp.id) continue;
  2315. const key = `${disp.id}>${target.id}`;
  2316. if (seen.has(key)) continue;
  2317. seen.add(key);
  2318. edges.push({
  2319. source: disp.id,
  2320. target: target.id,
  2321. kind: 'calls',
  2322. line,
  2323. provenance: 'heuristic',
  2324. metadata: { synthesizedBy: 'pinia-store', via: method, registeredAt: `${file}:${line}` },
  2325. });
  2326. added++;
  2327. }
  2328. }
  2329. return edges;
  2330. }
  2331. // ── Vuex string-keyed dispatch / commit bridge ───────────────────────────────
  2332. // Vuex dispatches actions/mutations by a runtime STRING key: `dispatch('user/login')`
  2333. // / `commit('SET_TOKEN')` / `this.$store.dispatch('app/toggleDevice')`. The action
  2334. // & mutation definitions are object-literal methods in store module files (now
  2335. // extracted as function nodes). Bridge the string key to its node: the LAST `/`
  2336. // segment is the action/mutation name; the preceding segment is the namespace
  2337. // (≈ the store module's file). Resolve the name to a function node IN A STORE FILE
  2338. // (the store-file gate excludes a same-named `api/` helper — `getInfo`/`login`
  2339. // commonly collide), disambiguated by the namespace appearing in the path (or, for
  2340. // a root key, the same file — Vuex's local-module `commit('M')` inside an action).
  2341. const VUEX_DISPATCH_RE = /\b(?:dispatch|commit)\s*\(\s*['"]([A-Za-z][\w/]*)['"]/g;
  2342. const VUEX_STORE_SIGNAL = /\bdefineStore\b|\bcreateStore\b|\bVuex\b|\bmutations\b|\bactions\b|\bgetters\b|\bnamespaced\b/g;
  2343. const VUEX_FANOUT_CAP = 120;
  2344. /** A path segment (dir or filename stem) equals `seg` — `…/modules/user.js` has
  2345. * the segment `user` for namespace `user`. */
  2346. function pathHasSegment(filePath: string, seg: string): boolean {
  2347. return new RegExp('[\\\\/]' + seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '[\\\\/.]').test(filePath);
  2348. }
  2349. async function vuexDispatchEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2350. let scannedFiles = 0;
  2351. const storeFileCache = new Map<string, boolean>();
  2352. const isStoreFile = (file: string): boolean => {
  2353. let v = storeFileCache.get(file);
  2354. if (v === undefined) {
  2355. const c = ctx.readFile(file);
  2356. const seen = new Set<string>();
  2357. if (c) {
  2358. VUEX_STORE_SIGNAL.lastIndex = 0;
  2359. let sm: RegExpExecArray | null;
  2360. while ((sm = VUEX_STORE_SIGNAL.exec(c))) { seen.add(sm[0]); if (seen.size >= 2) break; }
  2361. }
  2362. v = seen.size >= 2;
  2363. storeFileCache.set(file, v);
  2364. }
  2365. return v;
  2366. };
  2367. const resolve = (key: string, dispatchFile: string): Node | null => {
  2368. const segs = key.split('/');
  2369. const action = segs[segs.length - 1]!;
  2370. const cands = ctx.getNodesByName(action).filter((n) => n.kind === 'function' && isStoreFile(n.filePath));
  2371. if (!cands.length) return null;
  2372. if (segs.length > 1) {
  2373. const mod = segs[segs.length - 2]!; // immediate namespace ≈ the module file
  2374. return cands.find((c) => pathHasSegment(c.filePath, mod)) ?? (cands.length === 1 ? cands[0]! : null);
  2375. }
  2376. // Root key: a local `commit('M')` inside an action targets the same module file;
  2377. // otherwise accept only an unambiguous single store-wide match.
  2378. return cands.find((c) => c.filePath === dispatchFile) ?? (cands.length === 1 ? cands[0]! : null);
  2379. };
  2380. const edges: Edge[] = [];
  2381. const seen = new Set<string>();
  2382. for (const file of ctx.getAllFiles()) {
  2383. if ((++scannedFiles & 15) === 0) await onYield();
  2384. if (!PINIA_CONSUMER_EXT.test(file)) continue;
  2385. const content = ctx.readFile(file);
  2386. if (!content || (!content.includes('dispatch(') && !content.includes('commit('))) continue;
  2387. const safe = stripCommentsForRegex(content, /\.(?:jsx?|mjs|cjs)$/.test(file) ? 'javascript' : 'typescript');
  2388. const nodesInFile = ctx.getNodesInFile(file);
  2389. const fallback = nodesInFile.find((n) => n.kind === 'component'); // .vue top-level
  2390. VUEX_DISPATCH_RE.lastIndex = 0;
  2391. let m: RegExpExecArray | null;
  2392. let added = 0;
  2393. while ((m = VUEX_DISPATCH_RE.exec(safe)) && added < VUEX_FANOUT_CAP) {
  2394. const key = m[1]!;
  2395. const line = safe.slice(0, m.index).split('\n').length;
  2396. const disp = enclosingFn(nodesInFile, line) ?? fallback;
  2397. if (!disp) continue;
  2398. const target = resolve(key, file);
  2399. if (!target || target.id === disp.id) continue;
  2400. const edgeKey = `${disp.id}>${target.id}`;
  2401. if (seen.has(edgeKey)) continue;
  2402. seen.add(edgeKey);
  2403. edges.push({
  2404. source: disp.id,
  2405. target: target.id,
  2406. kind: 'calls',
  2407. line,
  2408. provenance: 'heuristic',
  2409. metadata: { synthesizedBy: 'vuex-dispatch', via: key, registeredAt: `${file}:${line}` },
  2410. });
  2411. added++;
  2412. }
  2413. }
  2414. return edges;
  2415. }
  2416. // ── Celery task dispatch (Python) ─────────────────────────────────────────────
  2417. // Celery decouples a task's call site from its body through async dispatch:
  2418. // # tasks.py
  2419. // @shared_task # also @app.task / @celery_app.task / @<app>.task / @task
  2420. // def process(account_ids): ...
  2421. // # views.py — a DIFFERENT module
  2422. // process.apply_async(kwargs={...}) # or process.delay(...) — dynamic, no static edge
  2423. // Bridge it: link the enclosing function/method at each `.delay(`/`.apply_async(` site → the
  2424. // task function body. Precision rests on the DECORATOR gate — the dispatched name must resolve
  2425. // to a Python function carrying a celery task decorator (read from the source lines above its
  2426. // `def`, since the def's own startLine excludes the decorator). A `.delay()` on a non-task
  2427. // object resolves to no task node → no edge, so a Celery-free repo yields 0. Same-file /
  2428. // unique-candidate disambiguation like vuex. (Canvas forms — `group(t).delay()`, `t.s()`/`.si()`
  2429. // — have no single identifier before `.delay`/`.apply_async`, so they're skipped, not mis-bridged.)
  2430. const CELERY_DISPATCH_RE = /\b([A-Za-z_]\w*)\s*\.\s*(?:delay|apply_async)\s*\(/g;
  2431. // A task decorator: bare `@shared_task`/`@task` or attribute `@app.task`/`@celery_app.task`,
  2432. // each optionally called with args. `\b`-bounded and `@`-anchored so `@mytask`, or a symbol
  2433. // merely named `task`, can't match. No `/g`, so `.test()` is stateless across reuse.
  2434. const CELERY_TASK_DECORATOR_RE = /@\s*(?:[A-Za-z_][\w.]*\.)?(?:shared_task|task)\b/;
  2435. const CELERY_PY_EXT = /\.py$/;
  2436. const CELERY_FANOUT_CAP = 80;
  2437. const CELERY_DECORATOR_LOOKBACK = 12; // max lines above a `def` to scan for its decorators
  2438. async function celeryDispatchEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2439. let scannedFiles = 0;
  2440. // Memoize the decorator check per task-candidate node: it reads the file and scans a few
  2441. // lines above the def. Only called on names that are actually `.delay`/`.apply_async`
  2442. // receivers, so the candidate set stays small.
  2443. const taskCache = new Map<string, boolean>();
  2444. const isCeleryTask = (node: Node): boolean => {
  2445. let v = taskCache.get(node.id);
  2446. if (v !== undefined) return v;
  2447. v = false;
  2448. if (node.kind === 'function' && CELERY_PY_EXT.test(node.filePath)) {
  2449. const content = ctx.readFile(node.filePath);
  2450. if (content) {
  2451. const lines = content.split('\n');
  2452. // startLine is the `def` line (decorators sit ABOVE it). Walk upward, stopping at the
  2453. // previous declaration so a non-task def can never inherit the prior def's decorator.
  2454. const stop = Math.max(0, node.startLine - 1 - CELERY_DECORATOR_LOOKBACK);
  2455. for (let i = node.startLine - 2; i >= stop; i--) {
  2456. const t = (lines[i] ?? '').trim();
  2457. if (/^(?:async\s+def|def|class)\b/.test(t)) break; // previous decl → stop
  2458. if (CELERY_TASK_DECORATOR_RE.test(t)) { v = true; break; }
  2459. }
  2460. }
  2461. }
  2462. taskCache.set(node.id, v);
  2463. return v;
  2464. };
  2465. const resolve = (name: string, dispatchFile: string): Node | null => {
  2466. const cands = ctx.getNodesByName(name).filter((n) => n.kind === 'function' && isCeleryTask(n));
  2467. if (!cands.length) return null;
  2468. if (cands.length === 1) return cands[0]!;
  2469. // Cross-module name collision: prefer a task defined in the dispatching file, else bail
  2470. // (ambiguous — precision over recall, like vuex's root-key resolution).
  2471. return cands.find((c) => c.filePath === dispatchFile) ?? null;
  2472. };
  2473. const edges: Edge[] = [];
  2474. const seen = new Set<string>();
  2475. for (const file of ctx.getAllFiles()) {
  2476. if ((++scannedFiles & 15) === 0) await onYield();
  2477. if (!CELERY_PY_EXT.test(file)) continue;
  2478. const content = ctx.readFile(file);
  2479. if (!content || (!content.includes('.delay(') && !content.includes('.apply_async('))) continue;
  2480. const safe = stripCommentsForRegex(content, 'python');
  2481. const nodesInFile = ctx.getNodesInFile(file);
  2482. CELERY_DISPATCH_RE.lastIndex = 0;
  2483. let m: RegExpExecArray | null;
  2484. let added = 0;
  2485. while ((m = CELERY_DISPATCH_RE.exec(safe)) && added < CELERY_FANOUT_CAP) {
  2486. const name = m[1]!;
  2487. const line = safe.slice(0, m.index).split('\n').length;
  2488. const disp = enclosingFn(nodesInFile, line);
  2489. if (!disp) continue; // module-level dispatch — no source symbol to attribute
  2490. const target = resolve(name, file);
  2491. if (!target || target.id === disp.id) continue;
  2492. const key = `${disp.id}>${target.id}`;
  2493. if (seen.has(key)) continue;
  2494. seen.add(key);
  2495. edges.push({
  2496. source: disp.id,
  2497. target: target.id,
  2498. kind: 'calls',
  2499. line,
  2500. provenance: 'heuristic',
  2501. metadata: { synthesizedBy: 'celery-dispatch', via: name, registeredAt: `${file}:${line}` },
  2502. });
  2503. added++;
  2504. }
  2505. }
  2506. return edges;
  2507. }
  2508. // ── Spring application events (Java) ──────────────────────────────────────────
  2509. // Spring decouples an event PUBLISHER from its LISTENER(s) through the application
  2510. // event bus, linked by the EVENT TYPE (not a name):
  2511. // // SomeService.java
  2512. // eventPublisher.publishEvent(new PasswordChangedEvent(this, username)); // publish
  2513. // // RememberMeTokenRevoker.java — a DIFFERENT file
  2514. // @EventListener(PasswordChangedEvent.class) // listen
  2515. // public void onPasswordChanged(PasswordChangedEvent event) { ... }
  2516. // Bridge it: link the enclosing method at each `publishEvent(new XEvent(...))` site →
  2517. // every listener method of XEvent. Listeners are `@EventListener` / `@TransactionalEventListener`
  2518. // methods (event type = the first param type, or the `@EventListener(X.class)` value form) and
  2519. // the older `class … implements ApplicationListener<X> { void onApplicationEvent(X e) }`. Keyed
  2520. // by exact type name, usually cross-file. A repo with no `@EventListener`/`publishEvent` yields 0.
  2521. // (Java method nodes INCLUDE their leading annotations in the range — startLine is the first
  2522. // `@…` line — so the annotation block is scanned DOWNWARD from startLine, bounded to consecutive
  2523. // `@`-lines so it can't bleed into an adjacent method.)
  2524. const SPRING_PUBLISH_RE = /\.publishEvent\s*\(\s*new\s+([A-Z][A-Za-z0-9_]*)/g;
  2525. const SPRING_LISTENER_ANNO_RE = /@(?:EventListener|TransactionalEventListener)\b/;
  2526. const SPRING_ANNO_TYPE_RE = /@(?:EventListener|TransactionalEventListener)\s*\(\s*([A-Z][A-Za-z0-9_]*)\.class/;
  2527. const SPRING_APP_LISTENER_RE = /\bApplicationListener\s*</;
  2528. const SPRING_JAVA_EXT = /\.java$/;
  2529. const SPRING_FANOUT_CAP = 80;
  2530. /** The first parameter's type from a Java method `signature` (`"void (XEvent e)"` → `XEvent`).
  2531. * Skips a leading `final`/`@Anno`, strips generics, and requires a PascalCase class name (event
  2532. * types are classes) — so a no-arg or primitive-param method yields null. */
  2533. function springFirstParamType(sig: string | undefined): string | null {
  2534. if (!sig) return null;
  2535. const open = sig.indexOf('(');
  2536. if (open < 0) return null;
  2537. const close = sig.indexOf(')', open);
  2538. const inner = sig.slice(open + 1, close < 0 ? sig.length : close).trim();
  2539. if (!inner) return null;
  2540. const first = inner.split(',')[0]!.trim();
  2541. const toks = first.split(/\s+/).filter((t) => t && t !== 'final' && !t.startsWith('@'));
  2542. if (toks.length < 2) return null; // need `Type name`
  2543. const type = toks[toks.length - 2]!.replace(/<.*$/, ''); // drop generic args
  2544. return /^[A-Z][A-Za-z0-9_]*$/.test(type) ? type : null;
  2545. }
  2546. async function springEventEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2547. let scannedFiles = 0;
  2548. // Pass 1 — event-type → listener methods, scanning only event-relevant files.
  2549. // This is the ONLY full read sweep: publisher files are recorded here so
  2550. // pass 2 re-reads just those instead of every .java file again (#1212 —
  2551. // the double full-repo read was one of the tail's longest unyielded spans).
  2552. const listeners = new Map<string, Node[]>();
  2553. const publisherFiles: string[] = [];
  2554. for (const file of ctx.getAllFiles()) {
  2555. if ((++scannedFiles & 15) === 0) await onYield();
  2556. if (!SPRING_JAVA_EXT.test(file)) continue;
  2557. const content = ctx.readFile(file);
  2558. if (!content) continue;
  2559. if (content.includes('.publishEvent(')) publisherFiles.push(file);
  2560. const hasAnno = content.includes('@EventListener') || content.includes('@TransactionalEventListener');
  2561. const hasAppListener = SPRING_APP_LISTENER_RE.test(content);
  2562. if (!hasAnno && !hasAppListener) continue;
  2563. const lines = content.split('\n');
  2564. for (const node of ctx.getNodesInFile(file)) {
  2565. if (node.kind !== 'method') continue;
  2566. // Collect this method's own leading annotation block (consecutive `@`-lines from startLine).
  2567. const annoLines: string[] = [];
  2568. for (let i = node.startLine - 1; i < lines.length && i < node.startLine + 7; i++) {
  2569. const t = (lines[i] ?? '').trim();
  2570. if (!t.startsWith('@')) break; // reached the declaration → stop (no bleed into next method)
  2571. annoLines.push(t);
  2572. }
  2573. const head = annoLines.join('\n');
  2574. const annotated = hasAnno && SPRING_LISTENER_ANNO_RE.test(head);
  2575. const isAppListener = hasAppListener && node.name === 'onApplicationEvent';
  2576. if (!annotated && !isAppListener) continue;
  2577. let type = springFirstParamType(node.signature);
  2578. if (!type && annotated) {
  2579. const m = SPRING_ANNO_TYPE_RE.exec(head);
  2580. if (m) type = m[1]!;
  2581. }
  2582. if (!type) continue;
  2583. let arr = listeners.get(type);
  2584. if (!arr) { arr = []; listeners.set(type, arr); }
  2585. arr.push(node);
  2586. }
  2587. }
  2588. if (!listeners.size) return [];
  2589. // Pass 2 — link each publishEvent(new XEvent(...)) site → every listener of
  2590. // XEvent. Only the publisher files recorded in pass 1 are (re-)read.
  2591. const edges: Edge[] = [];
  2592. const seen = new Set<string>();
  2593. for (const file of publisherFiles) {
  2594. if ((++scannedFiles & 15) === 0) await onYield();
  2595. const content = ctx.readFile(file);
  2596. if (!content || !content.includes('.publishEvent(')) continue;
  2597. const safe = stripCommentsForRegex(content, 'java');
  2598. const nodesInFile = ctx.getNodesInFile(file);
  2599. SPRING_PUBLISH_RE.lastIndex = 0;
  2600. let m: RegExpExecArray | null;
  2601. let added = 0;
  2602. while ((m = SPRING_PUBLISH_RE.exec(safe)) && added < SPRING_FANOUT_CAP) {
  2603. const targets = listeners.get(m[1]!);
  2604. if (!targets || !targets.length) continue;
  2605. const line = safe.slice(0, m.index).split('\n').length;
  2606. const disp = enclosingFn(nodesInFile, line);
  2607. if (!disp) continue;
  2608. for (const target of targets) {
  2609. if (target.id === disp.id) continue;
  2610. const key = `${disp.id}>${target.id}`;
  2611. if (seen.has(key)) continue;
  2612. seen.add(key);
  2613. edges.push({
  2614. source: disp.id,
  2615. target: target.id,
  2616. kind: 'calls',
  2617. line,
  2618. provenance: 'heuristic',
  2619. metadata: { synthesizedBy: 'spring-event', via: m[1]!, registeredAt: `${file}:${line}` },
  2620. });
  2621. added++;
  2622. }
  2623. }
  2624. }
  2625. return edges;
  2626. }
  2627. // ── MediatR request/notification dispatch (C#/.NET) ───────────────────────────
  2628. // MediatR decouples a Send/Publish call site from its Handle method through a mediator,
  2629. // linked by the request/notification TYPE (the IRequestHandler<T,…> generic):
  2630. // // CancelOrderCommandHandler.cs — the handler
  2631. // public class CancelOrderCommandHandler : IRequestHandler<CancelOrderCommand, bool> {
  2632. // public async Task<bool> Handle(CancelOrderCommand request, CancellationToken ct) { … }
  2633. // // some controller — the dispatch (usually a DIFFERENT file)
  2634. // var command = new CancelOrderCommand(orderId); await _mediator.Send(command);
  2635. // Bridge it: link the enclosing method at each mediator `.Send(x)`/`.Publish(x)` site → the
  2636. // `Handle` method of the handler for x's type. The sent type is resolved from the argument —
  2637. // inline `new X(…)`, a local `var v = new X(…)`, or a parameter/local declared `X v` — bounded
  2638. // to the enclosing method. Precision rests on TWO gates: the receiver must be mediator-ish
  2639. // (`mediator`/`sender`/`publisher`, so MAUI `MessagingCenter.Send` is ignored) AND the resolved
  2640. // type must be a known handler request type (so a same-named non-request DTO is never bridged).
  2641. // C# has no `signature` on method nodes, so the handler's request type is read from the class
  2642. // base-list source (`: IRequestHandler<X,…>`), not a param signature.
  2643. const MEDIATR_HANDLER_BASE_RE = /(?:IRequestHandler|INotificationHandler)\s*<\s*([A-Za-z_]\w*)/;
  2644. const MEDIATR_DISPATCH_RE = /([A-Za-z_][\w.]*)\s*\.\s*(?:Send|Publish)\s*\(\s*(new\s+[A-Z]\w*|[A-Za-z_]\w*)/g;
  2645. const MEDIATR_RECEIVER_RE = /(?:mediator|sender|publisher)/i;
  2646. const MEDIATR_CS_EXT = /\.cs$/;
  2647. const MEDIATR_FANOUT_CAP = 80;
  2648. const MEDIATR_HANDLER_DECL_LOOKAHEAD = 4; // lines from a class startLine to find a wrapped base list
  2649. /** The type sent at a MediatR `.Send(arg)`/`.Publish(arg)` site: an inline `new X(…)`, else
  2650. * `arg` as an identifier resolved within the enclosing method — a `… arg = new X(…)` assignment
  2651. * (wins), or a parameter/local declared `X arg`. Returns null when the type can't be seen. */
  2652. function resolveMediatrArgType(arg: string, lines: string[], methodStart: number, dispatchLine: number): string | null {
  2653. const inl = /^new\s+([A-Z]\w*)/.exec(arg);
  2654. if (inl) return inl[1]!;
  2655. if (!/^[A-Za-z_]\w*$/.test(arg)) return null;
  2656. const assignRe = new RegExp(`\\b${arg}\\b\\s*=\\s*new\\s+([A-Z]\\w*)`);
  2657. const declRe = new RegExp(`\\b([A-Z]\\w*)\\b\\s+${arg}\\b`);
  2658. let declType: string | null = null;
  2659. for (let i = Math.max(0, methodStart - 1); i < dispatchLine && i < lines.length; i++) {
  2660. const ln = lines[i] ?? '';
  2661. const a = assignRe.exec(ln);
  2662. if (a) return a[1]!; // an explicit `arg = new X` is the most specific — take it
  2663. if (!declType) {
  2664. const d = declRe.exec(ln);
  2665. if (d) declType = d[1]!; // a `X arg` declaration — remember, but keep scanning for an assignment
  2666. }
  2667. }
  2668. return declType;
  2669. }
  2670. async function mediatrDispatchEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2671. let scannedFiles = 0;
  2672. // Pass 1 — request/notification type → the Handle method of each handler class.
  2673. const handlers = new Map<string, Node[]>();
  2674. for (const file of ctx.getAllFiles()) {
  2675. if ((++scannedFiles & 15) === 0) await onYield();
  2676. if (!MEDIATR_CS_EXT.test(file)) continue;
  2677. const content = ctx.readFile(file);
  2678. if (!content || (!content.includes('IRequestHandler<') && !content.includes('INotificationHandler<'))) continue;
  2679. const lines = content.split('\n');
  2680. const nodesInFile = ctx.getNodesInFile(file);
  2681. for (const cls of nodesInFile) {
  2682. if (cls.kind !== 'class') continue;
  2683. const decl = lines.slice(cls.startLine - 1, cls.startLine - 1 + MEDIATR_HANDLER_DECL_LOOKAHEAD).join('\n');
  2684. const m = MEDIATR_HANDLER_BASE_RE.exec(decl);
  2685. if (!m) continue;
  2686. const type = m[1]!;
  2687. const end = cls.endLine ?? cls.startLine;
  2688. const handle = nodesInFile.find(
  2689. (n) => n.kind === 'method' && n.name === 'Handle' && n.startLine >= cls.startLine && n.startLine <= end
  2690. );
  2691. if (!handle) continue;
  2692. let arr = handlers.get(type);
  2693. if (!arr) { arr = []; handlers.set(type, arr); }
  2694. arr.push(handle);
  2695. }
  2696. }
  2697. if (!handlers.size) return [];
  2698. // Pass 2 — link each mediator-ish .Send(x)/.Publish(x) → the handler of x's type.
  2699. const edges: Edge[] = [];
  2700. const seen = new Set<string>();
  2701. for (const file of ctx.getAllFiles()) {
  2702. if ((++scannedFiles & 15) === 0) await onYield();
  2703. if (!MEDIATR_CS_EXT.test(file)) continue;
  2704. const content = ctx.readFile(file);
  2705. if (!content || (!content.includes('.Send(') && !content.includes('.Publish('))) continue;
  2706. const safe = stripCommentsForRegex(content, 'csharp');
  2707. const safeLines = safe.split('\n');
  2708. const nodesInFile = ctx.getNodesInFile(file);
  2709. MEDIATR_DISPATCH_RE.lastIndex = 0;
  2710. let m: RegExpExecArray | null;
  2711. let added = 0;
  2712. while ((m = MEDIATR_DISPATCH_RE.exec(safe)) && added < MEDIATR_FANOUT_CAP) {
  2713. if (!MEDIATR_RECEIVER_RE.test(m[1]!)) continue; // not a mediator (MessagingCenter, HttpClient, …)
  2714. const line = safe.slice(0, m.index).split('\n').length;
  2715. const disp = enclosingFn(nodesInFile, line);
  2716. if (!disp) continue;
  2717. const type = resolveMediatrArgType(m[2]!, safeLines, disp.startLine, line);
  2718. if (!type) continue;
  2719. const targets = handlers.get(type);
  2720. if (!targets) continue;
  2721. for (const target of targets) {
  2722. if (target.id === disp.id) continue;
  2723. const key = `${disp.id}>${target.id}`;
  2724. if (seen.has(key)) continue;
  2725. seen.add(key);
  2726. edges.push({
  2727. source: disp.id,
  2728. target: target.id,
  2729. kind: 'calls',
  2730. line,
  2731. provenance: 'heuristic',
  2732. metadata: { synthesizedBy: 'mediatr-dispatch', via: type, registeredAt: `${file}:${line}` },
  2733. });
  2734. added++;
  2735. }
  2736. }
  2737. }
  2738. return edges;
  2739. }
  2740. // ── Sidekiq job dispatch (Ruby) ───────────────────────────────────────────────
  2741. // Sidekiq decouples a job's enqueue site from the worker's `perform`, linked by the WORKER
  2742. // CLASS NAME:
  2743. // # app/workers/destroy_user_worker.rb
  2744. // class DestroyUserWorker
  2745. // include Sidekiq::Worker # or Sidekiq::Job (the modern alias)
  2746. // def perform(user_id) … end
  2747. // # app/services/… — a DIFFERENT file
  2748. // DestroyUserWorker.perform_async(user.id) # also .perform_in(t, …) / .perform_at(t, …)
  2749. // Bridge it: link the enclosing method at each `Worker.perform_async/_in/_at(…)` site → that
  2750. // worker's instance `perform`. Name-keyed (like Celery): the receiver class must be a Sidekiq
  2751. // worker — gated by reading `include Sidekiq::Job|Worker` from the class body, since that mixin
  2752. // is an external gem module that forms no resolvable edge. ActiveJob's `perform_later`/`_now` is
  2753. // a different shape and deliberately not matched, so an ActiveJob-only app yields 0.
  2754. const SIDEKIQ_DISPATCH_RE = /([A-Z][A-Za-z0-9_]*(?:::[A-Z][A-Za-z0-9_]*)*)\s*\.\s*perform_(?:async|in|at)\b/g;
  2755. const SIDEKIQ_WORKER_RE = /\binclude\s+Sidekiq::(?:Job|Worker)\b/;
  2756. const SIDEKIQ_RB_EXT = /\.rb$/;
  2757. const SIDEKIQ_FANOUT_CAP = 80;
  2758. async function sidekiqDispatchEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  2759. let scannedFiles = 0;
  2760. // class node id → its instance `perform` method (null if the class isn't a Sidekiq worker),
  2761. // memoized. Reads the class body for the mixin; only consulted for actual dispatch receivers.
  2762. const performCache = new Map<string, Node | null>();
  2763. const performOf = (cls: Node): Node | null => {
  2764. let v = performCache.get(cls.id);
  2765. if (v !== undefined) return v;
  2766. v = null;
  2767. const content = ctx.readFile(cls.filePath);
  2768. if (content) {
  2769. const end = cls.endLine ?? cls.startLine;
  2770. const body = content.split('\n').slice(cls.startLine - 1, end).join('\n');
  2771. if (SIDEKIQ_WORKER_RE.test(body)) {
  2772. v = ctx.getNodesInFile(cls.filePath).find(
  2773. (n) => n.kind === 'method' && n.name === 'perform' && n.startLine >= cls.startLine && n.startLine <= end
  2774. ) ?? null;
  2775. }
  2776. }
  2777. performCache.set(cls.id, v);
  2778. return v;
  2779. };
  2780. // Resolve a (possibly namespaced) worker reference to its `perform`. A namespaced ref is
  2781. // matched by EXACT qualified name first, so same-named workers in different namespaces
  2782. // (forem has four `SendEmailNotificationWorker`s) resolve to the right one; an unqualified
  2783. // ref falls back to the simple name and links only when a single worker bears it — an
  2784. // ambiguous collision bails (precision over recall).
  2785. const resolve = (ref: string): Node | null => {
  2786. if (ref.includes('::')) {
  2787. const q = ctx.getNodesByQualifiedName(ref).find((n) => n.kind === 'class' && performOf(n));
  2788. if (q) return performOf(q);
  2789. }
  2790. const workers = ctx.getNodesByName(ref.split('::').pop()!).filter((n) => n.kind === 'class' && performOf(n));
  2791. return workers.length === 1 ? performOf(workers[0]!) : null;
  2792. };
  2793. const edges: Edge[] = [];
  2794. const seen = new Set<string>();
  2795. for (const file of ctx.getAllFiles()) {
  2796. if ((++scannedFiles & 15) === 0) await onYield();
  2797. if (!SIDEKIQ_RB_EXT.test(file)) continue;
  2798. const content = ctx.readFile(file);
  2799. if (!content || !/\.perform_(?:async|in|at)\b/.test(content)) continue;
  2800. const safe = stripCommentsForRegex(content, 'ruby');
  2801. const nodesInFile = ctx.getNodesInFile(file);
  2802. SIDEKIQ_DISPATCH_RE.lastIndex = 0;
  2803. let m: RegExpExecArray | null;
  2804. let added = 0;
  2805. while ((m = SIDEKIQ_DISPATCH_RE.exec(safe)) && added < SIDEKIQ_FANOUT_CAP) {
  2806. const line = safe.slice(0, m.index).split('\n').length;
  2807. const disp = enclosingFn(nodesInFile, line);
  2808. if (!disp) continue;
  2809. const target = resolve(m[1]!);
  2810. if (!target || target.id === disp.id) continue;
  2811. const key = `${disp.id}>${target.id}`;
  2812. if (seen.has(key)) continue;
  2813. seen.add(key);
  2814. edges.push({
  2815. source: disp.id,
  2816. target: target.id,
  2817. kind: 'calls',
  2818. line,
  2819. provenance: 'heuristic',
  2820. metadata: { synthesizedBy: 'sidekiq-dispatch', via: m[1]!, registeredAt: `${file}:${line}` },
  2821. });
  2822. added++;
  2823. }
  2824. }
  2825. return edges;
  2826. }
  2827. // ── Erlang behaviour-callback dispatch ────────────────────────────────────────
  2828. // An Erlang behaviour is a compile-checked callback contract: the behaviour
  2829. // module declares `-callback init(...) -> ...`, implementers declare
  2830. // `-behaviour(B)` and export the callbacks, and the framework side dispatches
  2831. // through a VARIABLE module — cowboy's `Handler:init(Req, Opts)` and
  2832. // `Middleware:execute(Req, Env)` folds, ejabberd's `Mod:start/2`. Extraction
  2833. // deliberately leaves var-module calls silent (no static target), so the flow
  2834. // breaks at exactly the hop agents ask about (request → handler init). Bridge:
  2835. //
  2836. // dispatch site `Var:fn(args…)` → every in-repo implementer of the behaviour
  2837. // declaring `fn` with the SITE's arity — provided exactly ONE in-repo
  2838. // behaviour declares (fn, arity); a name+arity collision across behaviours
  2839. // bails (silent beats wrong) — and the implementer defines and exports `fn`.
  2840. //
  2841. // Behaviours are discovered by scanning every Erlang file for `-callback`
  2842. // declarations (not just `implements` targets), so a behaviour with zero
  2843. // implementers still participates in the ambiguity gate. Fan-out control: a
  2844. // mega-behaviour (ejabberd's gen_mod, ~200 mod_* implementers) would mint
  2845. // hundreds of edges per site that READ as complete coverage while being
  2846. // arbitrary — above the cap the site is skipped entirely and the boundary
  2847. // stays visibly dynamic (explore's boundary announcer covers it) instead of
  2848. // silently truncated.
  2849. const ERLANG_EXT = /\.(?:erl|hrl)$/;
  2850. // `Var:fn(` — variable (capitalized) module, lowercase function, immediate
  2851. // open-paren. The leading char class rejects `?MODULE:fn(` (macro), `a:b(`
  2852. // (static remote call, already linked), and mid-word matches.
  2853. const ERLANG_DISPATCH_RE = /(^|[^?\w@'])([A-Z][A-Za-z0-9_@]*):([a-z][A-Za-z0-9_@]*)\(/g;
  2854. const ERLANG_CALLBACK_DECL_RE = /(^|\n)\s*-callback\s+('[^'\n]+'|[a-z][A-Za-z0-9_@]*)\s*\(/g;
  2855. const ERLANG_BEHAVIOUR_FANOUT_CAP = 24;
  2856. /**
  2857. * Argument count of the call/declaration whose `(` sits at `openIdx` —
  2858. * top-level commas + 1, `()` → 0, unbalanced/oversized → -1. Skips nested
  2859. * (), [], {}, <<>> content, `"strings"`, `'atoms'`, and `$c` char literals,
  2860. * so `-callback init(fun((a, b) -> ok), #{k => v}) -> ok.` counts 2.
  2861. */
  2862. function erlangArityAt(src: string, openIdx: number): number {
  2863. let depth = 1;
  2864. // `<<1,2,3>>` binary literals: commas inside are element separators, not
  2865. // argument separators. Tracked separately from bracket depth because the
  2866. // single-char `<`/`>` comparison operators must stay inert (#1358).
  2867. let binDepth = 0;
  2868. let commas = 0;
  2869. let sawArg = false;
  2870. const limit = Math.min(src.length, openIdx + 4000);
  2871. for (let i = openIdx + 1; i < limit; i++) {
  2872. const ch = src[i]!;
  2873. if (ch === '"' || ch === "'") {
  2874. i++;
  2875. while (i < limit && src[i] !== ch) {
  2876. if (src[i] === '\\') i++;
  2877. i++;
  2878. }
  2879. sawArg = true;
  2880. continue;
  2881. }
  2882. if (ch === '$') {
  2883. i++;
  2884. if (src[i] === '\\') i++;
  2885. sawArg = true;
  2886. continue;
  2887. }
  2888. if (ch === '<' && src[i + 1] === '<') { binDepth++; i++; sawArg = true; continue; }
  2889. if (ch === '>' && src[i + 1] === '>' && binDepth > 0) { binDepth--; i++; continue; }
  2890. if (ch === '(' || ch === '[' || ch === '{') { depth++; sawArg = true; continue; }
  2891. if (ch === ')' || ch === ']' || ch === '}') {
  2892. depth--;
  2893. if (depth === 0) return sawArg ? commas + 1 : 0;
  2894. continue;
  2895. }
  2896. if (ch === ',' && depth === 1 && binDepth === 0) { commas++; continue; }
  2897. if (!/\s/.test(ch)) sawArg = true;
  2898. }
  2899. return -1;
  2900. }
  2901. /**
  2902. * Nix module-system option wiring. A NixOS/home-manager/nix-darwin option is
  2903. * DECLARED in one module (`options.launchd.user.agents = mkOption { ... }`)
  2904. * and SET in others (`launchd.user.agents.yabai = { ... }` inside a module's
  2905. * config) — the connection happens by option-path unification inside the
  2906. * module-system evaluator, so there is no static call/import edge to follow
  2907. * and flow questions ("how does services.yabai.enable become a launchd
  2908. * service?") go dark at the module boundary.
  2909. *
  2910. * This pass links each config-write binding to the option declaration whose
  2911. * path is the longest static-segment prefix of the write path. Precision gates:
  2912. * - only STATIC segments participate: plain identifiers, plus quoted segments
  2913. * (`"git/config"`, `"com.apple.dock"`) as opaque verbatim tokens that match
  2914. * only quote-exactly; an interpolated (`${name}`) segment ends the prefix,
  2915. * so dynamic paths never match beyond their static head;
  2916. * - matched prefixes must be ≥2 segments: 1-segment paths would wrongly link
  2917. * every package's `meta = { ... }` attrset to nixos's `options.meta`;
  2918. * - a prefix declared in more than one file is ambiguous → no edge (a wrong
  2919. * edge is worse than none);
  2920. * - writes physically inside an options block are declaration internals
  2921. * (types, defaults, examples), never config writes → excluded.
  2922. * Both declaration spellings register: flat (`options.a.b = ...`) by name, and
  2923. * nested (`options = { a.b = ...; }`) by line-span containment.
  2924. */
  2925. function nixLeadingPlainSegments(name: string): string[] {
  2926. const segs: string[] = [];
  2927. let i = 0;
  2928. const n = name.length;
  2929. while (i < n) {
  2930. if (name[i] === '"') {
  2931. // Quoted segment — an opaque verbatim token (quotes kept, so it can
  2932. // never collide with a plain identifier). `NSGlobalDomain."com.apple.
  2933. // mouse.tapBehavior"` must match ITS OWN quoted declaration, not
  2934. // whichever sibling registered the shared plain prefix first.
  2935. let j = i + 1;
  2936. while (j < n && name[j] !== '"') {
  2937. if (name[j] === '\\') j++;
  2938. j++;
  2939. }
  2940. if (j >= n) return segs; // unterminated — stop at the static head
  2941. const tok = name.slice(i, j + 1);
  2942. if (tok.includes('${')) return segs; // interpolated → dynamic → stop
  2943. segs.push(tok);
  2944. i = j + 1;
  2945. if (i >= n) break;
  2946. if (name[i] !== '.') return segs;
  2947. i++;
  2948. continue;
  2949. }
  2950. let j = i;
  2951. while (j < n && name[j] !== '.') {
  2952. if (name[j] === '"' || (name[j] === '$' && name[j + 1] === '{')) return segs;
  2953. j++;
  2954. }
  2955. const seg = name.slice(i, j);
  2956. if (!/^[A-Za-z_][A-Za-z0-9_'-]*$/.test(seg)) return segs;
  2957. segs.push(seg);
  2958. i = j + 1;
  2959. }
  2960. return segs;
  2961. }
  2962. async function nixOptionPathEdges(queries: QueryBuilder, onYield: MaybeYield): Promise<Edge[]> {
  2963. let scanned255 = 0;
  2964. type Rec = { id: string; filePath: string; startLine: number; endLine: number; segs: string[] };
  2965. // One streaming pass over nix bindings (variables + the odd function-valued
  2966. // option); memory stays O(bindings-kept), not O(all nodes) (#610).
  2967. const byFile = new Map<string, Rec[]>();
  2968. let scanned = 0;
  2969. for (const kind of ['variable', 'function'] as NodeKind[]) {
  2970. for (const node of queries.iterateNodesByKind(kind)) {
  2971. if ((++scanned255 & 63) === 0) await onYield();
  2972. if ((++scanned & 0x3fff) === 0 && onYield) await onYield();
  2973. if (node.language !== 'nix') continue;
  2974. const segs = nixLeadingPlainSegments(node.name);
  2975. if (segs.length === 0) continue;
  2976. const rec: Rec = {
  2977. id: node.id,
  2978. filePath: node.filePath,
  2979. startLine: node.startLine,
  2980. endLine: node.endLine,
  2981. segs,
  2982. };
  2983. const arr = byFile.get(node.filePath);
  2984. if (arr) arr.push(rec);
  2985. else byFile.set(node.filePath, [rec]);
  2986. }
  2987. }
  2988. // Per file: walk bindings outermost-first with a stack of active option
  2989. // spans, composing nested declaration paths (`options = { services.foo = {
  2990. // enable = mkOption ...; }; }` registers services.foo AND services.foo.enable).
  2991. // An `options` binding nested inside another option span is a SUBMODULE's
  2992. // own namespace (`attrsOf (submodule { options = ...; })`) — its internals
  2993. // are not globally addressable, so the sentinel blocks registration below it
  2994. // while still excluding the region from write candidates.
  2995. const SUBMODULE = '\u0000submodule';
  2996. const decls = new Map<string, Rec[]>();
  2997. const writes: Rec[] = [];
  2998. const register = (path: string[], rec: Rec) => {
  2999. if (path.length < 2 || path.includes(SUBMODULE)) return;
  3000. const key = path.join('.');
  3001. const arr = decls.get(key);
  3002. if (arr) arr.push(rec);
  3003. else decls.set(key, [rec]);
  3004. };
  3005. for (const recs of byFile.values()) {
  3006. recs.sort((a, b) => a.startLine - b.startLine || b.endLine - a.endLine);
  3007. const stack: Array<{ start: number; end: number; prefix: string[] }> = [];
  3008. for (const rec of recs) {
  3009. while (stack.length > 0 && stack[stack.length - 1]!.end < rec.startLine) stack.pop();
  3010. // Strict containment at line granularity: a one-line nested binding is
  3011. // indistinguishable from its container, so it stays unclassified (rare
  3012. // in module code, where option blocks are multi-line).
  3013. const enclosing =
  3014. stack.length > 0 &&
  3015. rec.startLine >= stack[stack.length - 1]!.start &&
  3016. rec.endLine <= stack[stack.length - 1]!.end &&
  3017. !(rec.startLine === stack[stack.length - 1]!.start && rec.endLine === stack[stack.length - 1]!.end)
  3018. ? stack[stack.length - 1]!
  3019. : null;
  3020. if (rec.segs[0] === 'options') {
  3021. const ownPath = rec.segs.slice(1); // [] for the bare `options = { ... }` spelling
  3022. const prefix = enclosing ? [SUBMODULE] : ownPath;
  3023. register(prefix, rec);
  3024. stack.push({ start: rec.startLine, end: rec.endLine, prefix });
  3025. continue;
  3026. }
  3027. if (enclosing) {
  3028. const composed = [...enclosing.prefix, ...rec.segs];
  3029. register(composed, rec);
  3030. stack.push({ start: rec.startLine, end: rec.endLine, prefix: composed });
  3031. continue;
  3032. }
  3033. if (rec.segs.length >= 2) {
  3034. writes.push(rec);
  3035. }
  3036. }
  3037. }
  3038. if (decls.size === 0 || writes.length === 0) return [];
  3039. const edges: Edge[] = [];
  3040. for (const w of writes) {
  3041. // `config.services.x = ...` spells the same write with an explicit prefix.
  3042. const segs = w.segs[0] === 'config' ? w.segs.slice(1) : w.segs;
  3043. if (segs.length < 2) continue;
  3044. // Longest prefix wins; an ambiguous longest match does NOT fall back to a
  3045. // shorter one (that would link `services.nginx.virtualHosts.x` to
  3046. // `options.services.nginx` when virtualHosts is the contested path).
  3047. for (let len = Math.min(segs.length, 6); len >= 2; len--) {
  3048. const candidates = decls.get(segs.slice(0, len).join('.'));
  3049. if (!candidates || candidates.length === 0) continue;
  3050. const files = new Set(candidates.map((c) => c.filePath));
  3051. if (files.size === 1) {
  3052. const target = candidates[0]!;
  3053. if (target.id !== w.id) {
  3054. edges.push({
  3055. source: w.id,
  3056. target: target.id,
  3057. kind: 'references',
  3058. line: w.startLine,
  3059. provenance: 'heuristic',
  3060. metadata: {
  3061. synthesizedBy: 'nix-option-path',
  3062. optionPath: segs.slice(0, len).join('.'),
  3063. registeredAt: `${target.filePath}:${target.startLine}`,
  3064. },
  3065. });
  3066. }
  3067. }
  3068. break; // longest hit decides, matched or ambiguous
  3069. }
  3070. }
  3071. return edges;
  3072. }
  3073. async function erlangBehaviourDispatchEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  3074. let scannedFiles = 0;
  3075. let scanned255 = 0;
  3076. // Cheap language gate: no Erlang modules → no cost beyond one streamed
  3077. // kind scan (never a materialized array of every namespace — #1212).
  3078. const erlangModules: Node[] = [];
  3079. for (const n of queries.iterateNodesByKind('namespace')) {
  3080. if ((++scanned255 & 63) === 0) await onYield();
  3081. if (n.language === 'erlang') erlangModules.push(n);
  3082. }
  3083. if (erlangModules.length === 0) return [];
  3084. // Pass 1 — scan every Erlang file with `-callback` decls: behaviour module →
  3085. // its (name, arity) callback set, and the global `name/arity` → declaring
  3086. // behaviours map that drives the ambiguity gate.
  3087. const moduleByFile = new Map<string, Node>();
  3088. for (const ns of erlangModules) {
  3089. if (!moduleByFile.has(ns.filePath)) moduleByFile.set(ns.filePath, ns);
  3090. }
  3091. const declaringBehaviours = new Map<string, Node[]>(); // `fn/arity` → behaviour namespaces
  3092. const callbackNames = new Set<string>();
  3093. for (const file of ctx.getAllFiles()) {
  3094. if ((++scannedFiles & 15) === 0) await onYield();
  3095. if (!ERLANG_EXT.test(file)) continue;
  3096. const behaviour = moduleByFile.get(file);
  3097. if (!behaviour) continue; // a .hrl or module-less file can't be a behaviour
  3098. const content = ctx.readFile(file);
  3099. if (!content || !content.includes('-callback')) continue;
  3100. const safe = stripCommentsForRegex(content, 'erlang');
  3101. ERLANG_CALLBACK_DECL_RE.lastIndex = 0;
  3102. let m: RegExpExecArray | null;
  3103. while ((m = ERLANG_CALLBACK_DECL_RE.exec(safe))) {
  3104. const name = m[2]!.replace(/^'|'$/g, '');
  3105. const arity = erlangArityAt(safe, m.index + m[0].length - 1);
  3106. if (arity < 0) continue;
  3107. const key = `${name}/${arity}`;
  3108. const arr = declaringBehaviours.get(key);
  3109. if (arr) {
  3110. if (!arr.some((b) => b.id === behaviour.id)) arr.push(behaviour);
  3111. } else {
  3112. declaringBehaviours.set(key, [behaviour]);
  3113. }
  3114. callbackNames.add(name);
  3115. }
  3116. }
  3117. if (declaringBehaviours.size === 0) return [];
  3118. // Implementer target lookup, lazy per (behaviour, fn, arity): implementers
  3119. // come from the `implements` edges extraction resolved, and the target is
  3120. // the implementer module's own exported `fn` node OF THE SITE'S ARITY —
  3121. // function qualifiedNames carry arity (`mod::fn/2`, #1610), so the arity the
  3122. // dispatch site used selects among same-named definitions.
  3123. const targetCache = new Map<string, Node[]>();
  3124. const qnArity = (qn: string): number => {
  3125. const m = /\/(\d{1,3})$/.exec(qn);
  3126. return m ? Number(m[1]) : -1;
  3127. };
  3128. const targetsOf = (behaviour: Node, fn: string, arity: number): Node[] => {
  3129. const cacheKey = `${behaviour.id}#${fn}/${arity}`;
  3130. let targets = targetCache.get(cacheKey);
  3131. if (targets) return targets;
  3132. targets = [];
  3133. for (const e of queries.getIncomingEdges(behaviour.id, ['implements'])) {
  3134. const impl = queries.getNodeById(e.source);
  3135. if (!impl || impl.language !== 'erlang' || impl.kind !== 'namespace') continue;
  3136. const fnNode = ctx
  3137. .getNodesInFile(impl.filePath)
  3138. .find(
  3139. (n) =>
  3140. n.kind === 'function' &&
  3141. n.name === fn &&
  3142. qnArity(n.qualifiedName) === arity &&
  3143. n.isExported !== false,
  3144. );
  3145. if (fnNode) targets.push(fnNode);
  3146. }
  3147. targetCache.set(cacheKey, targets);
  3148. return targets;
  3149. };
  3150. // Pass 2 — dispatch sites. Only files containing a var-module call shape are
  3151. // scanned in full.
  3152. const edges: Edge[] = [];
  3153. const seen = new Set<string>();
  3154. for (const file of ctx.getAllFiles()) {
  3155. if ((++scannedFiles & 15) === 0) await onYield();
  3156. if (!ERLANG_EXT.test(file)) continue;
  3157. const content = ctx.readFile(file);
  3158. if (!content || !/[A-Z][A-Za-z0-9_@]*:[a-z]/.test(content)) continue;
  3159. const safe = stripCommentsForRegex(content, 'erlang');
  3160. const nodesInFile = ctx.getNodesInFile(file);
  3161. ERLANG_DISPATCH_RE.lastIndex = 0;
  3162. let m: RegExpExecArray | null;
  3163. while ((m = ERLANG_DISPATCH_RE.exec(safe))) {
  3164. const fn = m[3]!;
  3165. if (!callbackNames.has(fn)) continue;
  3166. const openIdx = m.index + m[0].length - 1;
  3167. const arity = erlangArityAt(safe, openIdx);
  3168. if (arity < 0) continue;
  3169. const behaviours = declaringBehaviours.get(`${fn}/${arity}`);
  3170. if (!behaviours || behaviours.length !== 1) continue; // unknown or ambiguous
  3171. const behaviour = behaviours[0]!;
  3172. const targets = targetsOf(behaviour, fn, arity);
  3173. if (targets.length === 0 || targets.length > ERLANG_BEHAVIOUR_FANOUT_CAP) continue;
  3174. const line = safe.slice(0, m.index).split('\n').length;
  3175. const disp = enclosingFn(nodesInFile, line);
  3176. if (!disp) continue;
  3177. for (const target of targets) {
  3178. if (target.id === disp.id) continue;
  3179. const key = `${disp.id}>${target.id}`;
  3180. if (seen.has(key)) continue;
  3181. seen.add(key);
  3182. edges.push({
  3183. source: disp.id,
  3184. target: target.id,
  3185. kind: 'calls',
  3186. line,
  3187. provenance: 'heuristic',
  3188. metadata: {
  3189. synthesizedBy: 'erlang-behaviour',
  3190. via: `${behaviour.name}:${fn}/${arity}`,
  3191. registeredAt: `${file}:${line}`,
  3192. },
  3193. });
  3194. }
  3195. }
  3196. }
  3197. return edges;
  3198. }
  3199. // ── Laravel events (PHP) ──────────────────────────────────────────────────────
  3200. // Laravel decouples an event dispatch from its listener(s), linked by the EVENT CLASS:
  3201. // // app/Events/PlaybackStarted.php + app/Listeners/UpdateLastfmNowPlaying.php
  3202. // class UpdateLastfmNowPlaying { public function handle(PlaybackStarted $event) { … } }
  3203. // // a controller / service — a DIFFERENT file
  3204. // event(new PlaybackStarted($song, $user));
  3205. // Bridge it: link the enclosing method at each `event(new XEvent(...))` site → every listener's
  3206. // `handle` for XEvent. Listeners come from TWO registration mechanisms (both real, both needed):
  3207. // (A) auto-discovery — a `handle(EventType $e)` typed first param (also splits a union A|B);
  3208. // (B) the `protected $listen = [ XEvent::class => [Listener::class, …] ]` map in an
  3209. // EventServiceProvider, which also covers a listener whose `handle()` is UNTYPED.
  3210. // Only `event(new X)` is matched — queued JOBS dispatch via `::dispatch()` and their `handle()`
  3211. // takes an injected service, never an event type, so jobs are excluded by construction.
  3212. const LARAVEL_DISPATCH_RE = /\bevent\s*\(\s*new\s+\\?([A-Za-z_][\w\\]*)/g;
  3213. const LARAVEL_PHP_EXT = /\.php$/;
  3214. const LARAVEL_FANOUT_CAP = 200;
  3215. // A `$listen` entry: `Event::class => [Listener::class, …]`, key/values as `::class` or strings.
  3216. const LISTEN_ENTRY_RE = /(?:([A-Za-z_\\][\w\\]*)::class|'([^']+)'|"([^"]+)")\s*=>\s*\[([^\]]*)\]/g;
  3217. const LISTEN_CLASS_RE = /(?:([A-Za-z_\\][\w\\]*)::class|'([^']+)'|"([^"]+)")/g;
  3218. /** Short class name from a PHP reference: `\App\Events\Foo` / `App\Events::Foo` → `Foo`. */
  3219. function phpSimpleName(s: string): string {
  3220. return s.replace(/^\\/, '').split('\\').pop()!.split('::').pop()!.trim();
  3221. }
  3222. /** The first-parameter class type(s) of a `handle(...)` declaration — union-split, short-named,
  3223. * primitives dropped. `handle(A|B $e)` → [A, B]; `handle(string $x)` / `handle()` → []. */
  3224. function laravelHandleEventTypes(decl: string): string[] {
  3225. const m = /function\s+handle\s*\(\s*(?:\.\.\.\s*)?(\??[A-Za-z_\\][\w\\|]*)\s+&?\s*(?:\.\.\.\s*)?\$/.exec(decl);
  3226. if (!m) return [];
  3227. return m[1]!
  3228. .replace(/^\?/, '')
  3229. .split('|')
  3230. .map((t) => phpSimpleName(t))
  3231. .filter((t) => /^[A-Z]\w*$/.test(t));
  3232. }
  3233. /** From an opening `[`, the bracket-balanced body up to its matching `]`. */
  3234. function phpArrayBody(src: string, openIdx: number): string | null {
  3235. let depth = 0;
  3236. for (let i = openIdx; i < src.length; i++) {
  3237. if (src[i] === '[') depth++;
  3238. else if (src[i] === ']' && --depth === 0) return src.slice(openIdx + 1, i);
  3239. }
  3240. return null;
  3241. }
  3242. async function laravelEventEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]> {
  3243. let scannedFiles = 0;
  3244. // event short name → its listener `handle` methods (deduped by node id).
  3245. const listeners = new Map<string, Map<string, Node>>();
  3246. const add = (event: string, handle: Node) => {
  3247. let m = listeners.get(event);
  3248. if (!m) { m = new Map(); listeners.set(event, m); }
  3249. m.set(handle.id, handle);
  3250. };
  3251. const handleOf = (cls: Node): Node | null =>
  3252. ctx
  3253. .getNodesInFile(cls.filePath)
  3254. .find(
  3255. (n) => n.kind === 'method' && n.name === 'handle'
  3256. && n.startLine >= cls.startLine && n.startLine <= (cls.endLine ?? cls.startLine)
  3257. ) ?? null;
  3258. // Pass 1 — build the event→handle map from both registration mechanisms.
  3259. for (const file of ctx.getAllFiles()) {
  3260. if ((++scannedFiles & 15) === 0) await onYield();
  3261. if (!LARAVEL_PHP_EXT.test(file)) continue;
  3262. const content = ctx.readFile(file);
  3263. if (!content) continue;
  3264. // (A) typed listener handles — node-driven, so a commented-out method can't leak in.
  3265. if (content.includes('function handle')) {
  3266. const lines = content.split('\n');
  3267. for (const node of ctx.getNodesInFile(file)) {
  3268. if (node.kind !== 'method' || node.name !== 'handle') continue;
  3269. const decl = lines.slice(node.startLine - 1, node.startLine + 2).join('\n');
  3270. for (const ev of laravelHandleEventTypes(decl)) add(ev, node);
  3271. }
  3272. }
  3273. // (B) the EventServiceProvider `$listen` map — parsed from comment-stripped source so a
  3274. // fully-commented map (firefly's, on auto-discovery) contributes nothing.
  3275. if (content.includes('$listen')) {
  3276. const safe = stripCommentsForRegex(content, 'php');
  3277. const decl = safe.search(/\$listen\s*=\s*\[/);
  3278. const body = decl >= 0 ? phpArrayBody(safe, safe.indexOf('[', decl)) : null;
  3279. if (body) {
  3280. LISTEN_ENTRY_RE.lastIndex = 0;
  3281. let em: RegExpExecArray | null;
  3282. while ((em = LISTEN_ENTRY_RE.exec(body))) {
  3283. const event = phpSimpleName(em[1] ?? em[2] ?? em[3] ?? '');
  3284. LISTEN_CLASS_RE.lastIndex = 0;
  3285. let lm: RegExpExecArray | null;
  3286. while ((lm = LISTEN_CLASS_RE.exec(em[4]!))) {
  3287. const ln = phpSimpleName(lm[1] ?? lm[2] ?? lm[3] ?? '');
  3288. const cls = ctx.getNodesByName(ln).find((n) => n.kind === 'class' && handleOf(n));
  3289. if (cls) add(event, handleOf(cls)!);
  3290. }
  3291. }
  3292. }
  3293. }
  3294. }
  3295. if (!listeners.size) return [];
  3296. // Pass 2 — link each event(new X(...)) site → every listener of X.
  3297. const edges: Edge[] = [];
  3298. const seen = new Set<string>();
  3299. for (const file of ctx.getAllFiles()) {
  3300. if ((++scannedFiles & 15) === 0) await onYield();
  3301. if (!LARAVEL_PHP_EXT.test(file)) continue;
  3302. const content = ctx.readFile(file);
  3303. if (!content || !content.includes('event(')) continue;
  3304. const safe = stripCommentsForRegex(content, 'php');
  3305. const nodesInFile = ctx.getNodesInFile(file);
  3306. LARAVEL_DISPATCH_RE.lastIndex = 0;
  3307. let m: RegExpExecArray | null;
  3308. let added = 0;
  3309. while ((m = LARAVEL_DISPATCH_RE.exec(safe)) && added < LARAVEL_FANOUT_CAP) {
  3310. const targets = listeners.get(phpSimpleName(m[1]!));
  3311. if (!targets) continue;
  3312. const line = safe.slice(0, m.index).split('\n').length;
  3313. const disp = enclosingFn(nodesInFile, line);
  3314. if (!disp) continue;
  3315. for (const target of targets.values()) {
  3316. if (target.id === disp.id) continue;
  3317. const key = `${disp.id}>${target.id}`;
  3318. if (seen.has(key)) continue;
  3319. seen.add(key);
  3320. edges.push({
  3321. source: disp.id,
  3322. target: target.id,
  3323. kind: 'calls',
  3324. line,
  3325. provenance: 'heuristic',
  3326. metadata: { synthesizedBy: 'laravel-event', via: phpSimpleName(m[1]!), registeredAt: `${file}:${line}` },
  3327. });
  3328. added++;
  3329. }
  3330. }
  3331. }
  3332. return edges;
  3333. }
  3334. /**
  3335. * Synthesize dispatcher→callback edges (field observers + EventEmitters +
  3336. * React re-render + JSX children + Vue templates + SvelteKit load + RN event
  3337. * channel + Fabric native-impl + MyBatis Java↔XML + Gin middleware chain +
  3338. * Redux-thunk dispatch chain + object-literal registry dispatch + RTK Query
  3339. * generated-hook → endpoint + Pinia useStore().action() + Vuex string dispatch +
  3340. * Celery task .delay()/.apply_async() → task body + Spring publishEvent → @EventListener +
  3341. * MediatR Send/Publish → IRequestHandler/INotificationHandler +
  3342. * Sidekiq Worker.perform_async → #perform + Laravel event(new X) → listener handle).
  3343. * Returns the count added. Never throws into indexing — callers wrap in try/catch.
  3344. */
  3345. /**
  3346. * Number of progress steps synthesizeCallbackEdges reports: one per `__mark()`
  3347. * call (every synthesis pass, plus the dedupe-merge and edge-insert steps).
  3348. * Cosmetic only — drift just makes the progress bar end early or jump — and a
  3349. * test pins it to the actual step count (registry passes + the fixed
  3350. * pre/post marks) so adding a pass without bumping this fails loudly instead
  3351. * of silently skewing the bar.
  3352. */
  3353. const JS_FAMILY = ['typescript', 'javascript', 'tsx', 'jsx'];
  3354. /** `has(...)` shape passed to pass gates — true when the project contains any of the languages. */
  3355. type HasLang = (...ls: string[]) => boolean;
  3356. /**
  3357. * One independent synthesis pass. Every pass scans the COMMITTED graph (plus
  3358. * source via ctx) and returns an edge list; nothing it produces is persisted
  3359. * until the ordered merge in synthesizeCallbackEdges — which is what makes
  3360. * execution order free and the passes safe to fan out across the resolver
  3361. * pool's read-only workers. `gate` short-circuits a pass whose language never
  3362. * appears in the project (its result is provably empty — see #1212).
  3363. */
  3364. export interface SynthPassDef {
  3365. name: string;
  3366. gate: (has: HasLang) => boolean;
  3367. run: (
  3368. queries: QueryBuilder,
  3369. ctx: ResolutionContext,
  3370. yieldToLoop: MaybeYield,
  3371. subProgress?: (fraction: number) => void
  3372. ) => Promise<Edge[]>;
  3373. }
  3374. const ALWAYS = (): boolean => true;
  3375. /**
  3376. * The independent passes, in MERGE ORDER — the first-seen dedup in
  3377. * synthesizeCallbackEdges follows this array, so reordering entries changes
  3378. * which duplicate edge wins. The two Go pre-passes (cross-file method
  3379. * `contains`, implicit `implements`) are NOT here: they persist before these
  3380. * run because interfaceOverrideEdges reads their edges from the DB.
  3381. */
  3382. export const SYNTH_PASSES: SynthPassDef[] = [
  3383. { name: 'fieldEdges', gate: ALWAYS, run: (q, c, y) => fieldChannelEdges(q, c, y) },
  3384. { name: 'closureCollEdges', gate: ALWAYS, run: (q, c, y) => closureCollectionEdges(q, c, y) },
  3385. // Cross-tier channels — a client's `fetch('/api/x')` onto its own route,
  3386. // a queue job onto its consumer, a bus / socket event onto its handler.
  3387. // Before the in-process emitter pass: the same (source, target) pair
  3388. // keeps the more specific edge — the one that says which tier it crosses.
  3389. { name: 'tierEdges', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => crossTierEdges(c, y) },
  3390. { name: 'emitterEdges', gate: ALWAYS, run: (_q, c, y) => eventEmitterEdges(c, y) },
  3391. { name: 'renderEdges', gate: ALWAYS, run: (q, c, y) => reactRenderEdges(q, c, y) },
  3392. { name: 'jsxEdges', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => reactJsxChildEdges(c, y) },
  3393. { name: 'vueEdges', gate: (has) => has('vue'), run: (_q, c, y) => vueTemplateEdges(c, y) },
  3394. { name: 'svelteKitEdges', gate: (has) => has('svelte'), run: (_q, c, y) => svelteKitLoadEdges(c, y) },
  3395. { name: 'pascalEdges', gate: ALWAYS, run: (_q, c, y) => pascalFormEdges(c, y) },
  3396. { name: 'flutterEdges', gate: (has) => has('dart'), run: (q, c, y) => flutterBuildEdges(q, c, y) },
  3397. { name: 'arkuiStateEdges', gate: (has) => has('arkts'), run: (q, c, y) => arkuiStateBuildEdges(q, c, y) },
  3398. { name: 'arkuiEmitter', gate: (has) => has('arkts'), run: (_q, c, y) => arkuiEmitterEdges(c, y) },
  3399. { name: 'arkuiRoutes', gate: (has) => has('arkts'), run: (_q, c, y) => arkuiRouterEdges(c, y) },
  3400. { name: 'cppEdges', gate: (has) => has('cpp'), run: (q, _c, y) => cppOverrideEdges(q, y) },
  3401. {
  3402. name: 'ifaceEdges',
  3403. gate: (has) => has('java', 'kotlin', 'csharp', 'swift', 'scala', 'go', 'rust', 'arkts', ...JS_FAMILY),
  3404. run: (q, _c, y) => interfaceOverrideEdges(q, y),
  3405. },
  3406. { name: 'kotlinExpectActual', gate: (has) => has('kotlin'), run: (q, _c, y) => kotlinExpectActualEdges(q, y) },
  3407. { name: 'goGrpcEdges', gate: (has) => has('go'), run: (q, _c, y) => goGrpcStubImplEdges(q, y) },
  3408. { name: 'rnEventEdgesList', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => rnEventEdges(c, y) },
  3409. { name: 'fabricNativeEdges', gate: ALWAYS, run: (_q, c, y) => fabricNativeImplEdges(c, y) },
  3410. // Expo module nodes (`expo-module:` ids) are emitted only from .swift/.kt
  3411. // files, and a pair needs BOTH platforms — so without both languages the
  3412. // pass's only collection loop is provably empty (it was streaming every
  3413. // method row on pure-Java repos to find nothing).
  3414. { name: 'expoXPlatEdges', gate: (has) => has('swift') && has('kotlin'), run: (q, _c, y) => expoCrossPlatformEdges(q, y) },
  3415. // An RN cross-platform edge requires a JS-language caller on the native
  3416. // method (`isBridge`) — no JS-family files means no JS-language nodes, so
  3417. // the result is provably empty.
  3418. { name: 'rnXPlatEdges', gate: (has) => has(...JS_FAMILY), run: (q, _c, y) => rnCrossPlatformEdges(q, y) },
  3419. {
  3420. name: 'mybatisEdges',
  3421. gate: (has) => has('java', 'kotlin') && has('xml'),
  3422. run: (q, _c, y) => mybatisJavaXmlEdges(q, y),
  3423. },
  3424. { name: 'ginEdges', gate: (has) => has('go'), run: (q, c, y) => ginMiddlewareChainEdges(q, c, y) },
  3425. { name: 'thunkEdges', gate: (has) => has(...JS_FAMILY), run: (q, c, y) => reduxThunkEdges(q, c, y) },
  3426. { name: 'registryEdges', gate: ALWAYS, run: (_q, c, y) => objectRegistryEdges(c, y) },
  3427. { name: 'rtkEdges', gate: (has) => has(...JS_FAMILY), run: (q, c, y) => rtkQueryEdges(q, c, y) },
  3428. { name: 'piniaEdges', gate: (has) => has('vue', ...JS_FAMILY), run: (_q, c, y) => piniaStoreEdges(c, y) },
  3429. { name: 'vuexEdges', gate: (has) => has('vue', ...JS_FAMILY), run: (_q, c, y) => vuexDispatchEdges(c, y) },
  3430. { name: 'celeryEdges', gate: (has) => has('python'), run: (_q, c, y) => celeryDispatchEdges(c, y) },
  3431. { name: 'springEdges', gate: (has) => has('java'), run: (_q, c, y) => springEventEdges(c, y) },
  3432. { name: 'mediatrEdges', gate: (has) => has('csharp'), run: (_q, c, y) => mediatrDispatchEdges(c, y) },
  3433. { name: 'sidekiqEdges', gate: (has) => has('ruby'), run: (_q, c, y) => sidekiqDispatchEdges(c, y) },
  3434. {
  3435. name: 'erlangBehaviourEdges',
  3436. gate: (has) => has('erlang'),
  3437. run: (q, c, y) => erlangBehaviourDispatchEdges(q, c, y),
  3438. },
  3439. { name: 'laravelEdges', gate: (has) => has('php'), run: (_q, c, y) => laravelEventEdges(c, y) },
  3440. {
  3441. name: 'cFnPtrEdges',
  3442. gate: (has) => has('c', 'cpp'),
  3443. run: (q, c, y, sub) => cFnPointerDispatchEdges(q, c, y, sub),
  3444. },
  3445. { name: 'goframeEdges', gate: (has) => has('go'), run: (_q, c, y) => goframeRouteEdges(c, y) },
  3446. // `router.push(await helper())` — the helper's return literals are the screens.
  3447. { name: 'expoRouterReturnEdges', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => expoRouterReturnEdges(c, y) },
  3448. // `<Link href="/x">` / an internal `<a href>` — markup, not a call; the component navigates.
  3449. { name: 'nextLinkEdges', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => nextLinkEdges(c, y) },
  3450. { name: 'reactRouterLinkEdges', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => reactRouterLinkEdges(c, y) },
  3451. { name: 'tanstackLinkEdges', gate: (has) => has(...JS_FAMILY), run: (_q, c, y) => tanstackLinkEdges(c, y) },
  3452. { name: 'vueRouterLinkEdges', gate: (has) => has('vue', ...JS_FAMILY), run: (_q, c, y) => vueRouterLinkEdges(c, y) },
  3453. { name: 'svelteKitPageEdges', gate: (has) => has('svelte'), run: (_q, c, y) => svelteKitPageComponentEdges(c, y) },
  3454. { name: 'svelteKitLinkEdges', gate: (has) => has('svelte'), run: (_q, c, y) => svelteKitLinkEdges(c, y) },
  3455. { name: 'nixOptionEdges', gate: (has) => has('nix'), run: (q, _c, y) => nixOptionPathEdges(q, y) },
  3456. ];
  3457. /** Fixed non-registry steps: goMethodContains, goImplements, dedupe-merge, insertMergedEdges. */
  3458. const FIXED_SYNTH_STEPS = 4;
  3459. export const SYNTH_PROGRESS_STEPS = SYNTH_PASSES.length + FIXED_SYNTH_STEPS;
  3460. export async function synthesizeCallbackEdges(
  3461. queries: QueryBuilder,
  3462. ctx: ResolutionContext,
  3463. onProgress?: (done: number, total: number) => void,
  3464. // A live resolver pool to fan the independent passes across (structural type
  3465. // so this file never imports the pool — resolver-worker imports THIS file).
  3466. // Null/omitted → the sequential path, byte-identical to the pool path.
  3467. pool?: { runSynthPass(name: string): Promise<{ edges: Edge[]; ms: number }> } | null,
  3468. // WAL-valve writer backstop (WalCheckpointValve.backpressure), called at
  3469. // pool-idle points in the edge-insert loops below — the passes themselves
  3470. // only read; every write in this function happens with the pool idle.
  3471. backpressure?: () => Promise<void> | null
  3472. ): Promise<number> {
  3473. // Each sub-pass below is a whole-graph scan, and there are ~30 of them, all
  3474. // running synchronously on the indexer's main thread. Their AGGREGATE can run
  3475. // for well over a minute on a large repo — long enough for the #850 liveness
  3476. // watchdog to SIGKILL the process mid-index (#1091), since its heartbeat lives
  3477. // on this same thread. Yield between passes so the heartbeat can fire; a pass
  3478. // that itself hangs (a real wedge) never reaches the next yield, so the
  3479. // watchdog still catches that. See ./cooperative-yield.
  3480. const yieldToLoop = createYielder();
  3481. // Synthesis runs AFTER the resolution progress bar reaches 100%, so without
  3482. // its own progress the UI freezes at "Resolving refs 100%" for the whole
  3483. // tail — long enough on big repos that users conclude the index hung and
  3484. // kill it. Report each completed pass; the caller surfaces it as its own
  3485. // progress phase. Emit 0/total up front so the phase flips immediately.
  3486. // Emissions are throttled to whole-percent movement (each consumes a UI
  3487. // message); values may be fractional steps from within-pass reporting.
  3488. let passesDone = 0;
  3489. let lastPct = -1;
  3490. const emit = (value: number): void => {
  3491. if (!onProgress) return;
  3492. const v = Math.min(value, SYNTH_PROGRESS_STEPS);
  3493. const pct = Math.floor((v / SYNTH_PROGRESS_STEPS) * 100);
  3494. if (pct === lastPct) return;
  3495. lastPct = pct;
  3496. onProgress(v, SYNTH_PROGRESS_STEPS);
  3497. };
  3498. // A single long pass otherwise parks the bar between steps; a pass that
  3499. // takes this callback reports a 0..1 fraction of its own work, surfaced
  3500. // here as fractional progress within its step.
  3501. const subProgress = (fraction: number): void =>
  3502. emit(passesDone + Math.max(0, Math.min(fraction, 1)));
  3503. emit(0);
  3504. // Per-pass wall-clock timing to stderr, opt-in via CODEGRAPH_SYNTH_TIMINGS
  3505. // (=1: passes over 250ms; =all: every pass). This is the diagnostic that
  3506. // located both the #1091/#1122 watchdog stalls and the #1212 OOM — keep it.
  3507. const markT = { t: Date.now() };
  3508. const __mark = (label: string): void => {
  3509. const now = Date.now();
  3510. const dt = now - markT.t;
  3511. markT.t = now;
  3512. if (process.env.CODEGRAPH_SYNTH_TIMINGS && (dt > 250 || process.env.CODEGRAPH_SYNTH_TIMINGS === 'all')) {
  3513. console.error(`[synth-timing] ${label}: ${dt}ms`);
  3514. }
  3515. passesDone++;
  3516. emit(passesDone);
  3517. };
  3518. // Language gating: one indexed DISTINCT over the files table lets a pass
  3519. // whose own filters reference a specific language/extension be skipped
  3520. // outright when the project has no such files — its result is provably
  3521. // empty, so skipping is behavior-identical and the cost drops to zero
  3522. // (the Kotlin pass was the OOM culprit on the pure-C Linux kernel, #1212).
  3523. // Passes without an explicit language filter always run.
  3524. const langs = queries.getDistinctFileLanguages();
  3525. const has = (...ls: string[]): boolean => ls.some((l) => langs.has(l));
  3526. const NONE: Edge[] = [];
  3527. // Cross-file Go method→type `contains` edges must be synthesized AND persisted
  3528. // FIRST: a method declared in a different file from its receiver type is
  3529. // otherwise orphaned from the struct, and goImplementsEdges (next) derives a
  3530. // struct's method set from its `contains` edges — so without this it would
  3531. // under-count the interfaces a cross-file struct satisfies. (#583)
  3532. // Writer-side WAL backstop for the insert loops here (see the param doc):
  3533. // one fstat when under the valve's hard cap, a parked full backfill past it.
  3534. const foldIfOver = async (): Promise<void> => {
  3535. const bp = backpressure?.();
  3536. if (bp) await bp;
  3537. };
  3538. const goMethodContains = has('go') ? await goCrossFileMethodContainsEdges(queries, yieldToLoop) : NONE;
  3539. for (let i = 0; i < goMethodContains.length; i += 2000) {
  3540. queries.insertEdges(goMethodContains.slice(i, i + 2000));
  3541. await yieldToLoop();
  3542. await foldIfOver();
  3543. }
  3544. await yieldToLoop(); __mark('goMethodContains');
  3545. // Go implicit `implements` edges must be synthesized AND persisted next: the
  3546. // interface-dispatch bridge below reads `implements` edges from the DB, and
  3547. // Go has none statically. (Other languages already have static implements
  3548. // edges from extraction, so they don't need this pre-pass.)
  3549. const goImpl = has('go') ? await goImplementsEdges(queries, yieldToLoop) : NONE;
  3550. for (let i = 0; i < goImpl.length; i += 2000) {
  3551. queries.insertEdges(goImpl.slice(i, i + 2000));
  3552. await yieldToLoop();
  3553. await foldIfOver();
  3554. }
  3555. await yieldToLoop(); __mark('goImplements');
  3556. // Run the independent passes (see SYNTH_PASSES). Their results are merged in
  3557. // REGISTRY ORDER below regardless of execution order, and none of their edges
  3558. // persist until that merge — so every pass sees the same committed
  3559. // post-resolution DB state whether it runs sequentially here or on a resolver
  3560. // pool worker. With a live pool (already booted on ≥150k-ref repos), passes
  3561. // fan out across its read-only workers and the per-pass wall-clock comes from
  3562. // the worker; a pass that fails on a worker falls back to running on the main
  3563. // thread, so a worker crash isolates to a retry instead of failing synthesis.
  3564. const passEdges: Edge[][] = new Array<Edge[]>(SYNTH_PASSES.length).fill(NONE);
  3565. const markPass = (label: string, dt: number): void => {
  3566. if (process.env.CODEGRAPH_SYNTH_TIMINGS && (dt > 250 || process.env.CODEGRAPH_SYNTH_TIMINGS === 'all')) {
  3567. console.error(`[synth-timing] ${label}: ${dt}ms`);
  3568. }
  3569. passesDone++;
  3570. emit(passesDone);
  3571. };
  3572. const runPassOnMain = async (i: number): Promise<void> => {
  3573. const pass = SYNTH_PASSES[i]!;
  3574. const t0 = Date.now();
  3575. passEdges[i] = await pass.run(queries, ctx, yieldToLoop, subProgress);
  3576. await yieldToLoop();
  3577. markPass(pass.name, Date.now() - t0);
  3578. };
  3579. const gatedIn: number[] = [];
  3580. for (let i = 0; i < SYNTH_PASSES.length; i++) {
  3581. if (SYNTH_PASSES[i]!.gate(has)) gatedIn.push(i);
  3582. else markPass(SYNTH_PASSES[i]!.name, 0);
  3583. }
  3584. // Above this node count, a pass that OOM-killed its worker must NOT be
  3585. // retried on the main thread — the retry would OOM the whole process and
  3586. // take the index with it (the #1212 failure class). Below it, a worker
  3587. // failure is more likely a transient crash than a memory ceiling, and the
  3588. // main-thread retry keeps coverage. Skipping loses only that pass's
  3589. // synthesized edges; the index still completes.
  3590. const MAIN_RETRY_MAX_NODES = 1_500_000;
  3591. const graphNodes = queries.getNodeAndEdgeCount().nodes;
  3592. if (pool && gatedIn.length > 1) {
  3593. await Promise.all(
  3594. gatedIn.map(async (i) => {
  3595. const pass = SYNTH_PASSES[i]!;
  3596. try {
  3597. const out = await pool.runSynthPass(pass.name);
  3598. passEdges[i] = out.edges;
  3599. markPass(pass.name, out.ms);
  3600. } catch (err) {
  3601. if (graphNodes > MAIN_RETRY_MAX_NODES) {
  3602. // Worker died at a scale where the main-thread retry is a process
  3603. // OOM risk: skip the pass, keep the index alive, and say so.
  3604. console.error(
  3605. `[synthesis] pass '${pass.name}' failed on a worker at ${graphNodes} nodes — skipped (edges from this pass are absent): ${err instanceof Error ? err.message : String(err)}`
  3606. );
  3607. markPass(`${pass.name} (skipped at scale)`, 0);
  3608. return;
  3609. }
  3610. // Worker-side failure (crash, OOM, unknown pass after a version
  3611. // mismatch): retry this one pass on the main thread.
  3612. await runPassOnMain(i);
  3613. }
  3614. })
  3615. );
  3616. } else {
  3617. for (const i of gatedIn) {
  3618. await runPassOnMain(i);
  3619. }
  3620. }
  3621. const merged: Edge[] = [];
  3622. const seen = new Set<string>();
  3623. for (const e of passEdges.flat()) {
  3624. const key = `${e.source}>${e.target}`;
  3625. if (seen.has(key)) continue;
  3626. seen.add(key);
  3627. merged.push(e);
  3628. }
  3629. __mark('dedupe-merge');
  3630. // Chunked insert with yields: on the Linux kernel the merged synthesized
  3631. // edge set is ~275k rows, and one transaction for all of them was a 20s
  3632. // unyielded main-thread span (#1212 follow-up) — the last one in the tail.
  3633. for (let i = 0; i < merged.length; i += 2000) {
  3634. queries.insertEdges(merged.slice(i, i + 2000));
  3635. await yieldToLoop();
  3636. await foldIfOver();
  3637. }
  3638. __mark('insertMergedEdges');
  3639. return merged.length + goImpl.length + goMethodContains.length;
  3640. }