callback-synthesizer.ts 173 KB

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