tywrap 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +319 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +263 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/config/index.d.ts +41 -0
  8. package/dist/config/index.d.ts.map +1 -0
  9. package/dist/config/index.js +234 -0
  10. package/dist/config/index.js.map +1 -0
  11. package/dist/core/analyzer.d.ts +63 -0
  12. package/dist/core/analyzer.d.ts.map +1 -0
  13. package/dist/core/analyzer.js +676 -0
  14. package/dist/core/analyzer.js.map +1 -0
  15. package/dist/core/discovery.d.ts +85 -0
  16. package/dist/core/discovery.d.ts.map +1 -0
  17. package/dist/core/discovery.js +344 -0
  18. package/dist/core/discovery.js.map +1 -0
  19. package/dist/core/generator.d.ts +37 -0
  20. package/dist/core/generator.d.ts.map +1 -0
  21. package/dist/core/generator.js +368 -0
  22. package/dist/core/generator.js.map +1 -0
  23. package/dist/core/mapper.d.ts +40 -0
  24. package/dist/core/mapper.d.ts.map +1 -0
  25. package/dist/core/mapper.js +401 -0
  26. package/dist/core/mapper.js.map +1 -0
  27. package/dist/core/validation.d.ts +79 -0
  28. package/dist/core/validation.d.ts.map +1 -0
  29. package/dist/core/validation.js +486 -0
  30. package/dist/core/validation.js.map +1 -0
  31. package/dist/index.d.ts +26 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +29 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/runtime/base.d.ts +12 -0
  36. package/dist/runtime/base.d.ts.map +1 -0
  37. package/dist/runtime/base.js +6 -0
  38. package/dist/runtime/base.js.map +1 -0
  39. package/dist/runtime/errors.d.ts +17 -0
  40. package/dist/runtime/errors.d.ts.map +1 -0
  41. package/dist/runtime/errors.js +21 -0
  42. package/dist/runtime/errors.js.map +1 -0
  43. package/dist/runtime/http.d.ts +22 -0
  44. package/dist/runtime/http.d.ts.map +1 -0
  45. package/dist/runtime/http.js +79 -0
  46. package/dist/runtime/http.js.map +1 -0
  47. package/dist/runtime/index.d.ts +8 -0
  48. package/dist/runtime/index.d.ts.map +1 -0
  49. package/dist/runtime/index.js +17 -0
  50. package/dist/runtime/index.js.map +1 -0
  51. package/dist/runtime/node.d.ts +48 -0
  52. package/dist/runtime/node.d.ts.map +1 -0
  53. package/dist/runtime/node.js +328 -0
  54. package/dist/runtime/node.js.map +1 -0
  55. package/dist/runtime/optimized-node.d.ts +131 -0
  56. package/dist/runtime/optimized-node.d.ts.map +1 -0
  57. package/dist/runtime/optimized-node.js +622 -0
  58. package/dist/runtime/optimized-node.js.map +1 -0
  59. package/dist/runtime/protocol.d.ts +3 -0
  60. package/dist/runtime/protocol.d.ts.map +1 -0
  61. package/dist/runtime/protocol.js +3 -0
  62. package/dist/runtime/protocol.js.map +1 -0
  63. package/dist/runtime/pyodide.d.ts +27 -0
  64. package/dist/runtime/pyodide.d.ts.map +1 -0
  65. package/dist/runtime/pyodide.js +191 -0
  66. package/dist/runtime/pyodide.js.map +1 -0
  67. package/dist/tools/python_suite.js +173 -0
  68. package/dist/tools/python_suite.js.map +1 -0
  69. package/dist/types/index.d.ts +299 -0
  70. package/dist/types/index.d.ts.map +1 -0
  71. package/dist/types/index.js +5 -0
  72. package/dist/types/index.js.map +1 -0
  73. package/dist/tywrap.d.ts +29 -0
  74. package/dist/tywrap.d.ts.map +1 -0
  75. package/dist/tywrap.js +589 -0
  76. package/dist/tywrap.js.map +1 -0
  77. package/dist/utils/bundle-optimizer.d.ts +182 -0
  78. package/dist/utils/bundle-optimizer.d.ts.map +1 -0
  79. package/dist/utils/bundle-optimizer.js +680 -0
  80. package/dist/utils/bundle-optimizer.js.map +1 -0
  81. package/dist/utils/cache.d.ts +149 -0
  82. package/dist/utils/cache.d.ts.map +1 -0
  83. package/dist/utils/cache.js +492 -0
  84. package/dist/utils/cache.js.map +1 -0
  85. package/dist/utils/codec.d.ts +94 -0
  86. package/dist/utils/codec.d.ts.map +1 -0
  87. package/dist/utils/codec.js +150 -0
  88. package/dist/utils/codec.js.map +1 -0
  89. package/dist/utils/logger.d.ts +42 -0
  90. package/dist/utils/logger.d.ts.map +1 -0
  91. package/dist/utils/logger.js +140 -0
  92. package/dist/utils/logger.js.map +1 -0
  93. package/dist/utils/memory-profiler.d.ts +123 -0
  94. package/dist/utils/memory-profiler.d.ts.map +1 -0
  95. package/dist/utils/memory-profiler.js +426 -0
  96. package/dist/utils/memory-profiler.js.map +1 -0
  97. package/dist/utils/parallel-processor.d.ts +146 -0
  98. package/dist/utils/parallel-processor.d.ts.map +1 -0
  99. package/dist/utils/parallel-processor.js +636 -0
  100. package/dist/utils/parallel-processor.js.map +1 -0
  101. package/dist/utils/python.d.ts +8 -0
  102. package/dist/utils/python.d.ts.map +1 -0
  103. package/dist/utils/python.js +56 -0
  104. package/dist/utils/python.js.map +1 -0
  105. package/dist/utils/runtime.d.ts +153 -0
  106. package/dist/utils/runtime.d.ts.map +1 -0
  107. package/dist/utils/runtime.js +519 -0
  108. package/dist/utils/runtime.js.map +1 -0
  109. package/package.json +136 -0
  110. package/runtime/python_bridge.py +476 -0
  111. package/src/cli.ts +331 -0
  112. package/src/config/index.ts +289 -0
  113. package/src/core/analyzer.ts +788 -0
  114. package/src/core/discovery.ts +415 -0
  115. package/src/core/generator.ts +447 -0
  116. package/src/core/mapper.ts +504 -0
  117. package/src/core/validation.ts +693 -0
  118. package/src/index.ts +83 -0
  119. package/src/runtime/base.ts +32 -0
  120. package/src/runtime/errors.ts +19 -0
  121. package/src/runtime/http.ts +132 -0
  122. package/src/runtime/index.ts +24 -0
  123. package/src/runtime/node.ts +431 -0
  124. package/src/runtime/optimized-node.ts +838 -0
  125. package/src/runtime/protocol.ts +2 -0
  126. package/src/runtime/pyodide.ts +228 -0
  127. package/src/types/global.d.ts +60 -0
  128. package/src/types/index.ts +410 -0
  129. package/src/tywrap.ts +669 -0
  130. package/src/utils/bundle-optimizer.ts +876 -0
  131. package/src/utils/cache.ts +634 -0
  132. package/src/utils/codec.ts +275 -0
  133. package/src/utils/logger.ts +201 -0
  134. package/src/utils/memory-profiler.ts +582 -0
  135. package/src/utils/parallel-processor.ts +879 -0
  136. package/src/utils/python.ts +79 -0
  137. package/src/utils/runtime.ts +616 -0
