auryn-typescript 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,569 @@
1
+ """parse_file(path) -> RawFile: the parallelizable phase-1 unit (pure function, no shared
2
+ state -- safe under a ProcessPoolExecutor; only picklable raw_model dataclasses are returned,
3
+ no tree-sitter node crosses the boundary). parse_source(source, path_label) holds the logic
4
+ and takes raw bytes, so a git blob can be parsed without touching disk.
5
+
6
+ Every node type / field name below was confirmed empirically against tree-sitter-typescript
7
+ 0.23.2 (see the package's grammar probes), not assumed:
8
+
9
+ - top level: `import_statement` (import_clause + [source] string), `export_statement`
10
+ (wraps [declaration], or is a re-export carrying [source]), `function_declaration`
11
+ ([name],[parameters],[return_type],[body]), `lexical_declaration`/`variable_declaration`
12
+ (-> variable_declarator [name]/[value] for `const f = () => ...`), `class_declaration` /
13
+ `abstract_class_declaration`, `interface_declaration`, `enum_declaration`,
14
+ `type_alias_declaration`.
15
+ - class members: `method_definition` and `public_field_definition`; modifiers `readonly`,
16
+ `static`, `abstract`, `get`/`set`, `?` are ANONYMOUS children (checked by `.type`), while
17
+ `accessibility_modifier` is a named child. Constructor params carrying an
18
+ `accessibility_modifier`/`readonly` are TS "parameter properties" -> also emitted as
19
+ Property.
20
+ - heritage: `class_heritage` -> `extends_clause` ([value], generics in a sibling
21
+ type_arguments so [value] is already the bare base) + `implements_clause` (type_identifier
22
+ / generic_type children); interfaces use `extends_type_clause` ([type] children).
23
+ - calls: `call_expression` [function] (identifier | member_expression [object]/[property]) and
24
+ `new_expression` [constructor]; `super(...)` is a `super` node and is ignored.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from pathlib import Path
30
+
31
+ from auryn.core.docstrings import leading_comment
32
+ from auryn.ingestors.typescript.grammar import dialect_for, is_declaration, new_parser
33
+ from auryn.ingestors.typescript.raw_model import (
34
+ RawCall,
35
+ RawClass,
36
+ RawEnum,
37
+ RawFile,
38
+ RawFunction,
39
+ RawImport,
40
+ RawInterface,
41
+ RawMethod,
42
+ RawParameter,
43
+ RawProperty,
44
+ RawTypeAlias,
45
+ )
46
+
47
+ _CLASS_DECLS = {"class_declaration", "abstract_class_declaration"}
48
+ _FUNC_VALUE_KINDS = {"arrow_function": "ARROW", "function_expression": "FUNCTION_EXPR"}
49
+ _LEXICAL = {"lexical_declaration", "variable_declaration"}
50
+
51
+ # HTTP-client call detection (ADR 0006). Kept STRICT to avoid false positives + a per-call
52
+ # perf hit: a bare `x.get(...)` is Map/collection access, NOT HTTP -- a verb-named call counts
53
+ # only when its receiver is a known HTTP client. The argument walk that extracts the URL runs
54
+ # ONLY when `_is_http_idiom` is true, so non-HTTP calls pay just one set lookup.
55
+ _HTTP_CLIENT_RECEIVERS = {"$", "jquery", "axios", "http", "httpclient"}
56
+ _HTTP_VERB_METHODS = {"ajax", "get", "post", "put", "delete", "patch", "getjson", "request"}
57
+ _HTTP_VERB_TO_METHOD = {"get": "GET", "post": "POST", "put": "PUT", "delete": "DELETE",
58
+ "patch": "PATCH", "getjson": "GET"}
59
+
60
+
61
+ def _is_http_idiom(name: str, receiver: str | None, client_vars: frozenset[str] = frozenset()) -> bool:
62
+ n = name.lower()
63
+ if n in ("fetch", "axios") and receiver is None: # fetch("…"), axios("…")
64
+ return True
65
+ if receiver is None:
66
+ return False
67
+ if receiver.lower() in _HTTP_CLIENT_RECEIVERS and n in _HTTP_VERB_METHODS:
68
+ return True
69
+ # A configured client instance -- `const api = axios.create(...)` -> api.get(...). The var
70
+ # names are discovered per file (precise, so no false positives on an arbitrary `x.get()`).
71
+ return receiver in client_vars and n in _HTTP_VERB_METHODS
72
+
73
+
74
+ def parse_file(path: str) -> RawFile:
75
+ return parse_source(Path(path).read_bytes(), path)
76
+
77
+
78
+ def parse_source(source: bytes, path_label: str) -> RawFile:
79
+ tree = new_parser(path_label).parse(source)
80
+ rf = RawFile(
81
+ path=path_label,
82
+ dialect=dialect_for(path_label),
83
+ is_declaration=is_declaration(path_label),
84
+ has_error=tree.root_node.has_error, # broken/mid-edit code -> resync preserves last-good
85
+ )
86
+
87
+ def txt(node) -> str:
88
+ return source[node.start_byte : node.end_byte].decode("utf-8", "replace") if node else ""
89
+
90
+ def lines(node) -> tuple[int, int]:
91
+ # tree-sitter points are 0-based (row, col); expose 1-based inclusive line numbers.
92
+ return node.start_point[0] + 1, node.end_point[0] + 1
93
+
94
+ def field(node, name):
95
+ return node.child_by_field_name(name) if node is not None else None
96
+
97
+ def doc_for(inner, outer=None) -> str:
98
+ """The leading doc comment of a declaration, cleaned. A comment (incl. JSDoc `/** */`,
99
+ one block comment node) is a *preceding sibling* of the declaration -- but when the decl
100
+ is wrapped (`export class ...`, `export const f = () => ...`) the comment sits above the
101
+ OUTER `export_statement`, not the inner node, so fall back to it."""
102
+ doc = leading_comment(inner, source)
103
+ if not doc and outer is not None and outer is not inner:
104
+ doc = leading_comment(outer, source)
105
+ return doc
106
+
107
+ def anon_types(node) -> set[str]:
108
+ """The `.type` of every child (named or keyword) -- lets us detect the modifier tokens
109
+ (readonly/static/abstract/get/set/?) that the grammar exposes as anonymous children."""
110
+ return {c.type for c in node.children}
111
+
112
+ def accessibility(node) -> str:
113
+ for c in node.children:
114
+ if c.type == "accessibility_modifier":
115
+ return txt(c)
116
+ return "public"
117
+
118
+ def collect_type_refs(node) -> list[str]:
119
+ """Every bare `type_identifier` name mentioned under a type node (annotation / alias
120
+ value / heritage) -- predefined types (string/number/void/...) are a different node
121
+ kind and so are naturally excluded. Generic params like `T` are collected too but get
122
+ filtered downstream, where only names matching a project declaration become edges."""
123
+ if node is None:
124
+ return []
125
+ out: list[str] = []
126
+ seen: set[str] = set()
127
+ stack = [node]
128
+ while stack:
129
+ n = stack.pop()
130
+ if n.type == "type_identifier":
131
+ name = txt(n)
132
+ if name and name not in seen:
133
+ seen.add(name)
134
+ out.append(name)
135
+ stack.extend(n.children)
136
+ return out
137
+
138
+ def annotation(type_annotation_node) -> tuple[str, list[str]]:
139
+ """(text as written without the leading ':', bare type refs) for a `type_annotation`."""
140
+ if type_annotation_node is None:
141
+ return "", []
142
+ raw = txt(type_annotation_node).lstrip()
143
+ if raw.startswith(":"):
144
+ raw = raw[1:]
145
+ return " ".join(raw.split()), collect_type_refs(type_annotation_node)
146
+
147
+ def simple_type_name(node) -> str | None:
148
+ """The bare name a heritage/type node denotes: `Base` for `Base`, `Base<T>`, or
149
+ `mod.Base`; None if it names nothing simple."""
150
+ if node is None:
151
+ return None
152
+ if node.type in ("type_identifier", "identifier"):
153
+ return txt(node)
154
+ if node.type == "generic_type":
155
+ return simple_type_name(field(node, "name"))
156
+ if node.type in ("member_expression", "nested_type_identifier"):
157
+ return simple_type_name(field(node, "property")) or _first_type_identifier(node)
158
+ return _first_type_identifier(node)
159
+
160
+ def _first_type_identifier(node) -> str | None:
161
+ stack = [node]
162
+ while stack:
163
+ n = stack.pop(0)
164
+ if n.type in ("type_identifier", "identifier"):
165
+ return txt(n)
166
+ stack.extend(n.children)
167
+ return None
168
+
169
+ def type_param_names(type_parameters_node) -> list[str]:
170
+ if type_parameters_node is None:
171
+ return []
172
+ names = []
173
+ for c in type_parameters_node.children:
174
+ if c.type == "type_parameter":
175
+ nm = field(c, "name")
176
+ if nm is not None:
177
+ names.append(txt(nm))
178
+ return names
179
+
180
+ def _param_name(pattern) -> tuple[str, bool]:
181
+ """(name, is_rest) for a parameter pattern; "" for a destructuring pattern (no simple
182
+ name, but the positional slot is still recorded)."""
183
+ if pattern is None:
184
+ return "", False
185
+ if pattern.type == "rest_pattern":
186
+ return _first_type_identifier(pattern) or "", True
187
+ if pattern.type == "identifier":
188
+ return txt(pattern), False
189
+ return "", False # object_pattern / array_pattern
190
+
191
+ def parameters(formal_parameters_node) -> list[RawParameter]:
192
+ out: list[RawParameter] = []
193
+ if formal_parameters_node is None:
194
+ return out
195
+ pos = 0
196
+ for p in formal_parameters_node.children:
197
+ if p.type not in ("required_parameter", "optional_parameter"):
198
+ continue # skips '(', ')', ','
199
+ name, is_rest = _param_name(field(p, "pattern"))
200
+ t_text, t_refs = annotation(field(p, "type"))
201
+ optional = p.type == "optional_parameter" or field(p, "value") is not None
202
+ out.append(
203
+ RawParameter(
204
+ name=name, type=t_text, position=pos, optional=optional,
205
+ is_rest=is_rest, type_refs=t_refs,
206
+ )
207
+ )
208
+ pos += 1
209
+ return out
210
+
211
+ def _callee(fn) -> tuple[str | None, str | None]:
212
+ if fn is None:
213
+ return None, None
214
+ if fn.type == "identifier":
215
+ return txt(fn), None
216
+ if fn.type == "member_expression":
217
+ prop = field(fn, "property")
218
+ obj = field(fn, "object")
219
+ recv = None
220
+ if obj is not None and obj.type == "this":
221
+ recv = "this"
222
+ elif obj is not None and obj.type == "identifier":
223
+ recv = txt(obj)
224
+ return (txt(prop) if prop is not None else None), recv
225
+ return None, None
226
+
227
+ def _route_text(node) -> str:
228
+ """URL text of a string / template-string arg, with `${...}` interpolations rendered as
229
+ `{param}` so a templated URL matches an endpoint route template (`api/x/${id}` -> api/x/{param})."""
230
+ if node.type == "template_string":
231
+ parts = []
232
+ for c in node.children:
233
+ if c.type == "string_fragment":
234
+ parts.append(txt(c))
235
+ elif c.type == "template_substitution":
236
+ parts.append("{param}")
237
+ return "".join(parts)
238
+ return _string_literal(node)
239
+
240
+ def _http_request(call_node, name: str) -> tuple[str | None, str | None]:
241
+ """(url, method) for an HTTP-client call -- best-effort, only invoked when the callee is
242
+ a known HTTP idiom. url = first string arg or an object arg's `url:`; method = the call's
243
+ verb (get/post/…) or an object arg's `method:`/`type:`; (None, None) if no url is found."""
244
+ args = field(call_node, "arguments")
245
+ if args is None:
246
+ return None, None
247
+ method = _HTTP_VERB_TO_METHOD.get(name.lower())
248
+ url = None
249
+ for a in args.children:
250
+ if a.type in (",", "(", ")"):
251
+ continue
252
+ if url is None and a.type in ("string", "template_string"):
253
+ url = _route_text(a)
254
+ elif a.type == "object":
255
+ for prop in a.children:
256
+ if prop.type != "pair":
257
+ continue
258
+ key = txt(field(prop, "key")).strip("\"'`")
259
+ val = field(prop, "value")
260
+ if val is None or val.type not in ("string", "template_string"):
261
+ continue
262
+ if key == "url" and url is None:
263
+ url = _route_text(val)
264
+ elif key in ("method", "type") and method is None:
265
+ method = _string_literal(val).upper()
266
+ return (url or None), method
267
+
268
+ def _configured_client_vars() -> frozenset[str]:
269
+ """Names bound to a configured HTTP client -- `const api = axios.create(...)` -- so a later
270
+ `api.get(...)` counts as HTTP. Precise (only axios.create), so no false positive on any x.get()."""
271
+ names: set[str] = set()
272
+ stack = [tree.root_node]
273
+ while stack:
274
+ n = stack.pop()
275
+ if n.type == "variable_declarator":
276
+ name_node, value = field(n, "name"), field(n, "value")
277
+ if (name_node is not None and name_node.type == "identifier"
278
+ and value is not None and value.type == "call_expression"):
279
+ callee = field(value, "function")
280
+ if (callee is not None and callee.type == "member_expression"
281
+ and txt(field(callee, "object")) == "axios"
282
+ and txt(field(callee, "property")) == "create"):
283
+ names.add(txt(name_node))
284
+ stack.extend(n.children)
285
+ return frozenset(names)
286
+
287
+ http_client_vars = _configured_client_vars()
288
+
289
+ def collect_calls(body) -> list:
290
+ if body is None:
291
+ return []
292
+ out: list = []
293
+ seen: set = set()
294
+ # Start from the body node itself, not its children: an expression-bodied arrow
295
+ # (`() => make(s)`) has the call_expression *as* the body, so descending straight into
296
+ # children would skip the outermost call.
297
+ stack = [body]
298
+ while stack:
299
+ n = stack.pop()
300
+ if n.type in ("call_expression", "new_expression"):
301
+ is_new = n.type == "new_expression"
302
+ nm, recv = _callee(field(n, "constructor" if is_new else "function"))
303
+ if nm:
304
+ key = (nm, recv, is_new)
305
+ if key not in seen:
306
+ seen.add(key)
307
+ http_url = http_method = None
308
+ if not is_new and _is_http_idiom(nm, recv, http_client_vars): # gate the arg walk (perf)
309
+ http_url, http_method = _http_request(n, nm)
310
+ out.append(RawCall(name=nm, receiver=recv, is_new=is_new,
311
+ http_url=http_url, http_method=http_method))
312
+ stack.extend(n.children)
313
+ return out
314
+
315
+ def method_from(node) -> RawMethod:
316
+ """From a `method_definition` (class) or `method_signature` (interface)."""
317
+ name = txt(field(node, "name"))
318
+ types = anon_types(node)
319
+ if name == "constructor":
320
+ kind = "CONSTRUCTOR"
321
+ elif "get" in types:
322
+ kind = "GETTER"
323
+ elif "set" in types:
324
+ kind = "SETTER"
325
+ else:
326
+ kind = "METHOD"
327
+ ret_text, ret_refs = annotation(field(node, "return_type"))
328
+ body = field(node, "body")
329
+ ls, le = lines(node)
330
+ return RawMethod(
331
+ name=name, kind=kind, accessibility=accessibility(node),
332
+ is_static="static" in types, is_abstract="abstract" in types,
333
+ is_async="async" in types, params=parameters(field(node, "parameters")),
334
+ return_type=ret_text, return_type_refs=ret_refs,
335
+ calls=collect_calls(body), source=txt(node), doc=doc_for(node),
336
+ line_start=ls, line_end=le,
337
+ )
338
+
339
+ def property_from(node) -> RawProperty:
340
+ """From a `public_field_definition` (class) or `property_signature` (interface)."""
341
+ types = anon_types(node)
342
+ t_text, t_refs = annotation(field(node, "type"))
343
+ return RawProperty(
344
+ name=txt(field(node, "name")), type=t_text, type_refs=t_refs,
345
+ accessibility=accessibility(node), is_static="static" in types,
346
+ is_readonly="readonly" in types, is_optional="?" in types,
347
+ )
348
+
349
+ def property_from_param(param_node) -> RawProperty:
350
+ """A TS "parameter property": `constructor(private readonly store: Store)` declares a
351
+ class field as a side effect of the parameter."""
352
+ name, _ = _param_name(field(param_node, "pattern"))
353
+ t_text, t_refs = annotation(field(param_node, "type"))
354
+ types = anon_types(param_node)
355
+ return RawProperty(
356
+ name=name, type=t_text, type_refs=t_refs, accessibility=accessibility(param_node),
357
+ is_readonly="readonly" in types, is_optional=param_node.type == "optional_parameter",
358
+ )
359
+
360
+ def _param_is_property(param_node) -> bool:
361
+ return any(c.type in ("accessibility_modifier", "readonly") for c in param_node.children)
362
+
363
+ def class_from(node, exported: bool, doc: str = "") -> RawClass:
364
+ types = anon_types(node)
365
+ extends: list[str] = []
366
+ implements: list[str] = []
367
+ for h in node.children:
368
+ if h.type != "class_heritage":
369
+ continue
370
+ for clause in h.children:
371
+ if clause.type == "extends_clause":
372
+ nm = simple_type_name(field(clause, "value"))
373
+ if nm:
374
+ extends.append(nm)
375
+ elif clause.type == "implements_clause":
376
+ for it in clause.children:
377
+ if it.type in ("type_identifier", "generic_type"):
378
+ nm = simple_type_name(it)
379
+ if nm:
380
+ implements.append(nm)
381
+ methods: list[RawMethod] = []
382
+ properties: list[RawProperty] = []
383
+ body = field(node, "body")
384
+ if body is not None:
385
+ for m in body.children:
386
+ if m.type == "method_definition":
387
+ meth = method_from(m)
388
+ methods.append(meth)
389
+ if meth.kind == "CONSTRUCTOR":
390
+ fp = field(m, "parameters")
391
+ if fp is not None:
392
+ properties.extend(
393
+ property_from_param(pn)
394
+ for pn in fp.children
395
+ if pn.type in ("required_parameter", "optional_parameter")
396
+ and _param_is_property(pn)
397
+ )
398
+ elif m.type == "public_field_definition":
399
+ properties.append(property_from(m))
400
+ ls, le = lines(node)
401
+ return RawClass(
402
+ name=txt(field(node, "name")),
403
+ is_abstract=node.type == "abstract_class_declaration" or "abstract" in types,
404
+ is_exported=exported, type_parameters=type_param_names(field(node, "type_parameters")),
405
+ extends=extends, implements=implements, methods=methods, properties=properties,
406
+ source=txt(node), doc=doc, line_start=ls, line_end=le,
407
+ )
408
+
409
+ def interface_from(node, exported: bool, doc: str = "") -> RawInterface:
410
+ extends: list[str] = []
411
+ for c in node.children:
412
+ if c.type == "extends_type_clause":
413
+ for it in c.children:
414
+ if it.type in ("type_identifier", "generic_type"):
415
+ nm = simple_type_name(it)
416
+ if nm:
417
+ extends.append(nm)
418
+ methods: list[RawMethod] = []
419
+ properties: list[RawProperty] = []
420
+ body = field(node, "body")
421
+ if body is not None:
422
+ for m in body.children:
423
+ if m.type == "method_signature":
424
+ methods.append(method_from(m))
425
+ elif m.type == "property_signature":
426
+ properties.append(property_from(m))
427
+ ls, le = lines(node)
428
+ return RawInterface(
429
+ name=txt(field(node, "name")), is_exported=exported,
430
+ type_parameters=type_param_names(field(node, "type_parameters")),
431
+ extends=extends, methods=methods, properties=properties,
432
+ source=txt(node), doc=doc, line_start=ls, line_end=le,
433
+ )
434
+
435
+ def enum_from(node, exported: bool, doc: str = "") -> RawEnum:
436
+ members: list[str] = []
437
+ body = field(node, "body")
438
+ if body is not None:
439
+ for e in body.children:
440
+ if e.type == "property_identifier":
441
+ members.append(txt(e))
442
+ elif e.type == "enum_assignment":
443
+ members.append(txt(field(e, "name")))
444
+ ls, le = lines(node)
445
+ return RawEnum(
446
+ name=txt(field(node, "name")), is_const="const" in anon_types(node),
447
+ is_exported=exported, members=members, source=txt(node), doc=doc,
448
+ line_start=ls, line_end=le,
449
+ )
450
+
451
+ def type_alias_from(node, exported: bool, doc: str = "") -> RawTypeAlias:
452
+ value = field(node, "value")
453
+ ls, le = lines(node)
454
+ return RawTypeAlias(
455
+ name=txt(field(node, "name")), value=" ".join(txt(value).split()),
456
+ is_exported=exported, type_refs=collect_type_refs(value),
457
+ source=txt(node), doc=doc, line_start=ls, line_end=le,
458
+ )
459
+
460
+ def function_from(node, exported: bool, kind: str, name: str, doc: str = "") -> RawFunction:
461
+ ret_text, ret_refs = annotation(field(node, "return_type"))
462
+ body = field(node, "body")
463
+ ls, le = lines(node)
464
+ return RawFunction(
465
+ name=name, kind=kind, is_exported=exported, is_async="async" in anon_types(node),
466
+ params=parameters(field(node, "parameters")), return_type=ret_text,
467
+ return_type_refs=ret_refs, calls=collect_calls(body), source=txt(node),
468
+ doc=doc, line_start=ls, line_end=le,
469
+ )
470
+
471
+ def _string_literal(node) -> str:
472
+ """The specifier text of a `string` node, quotes stripped."""
473
+ if node is None:
474
+ return ""
475
+ for c in node.children:
476
+ if c.type == "string_fragment":
477
+ return txt(c)
478
+ return txt(node).strip("\"'`")
479
+
480
+ def import_from(node) -> RawImport | None:
481
+ src = _string_literal(field(node, "source"))
482
+ if not src:
483
+ return None
484
+ clause = next((c for c in node.children if c.type == "import_clause"), None)
485
+ if clause is None:
486
+ return RawImport(module=src, kind="side_effect", line_start=lines(node)[0])
487
+ names: list[str] = []
488
+ kind = "named"
489
+ for c in clause.children:
490
+ if c.type == "identifier": # default import
491
+ kind = "default" if not names else kind
492
+ names.append(txt(c))
493
+ elif c.type == "namespace_import":
494
+ kind = "namespace"
495
+ names.append(_first_type_identifier(c) or "")
496
+ elif c.type == "named_imports":
497
+ for spec in c.children:
498
+ if spec.type == "import_specifier":
499
+ alias = field(spec, "alias")
500
+ names.append(txt(alias) if alias is not None else txt(field(spec, "name")))
501
+ return RawImport(module=src, kind=kind, names=names, line_start=lines(node)[0])
502
+
503
+ def reexport_from(node) -> RawImport | None:
504
+ """`export { A } from "m"` / `export * from "m"` -- a Module->Module dependency."""
505
+ src = _string_literal(field(node, "source"))
506
+ if not src:
507
+ return None
508
+ names: list[str] = ["*"]
509
+ clause = next((c for c in node.children if c.type == "export_clause"), None)
510
+ if clause is not None:
511
+ names = []
512
+ for spec in clause.children:
513
+ if spec.type == "export_specifier":
514
+ alias = field(spec, "alias")
515
+ names.append(txt(alias) if alias is not None else txt(field(spec, "name")))
516
+ return RawImport(module=src, kind="reexport", names=names, line_start=lines(node)[0])
517
+
518
+ def dispatch_declaration(decl, exported: bool, outer=None) -> None:
519
+ # A comment above `export class X` / `export const f = ...` attaches to the OUTER
520
+ # export_statement, so `outer` (the wrapper, or None when the decl is bare) is consulted.
521
+ doc = doc_for(decl, outer)
522
+ if decl.type in _CLASS_DECLS:
523
+ rf.classes.append(class_from(decl, exported, doc))
524
+ elif decl.type == "interface_declaration":
525
+ rf.interfaces.append(interface_from(decl, exported, doc))
526
+ elif decl.type == "enum_declaration":
527
+ rf.enums.append(enum_from(decl, exported, doc))
528
+ elif decl.type == "type_alias_declaration":
529
+ rf.type_aliases.append(type_alias_from(decl, exported, doc))
530
+ elif decl.type == "function_declaration":
531
+ name = txt(field(decl, "name"))
532
+ if name:
533
+ rf.functions.append(function_from(decl, exported, "FUNCTION", name, doc))
534
+ elif decl.type in _LEXICAL:
535
+ _lexical_functions(decl, exported, doc)
536
+
537
+ def _lexical_functions(decl, exported: bool, doc: str = "") -> None:
538
+ """`const f = () => ...` / `const g = function () {}` -> a module-level Function. Plain
539
+ value bindings (`const x = 42`) are deferred (no Variable node in v1). The doc comment
540
+ sits above the `lexical_declaration` (or its export wrapper), never the arrow/function
541
+ value node, so it is threaded in from `dispatch_declaration`."""
542
+ for d in decl.children:
543
+ if d.type != "variable_declarator":
544
+ continue
545
+ value = field(d, "value")
546
+ if value is not None and value.type in _FUNC_VALUE_KINDS:
547
+ name = txt(field(d, "name"))
548
+ if name:
549
+ rf.functions.append(
550
+ function_from(value, exported, _FUNC_VALUE_KINDS[value.type], name, doc)
551
+ )
552
+
553
+ for child in tree.root_node.children:
554
+ if child.type == "import_statement":
555
+ imp = import_from(child)
556
+ if imp is not None:
557
+ rf.imports.append(imp)
558
+ elif child.type == "export_statement":
559
+ decl = field(child, "declaration")
560
+ if decl is not None:
561
+ dispatch_declaration(decl, exported=True, outer=child)
562
+ elif field(child, "source") is not None: # re-export
563
+ imp = reexport_from(child)
564
+ if imp is not None:
565
+ rf.imports.append(imp)
566
+ else:
567
+ dispatch_declaration(child, exported=False)
568
+
569
+ return rf