Repository navigation
Expand file tree
/
Copy pathtest_javascript_modules.py
More file actions
1389 lines (1161 loc) · 35.2 KB
/
Copy pathtest_javascript_modules.py
File metadata and controls
1389 lines (1161 loc) · 35.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Comprehensive JavaScript module system parsing and relationship testing.
Tests CommonJS and ES6 module patterns, exports, and module resolution.
"""
from pathlib import Path
from typing import cast
from unittest.mock import MagicMock
import pytest
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
@pytest.fixture
def javascript_modules_project(temp_repo: Path) -> Path:
"""Create a comprehensive JavaScript project with module patterns."""
project_path = temp_repo / "javascript_modules_test"
project_path.mkdir()
# Create directory structure
(project_path / "src").mkdir()
(project_path / "lib").mkdir()
(project_path / "utils").mkdir()
(project_path / "models").mkdir()
(project_path / "node_modules").mkdir()
(project_path / "node_modules" / "lodash").mkdir()
# Create base files for testing imports
(project_path / "utils" / "constants.js").write_text(
"""
module.exports.API_URL = 'https://api.example.com';
module.exports.TIMEOUT = 5000;
module.exports.VERSION = '1.0.0';
"""
)
(project_path / "models" / "User.js").write_text(
"""
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
module.exports = User;
"""
)
(project_path / "lib" / "validators.js").write_text(
r"""
export function isEmail(email) {
return /^[^@]+@[^@]+\.[^@]+$/.test(email);
}
export function isPhone(phone) {
return /^\d{10}$/.test(phone);
}
export default function validate(type, value) {
switch(type) {
case 'email': return isEmail(value);
case 'phone': return isPhone(value);
default: return false;
}
}
"""
)
return project_path
def test_commonjs_module_exports(
javascript_modules_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test CommonJS module.exports patterns."""
test_file = javascript_modules_project / "commonjs_exports.js"
test_file.write_text(
"""
// Single export assignment
module.exports = function mainFunction() {
return "main";
};
// This pattern overwrites the previous export
module.exports = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: (a, b) => a * b,
PI: 3.14159,
config: {
debug: true,
version: "1.0.0"
}
};
// Individual property exports (on a different file)
// These would be ignored since module.exports was reassigned above
module.exports.ignored = "This won't be exported";
// Another file demonstrating individual exports
const helperFile = "helper.js";
// In helper.js:
// module.exports.helper1 = function() { return "helper1"; };
// module.exports.helper2 = function() { return "helper2"; };
// exports.helper3 = function() { return "helper3"; };
// Conditional exports
if (process.env.NODE_ENV === 'production') {
module.exports.productionOnly = function() {
return "prod";
};
}
// Function that returns module
function createModule() {
return {
method1: () => "method1",
method2: () => "method2"
};
}
// Dynamic module export
module.exports = createModule();
// Class export
class Calculator {
add(a, b) { return a + b; }
subtract(a, b) { return a - b; }
}
module.exports = Calculator;
// Mixed exports pattern (separate file example)
// exports.namedExport1 = function() {};
// exports.namedExport2 = function() {};
// module.exports.namedExport3 = function() {};
"""
)
# Create a file with exports shorthand
exports_file = javascript_modules_project / "exports_shorthand.js"
exports_file.write_text(
"""
// Using exports shorthand
exports.utilityA = function utilityA() {
return "A";
};
exports.utilityB = function utilityB() {
return "B";
};
exports.constant = "CONSTANT_VALUE";
exports.objectExport = {
nested: {
method: function() {
return "nested method";
}
}
};
// Arrow function exports
exports.arrowFunc = (x) => x * 2;
// Class export via exports
exports.ExportedClass = class ExportedClass {
constructor() {
this.value = "exported";
}
};
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=javascript_modules_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = javascript_modules_project.name
# Get all Function and Class node creation calls
function_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Function"
]
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
# Should create nodes for exported functions and classes
all_nodes = function_calls + class_calls
exported_nodes = [
call
for call in all_nodes
if any(
file in call[0][1]["qualified_name"]
for file in ["commonjs_exports", "exports_shorthand"]
)
]
assert len(exported_nodes) >= 5, (
f"Expected at least 5 exported functions/classes, found {len(exported_nodes)}"
)
# Check specific exports in exports_shorthand
created_functions = {call[0][1]["qualified_name"] for call in function_calls}
expected_functions = [
f"{project_name}.exports_shorthand.utilityA",
f"{project_name}.exports_shorthand.utilityB",
f"{project_name}.exports_shorthand.arrowFunc",
]
for expected in expected_functions:
assert expected in created_functions, f"Missing exported function: {expected}"
def test_es6_export_patterns(
javascript_modules_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test ES6 export patterns including default and named exports."""
test_file = javascript_modules_project / "es6_exports.js"
test_file.write_text(
"""
// Named exports
export const API_URL = 'https://api.example.com';
export const TIMEOUT = 5000;
export let counter = 0;
export var deprecated = "old";
export function fetchData(url) {
return fetch(url).then(res => res.json());
}
export async function fetchDataAsync(url) {
const response = await fetch(url);
return response.json();
}
export const arrowFunction = (x) => x * 2;
export class DataService {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
getData(endpoint) {
return fetchData(this.baseUrl + endpoint);
}
}
// Default export (function)
export default function processData(data) {
return data.map(item => ({
...item,
processed: true
}));
}
// Can't have multiple defaults, but showing the pattern
// export default class DefaultClass {} // This would be an error
// Export list
const helper1 = () => "helper1";
const helper2 = () => "helper2";
const helper3 = () => "helper3";
export { helper1, helper2, helper3 };
// Export with rename
const internalName = "internal";
export { internalName as externalName };
// Re-exports from other modules
export { isEmail, isPhone } from './lib/validators';
export { default as Validator } from './lib/validators';
export * from './utils/constants';
// Namespace export
export * as validationUtils from './lib/validators';
// Export at declaration
export let { destructured1, destructured2 } = {
destructured1: "d1",
destructured2: "d2"
};
// Export functions with different patterns
export function* generatorFunction() {
yield 1;
yield 2;
yield 3;
}
export const asyncArrow = async () => {
return await Promise.resolve("async arrow");
};
// Complex export expressions
export const complexExport = (() => {
const private = "hidden";
return {
public: "visible",
method() {
return private;
}
};
})();
// Type-like exports (even in JS)
export const UserType = {
ADMIN: 'admin',
USER: 'user',
GUEST: 'guest'
};
"""
)
# Create another file for testing re-exports
reexport_file = javascript_modules_project / "reexports.js"
reexport_file.write_text(
"""
// Re-export patterns
export { fetchData, DataService } from './es6_exports';
export { default } from './es6_exports';
export { default as processDataRenamed } from './es6_exports';
// Aggregate exports
export * from './es6_exports';
export * from './lib/validators';
// Namespace re-exports
export * as exports from './es6_exports';
export * as validators from './lib/validators';
// Mixed re-exports and local exports
export { API_URL as API_ENDPOINT } from './es6_exports';
export const localExport = "local";
// Re-export with local processing
import { fetchData as originalFetch } from './es6_exports';
export function enhancedFetch(url, options) {
console.log('Fetching:', url);
return originalFetch(url, options);
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=javascript_modules_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = javascript_modules_project.name
# Get all Function and Class nodes
function_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Function"
]
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
# Verify ES6 exported functions and classes
created_functions = {call[0][1]["qualified_name"] for call in function_calls}
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
expected_functions = [
f"{project_name}.es6_exports.fetchData",
f"{project_name}.es6_exports.fetchDataAsync",
f"{project_name}.es6_exports.arrowFunction",
f"{project_name}.es6_exports.processData", # default export
f"{project_name}.es6_exports.generatorFunction",
f"{project_name}.es6_exports.asyncArrow",
f"{project_name}.reexports.enhancedFetch",
]
for expected in expected_functions:
assert expected in created_functions, (
f"Missing ES6 exported function: {expected}"
)
expected_classes = [
f"{project_name}.es6_exports.DataService",
]
for expected in expected_classes:
assert expected in created_classes, f"Missing ES6 exported class: {expected}"
# Check import relationships for re-exports
import_relationships = [
c
for c in cast(MagicMock, mock_ingestor.ensure_relationship_batch).call_args_list
if c.args[1] == "IMPORTS"
]
reexport_imports = [
call for call in import_relationships if "reexports" in call.args[0][2]
]
assert len(reexport_imports) >= 3, (
f"Expected at least 3 re-export imports, found {len(reexport_imports)}"
)
def test_mixed_module_systems(
javascript_modules_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test files using both CommonJS and ES6 modules."""
test_file = javascript_modules_project / "mixed_modules.js"
test_file.write_text(
"""
// Mixed CommonJS and ES6 - This is technically invalid but sometimes seen
// ES6 imports
import React from 'react';
import { useState, useEffect } from 'react';
import * as utils from './utils';
// CommonJS require
const fs = require('fs');
const path = require('path');
const { readFile, writeFile } = require('fs').promises;
// ES6 exports
export const config = {
apiUrl: process.env.API_URL || 'http://localhost:3000',
timeout: 5000
};
export function processFile(filename) {
const fullPath = path.join(__dirname, filename);
return readFile(fullPath, 'utf8');
}
// CommonJS exports (would override ES6 in practice)
module.exports.legacyFunction = function() {
return "legacy";
};
// Dynamic imports
export async function loadModule(moduleName) {
const module = await import(`./${moduleName}`);
return module.default || module;
}
// Conditional exports based on environment
if (typeof window !== 'undefined') {
// Browser environment
export const browserOnly = true;
} else {
// Node environment
module.exports.nodeOnly = true;
}
// Class using both module systems
export class MixedService {
constructor() {
// Using CommonJS require
this.validator = require('./lib/validators');
// Using ES6 import result
this.React = React;
}
async loadDynamic(name) {
// Dynamic import
const mod = await import(`./dynamic/${name}`);
return mod;
}
}
// Function that uses both
export function hybridFunction() {
const commonjsModule = require('./models/User');
const [state, setState] = useState(null);
return {
User: commonjsModule,
state: state
};
}
"""
)
# Create a UMD pattern file
umd_file = javascript_modules_project / "umd_module.js"
umd_file.write_text(
"""
// UMD (Universal Module Definition) pattern
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['exports', 'react'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('react'));
} else {
// Browser globals
factory((root.MyModule = {}), root.React);
}
}(typeof self !== 'undefined' ? self : this, function (exports, React) {
'use strict';
// Module implementation
function MyComponent(props) {
return React.createElement('div', null, props.children);
}
function utility() {
return "utility function";
}
class MyClass {
constructor() {
this.name = "MyClass";
}
render() {
return MyComponent({ children: this.name });
}
}
// Exports
exports.MyComponent = MyComponent;
exports.utility = utility;
exports.MyClass = MyClass;
exports.default = MyComponent;
// Also attach to exports for CommonJS default export pattern
if (typeof module !== 'undefined' && module.exports) {
module.exports = exports;
}
}));
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=javascript_modules_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check that mixed module imports are captured
import_relationships = [
c
for c in cast(MagicMock, mock_ingestor.ensure_relationship_batch).call_args_list
if c.args[1] == "IMPORTS"
]
mixed_imports = [
call for call in import_relationships if "mixed_modules" in call.args[0][2]
]
# Should have both ES6 and CommonJS imports
imported_modules = [call.args[2][2] for call in mixed_imports]
# Check for ES6 imports
assert any("react" in module.lower() for module in imported_modules), (
"Missing ES6 React import"
)
# Check for CommonJS requires
assert any("fs" in module for module in imported_modules), (
"Missing CommonJS fs require"
)
# Check that functions and classes are created
function_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Function"
]
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
mixed_functions = [
call
for call in function_calls
if "mixed_modules" in call[0][1]["qualified_name"]
]
assert len(mixed_functions) >= 3, (
f"Expected at least 3 functions in mixed modules, found {len(mixed_functions)}"
)
# Check UMD pattern parsing
umd_functions = [
call for call in function_calls if "umd_module" in call[0][1]["qualified_name"]
]
umd_classes = [
call for call in class_calls if "umd_module" in call[0][1]["qualified_name"]
]
assert len(umd_functions) >= 2, (
f"Expected at least 2 UMD functions, found {len(umd_functions)}"
)
assert len(umd_classes) >= 1, (
f"Expected at least 1 UMD class, found {len(umd_classes)}"
)
def test_circular_dependencies(
javascript_modules_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test circular dependency handling in modules."""
# Create circular dependency files
module_a = javascript_modules_project / "circular_a.js"
module_a.write_text(
"""
// Circular dependency - A imports B
const B = require('./circular_b');
class A {
constructor() {
this.name = "A";
this.b = null;
}
setB(b) {
this.b = b;
}
callB() {
if (this.b) {
return this.b.getName();
}
return "No B";
}
getName() {
return this.name;
}
}
module.exports = A;
// Using B after export to handle circular dependency
if (B) {
const bInstance = new B();
console.log("B instance in A:", bInstance.getName());
}
"""
)
module_b = javascript_modules_project / "circular_b.js"
module_b.write_text(
"""
// Circular dependency - B imports A
const A = require('./circular_a');
class B {
constructor() {
this.name = "B";
this.a = null;
}
setA(a) {
this.a = a;
}
callA() {
if (this.a) {
return this.a.getName();
}
return "No A";
}
getName() {
return this.name;
}
}
module.exports = B;
// Using A after export to handle circular dependency
if (A) {
const aInstance = new A();
console.log("A instance in B:", aInstance.getName());
}
"""
)
# ES6 circular dependencies
es6_circular_a = javascript_modules_project / "es6_circular_a.js"
es6_circular_a.write_text(
"""
// ES6 Circular dependency - A imports B
import { B, createB } from './es6_circular_b.js';
export class A {
constructor() {
this.name = "A";
this.b = null;
}
setB(b) {
this.b = b;
}
getName() {
return this.name;
}
}
export function createA() {
return new A();
}
// Function that uses B
export function useB() {
const b = createB();
return b.getName();
}
"""
)
es6_circular_b = javascript_modules_project / "es6_circular_b.js"
es6_circular_b.write_text(
"""
// ES6 Circular dependency - B imports A
import { A, createA } from './es6_circular_a.js';
export class B {
constructor() {
this.name = "B";
this.a = null;
}
setA(a) {
this.a = a;
}
getName() {
return this.name;
}
}
export function createB() {
return new B();
}
// Function that uses A
export function useA() {
const a = createA();
return a.getName();
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=javascript_modules_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check that circular imports are captured
import_relationships = [
c
for c in cast(MagicMock, mock_ingestor.ensure_relationship_batch).call_args_list
if c.args[1] == "IMPORTS"
]
# CommonJS circular imports
circular_imports = [
call
for call in import_relationships
if "circular_a" in call.args[0][2] or "circular_b" in call.args[0][2]
]
# Should have A importing B and B importing A
a_imports_b = any(
"circular_a" in call.args[0][2] and "circular_b" in call.args[2][2]
for call in circular_imports
)
b_imports_a = any(
"circular_b" in call.args[0][2] and "circular_a" in call.args[2][2]
for call in circular_imports
)
assert a_imports_b, "circular_a should import circular_b"
assert b_imports_a, "circular_b should import circular_a"
# ES6 circular imports
es6_circular_imports = [
call
for call in import_relationships
if "es6_circular_a" in call.args[0][2] or "es6_circular_b" in call.args[0][2]
]
es6_a_imports_b = any(
"es6_circular_a" in call.args[0][2] and "es6_circular_b" in call.args[2][2]
for call in es6_circular_imports
)
es6_b_imports_a = any(
"es6_circular_b" in call.args[0][2] and "es6_circular_a" in call.args[2][2]
for call in es6_circular_imports
)
assert es6_a_imports_b, "es6_circular_a should import es6_circular_b"
assert es6_b_imports_a, "es6_circular_b should import es6_circular_a"
def test_dynamic_exports(
javascript_modules_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test dynamic and conditional export patterns."""
test_file = javascript_modules_project / "dynamic_exports.js"
test_file.write_text(
"""
// Dynamic property exports
const methods = ['get', 'post', 'put', 'delete'];
methods.forEach(method => {
exports[method] = function(url, data) {
return fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(data)
});
};
});
// Conditional exports based on environment
if (process.env.NODE_ENV === 'development') {
exports.debug = function(message) {
console.log('[DEBUG]:', message);
};
exports.DevTools = class DevTools {
constructor() {
this.enabled = true;
}
log(message) {
if (this.enabled) {
console.log('[DevTools]:', message);
}
}
};
}
// Dynamic module.exports assignment
const moduleConfig = {
version: '1.0.0',
features: []
};
if (process.env.FEATURE_A) {
moduleConfig.features.push('featureA');
moduleConfig.featureA = function() {
return "Feature A enabled";
};
}
if (process.env.FEATURE_B) {
moduleConfig.features.push('featureB');
moduleConfig.featureB = function() {
return "Feature B enabled";
};
}
module.exports = moduleConfig;
// Factory pattern exports
function createAPI(config) {
return {
get(endpoint) {
return fetch(config.baseUrl + endpoint);
},
post(endpoint, data) {
return fetch(config.baseUrl + endpoint, {
method: 'POST',
body: JSON.stringify(data)
});
}
};
}
module.exports = createAPI({ baseUrl: 'https://api.example.com' });
// Computed property exports
const operations = {
ADD: 'add',
SUBTRACT: 'subtract',
MULTIPLY: 'multiply',
DIVIDE: 'divide'
};
Object.entries(operations).forEach(([key, value]) => {
exports[value] = function(a, b) {
switch(value) {
case 'add': return a + b;
case 'subtract': return a - b;
case 'multiply': return a * b;
case 'divide': return a / b;
}
};
exports[`${value}Async`] = async function(a, b) {
return new Promise(resolve => {
setTimeout(() => resolve(exports[value](a, b)), 100);
});
};
});
// Proxy-based exports
const handler = {
get(target, property) {
if (property in target) {
return target[property];
}
return function() {
console.log(`Method ${property} not implemented`);
};
}
};
module.exports = new Proxy({
implementedMethod() {
return "This method exists";
}
}, handler);
"""
)
# Create ES6 dynamic exports
es6_dynamic = javascript_modules_project / "es6_dynamic_exports.js"
es6_dynamic.write_text(
"""
// ES6 dynamic exports using export declarations
const endpoints = {
users: '/api/users',
posts: '/api/posts',
comments: '/api/comments'
};
// Can't dynamically create named exports, but can export dynamic object
export const api = Object.entries(endpoints).reduce((acc, [key, endpoint]) => {
acc[key] = {
getAll: () => fetch(endpoint),
getById: (id) => fetch(`${endpoint}/${id}`),
create: (data) => fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
}),
update: (id, data) => fetch(`${endpoint}/${id}`, {
method: 'PUT',
body: JSON.stringify(data)
}),
delete: (id) => fetch(`${endpoint}/${id}`, {
method: 'DELETE'
})
};
return acc;
}, {});
// Dynamic default export based on conditions
let DefaultExport;