@@ -0,0 +1,676 @@
1
+ /**
2
+ * PyAnalyzer - Python AST analysis and type extraction
3
+ */
4
+ import Parser from 'tree-sitter';
5
+ import Python from 'tree-sitter-python';
6
+ import { globalCache } from '../utils/cache.js';
7
+ import { getComponentLogger } from '../utils/logger.js';
8
+ const log = getComponentLogger('Analyzer');
9
+ const UNKNOWN_TYPE = { kind: 'custom', name: 'Any', module: 'typing' };
10
+ export class PyAnalyzer {
11
+ parser;
12
+ initialized = false;
13
+ constructor() {
14
+ this.parser = new Parser();
15
+ }
16
+ /**
17
+ * Initialize the tree-sitter parser with Python grammar
18
+ */
19
+ async initialize() {
20
+ if (this.initialized) {
21
+ return;
22
+ }
23
+ try {
24
+ await this.parser.setLanguage(Python);
25
+ this.initialized = true;
26
+ }
27
+ catch (error) {
28
+ throw new Error(`Failed to initialize Python parser: ${error}`);
29
+ }
30
+ }
31
+ /**
32
+ * Analyze Python module source code and extract structure with caching
33
+ */
34
+ async analyzePythonModule(source, modulePath) {
35
+ await this.initialize();
36
+ // Check cache first
37
+ const cached = await globalCache.getCachedAnalysis(source, modulePath ?? 'unknown');
38
+ if (cached) {
39
+ return cached;
40
+ }
41
+ const startTime = performance.now();
42
+ const errors = [];
43
+ const warnings = [];
44
+ const dependencies = [];
45
+ try {
46
+ const tree = this.parser.parse(source);
47
+ const rootNode = tree.rootNode;
48
+ // Check for syntax errors
49
+ if (rootNode.hasError) {
50
+ this.collectSyntaxErrors(rootNode, errors);
51
+ }
52
+ // Extract module components
53
+ const functions = await this.extractFunctions(rootNode);
54
+ const classes = await this.extractClasses(rootNode);
55
+ const imports = this.extractImports(rootNode);
56
+ // Collect dependencies from imports (deduplicated)
57
+ const uniqueDependencies = [...new Set(imports.map(imp => imp.module))];
58
+ dependencies.push(...uniqueDependencies);
59
+ // Generate statistics
60
+ const statistics = this.generateStatistics(functions, classes, source);
61
+ const module = {
62
+ name: this.extractModuleName(modulePath),
63
+ path: modulePath,
64
+ functions,
65
+ classes,
66
+ imports,
67
+ exports: this.extractExports(rootNode),
68
+ };
69
+ const result = {
70
+ module,
71
+ errors,
72
+ warnings,
73
+ dependencies,
74
+ statistics,
75
+ };
76
+ // Cache the successful result
77
+ const computeTime = performance.now() - startTime;
78
+ await globalCache.setCachedAnalysis(source, modulePath ?? 'unknown', result, computeTime);
79
+ return result;
80
+ }
81
+ catch (error) {
82
+ errors.push({
83
+ type: 'syntax',
84
+ message: `Failed to parse Python module: ${error}`,
85
+ file: modulePath,
86
+ });
87
+ return {
88
+ module: {
89
+ name: this.extractModuleName(modulePath),
90
+ path: modulePath,
91
+ functions: [],
92
+ classes: [],
93
+ imports: [],
94
+ exports: [],
95
+ },
96
+ errors,
97
+ warnings,
98
+ dependencies,
99
+ statistics: this.generateStatistics([], [], source),
100
+ };
101
+ }
102
+ }
103
+ /**
104
+ * Extract function definitions from AST
105
+ */
106
+ async extractFunctions(node) {
107
+ const functions = [];
108
+ const functionNodes = this.findNodesByType(node, 'function_definition');
109
+ for (const funcNode of functionNodes) {
110
+ try {
111
+ const func = await this.extractFunction(funcNode);
112
+ functions.push(func);
113
+ }
114
+ catch (error) {
115
+ log.warn('Failed to extract function', { error: String(error) });
116
+ }
117
+ }
118
+ return functions;
119
+ }
120
+ /**
121
+ * Extract class definitions from AST
122
+ */
123
+ async extractClasses(node) {
124
+ const classes = [];
125
+ const classNodes = this.findNodesByType(node, 'class_definition');
126
+ for (const classNode of classNodes) {
127
+ try {
128
+ const cls = await this.extractClass(classNode);
129
+ classes.push(cls);
130
+ }
131
+ catch (error) {
132
+ log.warn('Failed to extract class', { error: String(error) });
133
+ }
134
+ }
135
+ return classes;
136
+ }
137
+ /**
138
+ * Extract single function from function_definition node
139
+ */
140
+ async extractFunction(node) {
141
+ const nameNode = node.childForFieldName('name');
142
+ const parametersNode = node.childForFieldName('parameters');
143
+ const returnTypeNode = node.childForFieldName('return_type');
144
+ const bodyNode = node.childForFieldName('body');
145
+ const name = nameNode?.text ?? 'unknown';
146
+ const parameters = parametersNode ? this.extractParameters(parametersNode) : [];
147
+ const returnType = returnTypeNode ? this.parseTypeAnnotation(returnTypeNode) : UNKNOWN_TYPE;
148
+ // Extract decorators
149
+ const decorators = this.extractDecorators(node);
150
+ // Determine if async
151
+ const isAsync = node.text.trimStart().startsWith('async def');
152
+ // Check if generator (contains yield)
153
+ const isGenerator = bodyNode ? this.containsYield(bodyNode) : false;
154
+ // Extract docstring
155
+ const docstring = bodyNode ? this.extractDocstring(bodyNode) : undefined;
156
+ const signature = {
157
+ parameters,
158
+ returnType,
159
+ isAsync,
160
+ isGenerator,
161
+ };
162
+ return {
163
+ name,
164
+ signature,
165
+ docstring,
166
+ decorators,
167
+ isAsync,
168
+ isGenerator,
169
+ returnType,
170
+ parameters,
171
+ };
172
+ }
173
+ /**
174
+ * Extract single class from class_definition node
175
+ */
176
+ async extractClass(node) {
177
+ const nameNode = node.childForFieldName('name');
178
+ const superclassesNode = node.childForFieldName('superclasses');
179
+ const bodyNode = node.childForFieldName('body');
180
+ const name = nameNode?.text ?? 'unknown';
181
+ const bases = superclassesNode ? this.extractBases(superclassesNode) : [];
182
+ const decorators = this.extractDecorators(node);
183
+ const docstring = bodyNode ? this.extractDocstring(bodyNode) : undefined;
184
+ // Extract methods and properties from body
185
+ const methods = [];
186
+ const properties = [];
187
+ if (bodyNode) {
188
+ const methodNodes = this.findNodesByType(bodyNode, 'function_definition');
189
+ for (const methodNode of methodNodes) {
190
+ try {
191
+ const method = await this.extractFunction(methodNode);
192
+ methods.push(method);
193
+ }
194
+ catch (error) {
195
+ log.warn('Failed to extract method', { error: String(error) });
196
+ }
197
+ }
198
+ // Extract properties (assignments with type annotations or @property decorators)
199
+ const assignmentNodes = this.findNodesByType(bodyNode, 'assignment');
200
+ for (const assignNode of assignmentNodes) {
201
+ const prop = this.extractProperty(assignNode);
202
+ if (prop) {
203
+ properties.push(prop);
204
+ }
205
+ }
206
+ }
207
+ return {
208
+ name,
209
+ bases,
210
+ methods,
211
+ properties,
212
+ docstring,
213
+ decorators,
214
+ };
215
+ }
216
+ /**
217
+ * Extract function parameters from parameters node
218
+ */
219
+ extractParameters(node) {
220
+ const parameters = [];
221
+ // Handle different parameter types
222
+ for (const child of node.namedChildren) {
223
+ if (child.type === 'identifier') {
224
+ // Simple parameter
225
+ parameters.push({
226
+ name: child.text,
227
+ type: UNKNOWN_TYPE,
228
+ optional: false,
229
+ varArgs: false,
230
+ kwArgs: false,
231
+ });
232
+ }
233
+ else if (child.type === 'typed_parameter') {
234
+ // Parameter with type annotation - check multiple possible field names
235
+ const patternNode = child.childForFieldName('pattern');
236
+ let nameNode = patternNode ?? child.child(0) ?? null;
237
+ const typeFieldNode = child.childForFieldName('type');
238
+ const typeNode = typeFieldNode ?? child.child(2) ?? null;
239
+ // If pattern field doesn't exist, try to find identifier directly
240
+ if (!nameNode || nameNode.type !== 'identifier') {
241
+ nameNode = this.findNodesByType(child, 'identifier')[0] ?? null;
242
+ }
243
+ parameters.push({
244
+ name: nameNode?.text ?? 'unknown',
245
+ type: typeNode ? this.parseTypeAnnotation(typeNode) : UNKNOWN_TYPE,
246
+ optional: false,
247
+ varArgs: false,
248
+ kwArgs: false,
249
+ });
250
+ }
251
+ else if (child.type === 'default_parameter') {
252
+ // Parameter with default value
253
+ const nameFieldNode = child.childForFieldName('name');
254
+ const nameNode = nameFieldNode ?? child.child(0) ?? null;
255
+ let valueNode = child.childForFieldName('value') ?? null;
256
+ // Find value node if field name doesn't work
257
+ if (!valueNode) {
258
+ const equalIndex = child.children.findIndex(c => c.text === '=');
259
+ if (equalIndex >= 0 && equalIndex + 1 < child.children.length) {
260
+ valueNode = child.children[equalIndex + 1] ?? null;
261
+ }
262
+ }
263
+ parameters.push({
264
+ name: nameNode?.text ?? 'unknown',
265
+ type: UNKNOWN_TYPE,
266
+ optional: true,
267
+ defaultValue: valueNode?.text,
268
+ varArgs: false,
269
+ kwArgs: false,
270
+ });
271
+ }
272
+ else if (child.type === 'typed_default_parameter') {
273
+ // Parameter with type and default
274
+ const patternNode = child.childForFieldName('pattern');
275
+ let nameNode = patternNode ?? child.child(0) ?? null;
276
+ let typeNode = child.childForFieldName('type') ?? null;
277
+ let valueNode = child.childForFieldName('value') ?? null;
278
+ // If pattern field doesn't exist, try to find identifier directly
279
+ if (!nameNode || nameNode.type !== 'identifier') {
280
+ nameNode = this.findNodesByType(child, 'identifier')[0] ?? null;
281
+ }
282
+ // Find type and value nodes if field names don't work
283
+ if (!typeNode || !valueNode) {
284
+ const colonIndex = child.children.findIndex(c => c.text === ':');
285
+ const equalIndex = child.children.findIndex(c => c.text === '=');
286
+ if (colonIndex >= 0 && colonIndex + 1 < child.children.length) {
287
+ typeNode = child.children[colonIndex + 1] ?? null;
288
+ }
289
+ if (equalIndex >= 0 && equalIndex + 1 < child.children.length) {
290
+ valueNode = child.children[equalIndex + 1] ?? null;
291
+ }
292
+ }
293
+ parameters.push({
294
+ name: nameNode?.text ?? 'unknown',
295
+ type: typeNode ? this.parseTypeAnnotation(typeNode) : UNKNOWN_TYPE,
296
+ optional: true,
297
+ defaultValue: valueNode?.text,
298
+ varArgs: false,
299
+ kwArgs: false,
300
+ });
301
+ }
302
+ else if (child.type === 'list_splat_pattern') {
303
+ // *args parameter
304
+ const nameNode = child.child(1); // Skip the *
305
+ parameters.push({
306
+ name: nameNode?.text ?? 'args',
307
+ type: { kind: 'collection', name: 'tuple', itemTypes: [] },
308
+ optional: false,
309
+ varArgs: true,
310
+ kwArgs: false,
311
+ });
312
+ }
313
+ else if (child.type === 'dictionary_splat_pattern') {
314
+ // **kwargs parameter
315
+ const nameNode = child.child(1); // Skip the **
316
+ parameters.push({
317
+ name: nameNode?.text ?? 'kwargs',
318
+ type: { kind: 'collection', name: 'dict', itemTypes: [] },
319
+ optional: false,
320
+ varArgs: false,
321
+ kwArgs: true,
322
+ });
323
+ }
324
+ }
325
+ return parameters;
326
+ }
327
+ /**
328
+ * Parse type annotation node into PythonType
329
+ */
330
+ parseTypeAnnotation(node) {
331
+ const typeText = node.text.trim();
332
+ // Handle primitive types
333
+ const primitiveTypes = ['int', 'float', 'str', 'bool', 'bytes', 'None'];
334
+ if (primitiveTypes.includes(typeText)) {
335
+ return {
336
+ kind: 'primitive',
337
+ name: typeText,
338
+ };
339
+ }
340
+ // Handle collection types
341
+ const collectionTypes = [
342
+ 'dict',
343
+ 'Dict',
344
+ 'list',
345
+ 'List',
346
+ 'tuple',
347
+ 'Tuple',
348
+ 'set',
349
+ 'Set',
350
+ ];
351
+ if (collectionTypes.includes(typeText)) {
352
+ const normalizedName = typeText.toLowerCase() === 'dict' || typeText === 'Dict'
353
+ ? 'dict'
354
+ : typeText.toLowerCase() === 'list' || typeText === 'List'
355
+ ? 'list'
356
+ : typeText.toLowerCase() === 'tuple' || typeText === 'Tuple'
357
+ ? 'tuple'
358
+ : typeText.toLowerCase() === 'set' || typeText === 'Set'
359
+ ? 'set'
360
+ : 'dict';
361
+ return { kind: 'collection', name: normalizedName, itemTypes: [] };
362
+ }
363
+ // Handle List, Dict, etc.
364
+ if (typeText.startsWith('List[') || typeText.startsWith('list[')) {
365
+ return this.parseGenericType(typeText, 'list');
366
+ }
367
+ if (typeText.startsWith('Dict[') || typeText.startsWith('dict[')) {
368
+ return this.parseGenericType(typeText, 'dict');
369
+ }
370
+ if (typeText.startsWith('Tuple[') || typeText.startsWith('tuple[')) {
371
+ return this.parseGenericType(typeText, 'tuple');
372
+ }
373
+ if (typeText.startsWith('Set[') || typeText.startsWith('set[')) {
374
+ return this.parseGenericType(typeText, 'set');
375
+ }
376
+ // Handle Union types
377
+ if (typeText.includes(' | ') || typeText.startsWith('Union[')) {
378
+ return this.parseUnionType(typeText);
379
+ }
380
+ // Handle Optional
381
+ if (typeText.startsWith('Optional[')) {
382
+ const innerType = typeText.slice(9, -1);
383
+ const parsedInnerType = this.parseTypeAnnotation({ text: innerType });
384
+ // For Optional[Dict] -> ensure Dict is treated as collection, not custom
385
+ if (innerType === 'Dict' || innerType === 'dict') {
386
+ return {
387
+ kind: 'optional',
388
+ type: { kind: 'collection', name: 'dict', itemTypes: [] },
389
+ };
390
+ }
391
+ return {
392
+ kind: 'optional',
393
+ type: parsedInnerType,
394
+ };
395
+ }
396
+ // Custom/module type - clean up quotes
397
+ let cleanedName = typeText;
398
+ if ((cleanedName.startsWith("'") && cleanedName.endsWith("'")) ||
399
+ (cleanedName.startsWith('"') && cleanedName.endsWith('"'))) {
400
+ cleanedName = cleanedName.slice(1, -1);
401
+ }
402
+ return {
403
+ kind: 'custom',
404
+ name: cleanedName,
405
+ };
406
+ }
407
+ parseGenericType(typeText, collectionName) {
408
+ const bracketStart = typeText.indexOf('[');
409
+ const bracketEnd = typeText.lastIndexOf(']');
410
+ if (bracketStart === -1 || bracketEnd === -1) {
411
+ return { kind: 'collection', name: collectionName, itemTypes: [] };
412
+ }
413
+ const genericPart = typeText.slice(bracketStart + 1, bracketEnd);
414
+ const itemTypes = this.parseGenericArguments(genericPart);
415
+ return {
416
+ kind: 'collection',
417
+ name: collectionName,
418
+ itemTypes,
419
+ };
420
+ }
421
+ parseUnionType(typeText) {
422
+ let unionPart;
423
+ if (typeText.startsWith('Union[')) {
424
+ unionPart = typeText.slice(6, -1);
425
+ }
426
+ else {
427
+ unionPart = typeText;
428
+ }
429
+ const types = this.parseGenericArguments(unionPart);
430
+ return { kind: 'union', types };
431
+ }
432
+ parseGenericArguments(argsText) {
433
+ // Nested-aware argument splitter for generics (handles [] and ())
434
+ const results = [];
435
+ let depthSquare = 0;
436
+ let depthParen = 0;
437
+ let current = '';
438
+ for (let i = 0; i < argsText.length; i++) {
439
+ const ch = String(argsText.charAt(i));
440
+ if (ch === '[') {
441
+ depthSquare++;
442
+ }
443
+ if (ch === ']') {
444
+ depthSquare = Math.max(0, depthSquare - 1);
445
+ }
446
+ if (ch === '(') {
447
+ depthParen++;
448
+ }
449
+ if (ch === ')') {
450
+ depthParen = Math.max(0, depthParen - 1);
451
+ }
452
+ if (ch === ',' && depthSquare === 0 && depthParen === 0) {
453
+ results.push(current.trim());
454
+ current = '';
455
+ continue;
456
+ }
457
+ current += ch;
458
+ }
459
+ if (current.trim().length > 0) {
460
+ results.push(current.trim());
461
+ }
462
+ return results.map(arg => this.parseTypeAnnotation({ text: arg }));
463
+ }
464
+ /**
465
+ * Extract import statements
466
+ */
467
+ extractImports(node) {
468
+ const imports = [];
469
+ const seen = new Set();
470
+ // Only look for import statements at the module level (not nested)
471
+ const moduleChildren = node.namedChildren;
472
+ const importNodes = [];
473
+ for (const child of moduleChildren) {
474
+ if (child.type === 'import_statement' || child.type === 'import_from_statement') {
475
+ importNodes.push(child);
476
+ }
477
+ }
478
+ for (const importNode of importNodes) {
479
+ if (importNode.type === 'import_statement') {
480
+ // import module [as alias]
481
+ const nameNode = importNode.child(1);
482
+ if (nameNode && (nameNode.type === 'dotted_name' || nameNode.type === 'aliased_import')) {
483
+ let moduleName;
484
+ if (nameNode.type === 'aliased_import') {
485
+ // Handle 'import module as alias' - extract module name before 'as'
486
+ const parts = nameNode.text.split(' as ');
487
+ const firstPart = parts[0];
488
+ if (firstPart) {
489
+ moduleName = firstPart.split('.')[0]; // Get base module name
490
+ }
491
+ }
492
+ else {
493
+ // Handle 'import module' - extract module name
494
+ moduleName = nameNode.text.split('.')[0]; // Get base module name
495
+ }
496
+ if (moduleName) {
497
+ const key = `${moduleName}:import`;
498
+ if (!seen.has(key)) {
499
+ seen.add(key);
500
+ imports.push({
501
+ module: moduleName,
502
+ fromImport: false,
503
+ });
504
+ }
505
+ }
506
+ }
507
+ }
508
+ else if (importNode.type === 'import_from_statement') {
509
+ // from module import name [as alias]
510
+ const moduleNameIndex = importNode.children.findIndex(c => c.text === 'from');
511
+ const importIndex = importNode.children.findIndex(c => c.text === 'import');
512
+ if (moduleNameIndex >= 0 && importIndex > moduleNameIndex) {
513
+ const moduleNode = importNode.children[moduleNameIndex + 1];
514
+ if (moduleNode && moduleNode.type === 'dotted_name') {
515
+ const moduleName = moduleNode.text.split('.')[0];
516
+ if (moduleName) {
517
+ // Collect all import names after the 'import' keyword
518
+ const importNames = [];
519
+ for (let i = importIndex + 1; i < importNode.children.length; i++) {
520
+ const child = importNode.children.at(i);
521
+ if (child && (child.type === 'dotted_name' || child.type === 'identifier')) {
522
+ importNames.push(child.text);
523
+ }
524
+ else if (child && child.type === 'wildcard_import') {
525
+ importNames.push('*');
526
+ }
527
+ // Skip comma separators
528
+ }
529
+ // Create separate import entries for each imported name
530
+ for (const importName of importNames) {
531
+ const key = `${moduleName}:${importName}`;
532
+ if (!seen.has(key)) {
533
+ seen.add(key);
534
+ imports.push({
535
+ module: moduleName,
536
+ name: importName,
537
+ fromImport: true,
538
+ });
539
+ }
540
+ }
541
+ }
542
+ }
543
+ }
544
+ }
545
+ }
546
+ return imports;
547
+ }
548
+ /**
549
+ * Utility methods
550
+ */
551
+ findNodesByType(node, type) {
552
+ const results = [];
553
+ const traverse = (n) => {
554
+ if (n.type === type) {
555
+ results.push(n);
556
+ }
557
+ for (const child of n.children) {
558
+ traverse(child);
559
+ }
560
+ };
561
+ traverse(node);
562
+ return results;
563
+ }
564
+ extractModuleName(path) {
565
+ if (!path) {
566
+ return 'unknown';
567
+ }
568
+ const parts = path.split('/').pop()?.replace('.py', '') ?? 'unknown';
569
+ return parts;
570
+ }
571
+ extractDecorators(node) {
572
+ const decorators = [];
573
+ // Look for decorated_definition parent
574
+ if (node.parent?.type === 'decorated_definition') {
575
+ const decoratorNodes = this.findNodesByType(node.parent, 'decorator');
576
+ decorators.push(...decoratorNodes.map(d => d.text));
577
+ }
578
+ return decorators;
579
+ }
580
+ extractDocstring(bodyNode) {
581
+ // First statement in body might be a string (docstring)
582
+ const firstChild = bodyNode.namedChildren[0];
583
+ if (firstChild?.type === 'expression_statement') {
584
+ const expr = firstChild.child(0);
585
+ if (expr?.type === 'string') {
586
+ let docstring = expr.text;
587
+ // Remove outer quotes and any remaining inner quotes
588
+ if (docstring.startsWith('"""') && docstring.endsWith('"""')) {
589
+ docstring = docstring.slice(3, -3);
590
+ }
591
+ else if (docstring.startsWith("'''") && docstring.endsWith("'''")) {
592
+ docstring = docstring.slice(3, -3);
593
+ }
594
+ else if (docstring.startsWith('"') && docstring.endsWith('"')) {
595
+ docstring = docstring.slice(1, -1);
596
+ }
597
+ else if (docstring.startsWith("'") && docstring.endsWith("'")) {
598
+ docstring = docstring.slice(1, -1);
599
+ }
600
+ return docstring.trim();
601
+ }
602
+ }
603
+ return undefined;
604
+ }
605
+ containsYield(node) {
606
+ const yieldNodes = this.findNodesByType(node, 'yield');
607
+ return yieldNodes.length > 0;
608
+ }
609
+ extractBases(node) {
610
+ const bases = [];
611
+ for (const child of node.namedChildren) {
612
+ if (child.type === 'identifier') {
613
+ bases.push(child.text);
614
+ }
615
+ }
616
+ return bases;
617
+ }
618
+ extractProperty(node) {
619
+ // Simple property extraction from assignments
620
+ const leftNode = node.child(0);
621
+ if (leftNode?.type === 'identifier') {
622
+ return {
623
+ name: leftNode.text,
624
+ type: UNKNOWN_TYPE,
625
+ readonly: false,
626
+ };
627
+ }
628
+ return null;
629
+ }
630
+ extractExports(node) {
631
+ // Look for __all__ definition
632
+ const assignments = this.findNodesByType(node, 'assignment');
633
+ for (const assignment of assignments) {
634
+ const leftNode = assignment.child(0);
635
+ if (leftNode?.text === '__all__') {
636
+ const rightNode = assignment.child(2);
637
+ if (rightNode?.type === 'list') {
638
+ return rightNode.namedChildren
639
+ .filter(child => child.type === 'string')
640
+ .map(child => child.text.slice(1, -1)); // Remove quotes
641
+ }
642
+ }
643
+ }
644
+ return [];
645
+ }
646
+ collectSyntaxErrors(node, errors) {
647
+ if (node.hasError) {
648
+ errors.push({
649
+ type: 'syntax',
650
+ message: 'Syntax error in Python code',
651
+ line: node.startPosition.row + 1,
652
+ column: node.startPosition.column + 1,
653
+ });
654
+ }
655
+ for (const child of node.children) {
656
+ this.collectSyntaxErrors(child, errors);
657
+ }
658
+ }
659
+ generateStatistics(functions, classes, source) {
660
+ // Count only module-level functions, not class methods in the main count
661
+ const totalFunctions = functions.length;
662
+ const totalClasses = classes.length;
663
+ // Simple type hint coverage calculation
664
+ const functionsWithTypes = functions.filter(f => f.parameters.some(p => p.type.kind !== 'primitive' || p.type.name !== 'None') ||
665
+ f.returnType.kind !== 'primitive' ||
666
+ f.returnType.name !== 'None').length;
667
+ const typeHintsCoverage = totalFunctions > 0 ? (functionsWithTypes / totalFunctions) * 100 : 0;
668
+ return {
669
+ functionsAnalyzed: totalFunctions,
670
+ classesAnalyzed: totalClasses,
671
+ typeHintsCoverage,
672
+ estimatedComplexity: Math.min(source.length / 1000, 10), // Simple complexity estimate
673
+ };
674
+ }
675
+ }
676
+ //# sourceMappingURL=analyzer.js.map