Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

file.test.ts 23 KB

You have to be logged in to leave a comment. Sign In
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
  1. import * as fs from 'fs';
  2. import path from 'path';
  3. import { globSync } from 'glob';
  4. import yaml from 'js-yaml';
  5. import cliState from '../../src/cliState';
  6. import {
  7. getResolvedRelativePath,
  8. maybeLoadConfigFromExternalFile,
  9. maybeLoadFromExternalFile,
  10. } from '../../src/util/file';
  11. import { safeJoin, safeResolve } from '../../src/util/file.node';
  12. import {
  13. isAudioFile,
  14. isImageFile,
  15. isJavascriptFile,
  16. isVideoFile,
  17. } from '../../src/util/fileExtensions';
  18. jest.mock('fs', () => ({
  19. ...jest.requireActual('fs'),
  20. readFileSync: jest.fn(),
  21. existsSync: jest.fn(),
  22. }));
  23. jest.mock('glob');
  24. describe('file utilities', () => {
  25. // Helper to create platform-appropriate file URLs
  26. const getFileUrl = (path: string) => {
  27. return process.platform === 'win32'
  28. ? `file:///C:/${path.replace(/\\/g, '/')}`
  29. : `file:///${path}`;
  30. };
  31. describe('isJavascriptFile', () => {
  32. it('identifies JavaScript and TypeScript files', () => {
  33. expect(isJavascriptFile('test.js')).toBe(true);
  34. expect(isJavascriptFile('test.cjs')).toBe(true);
  35. expect(isJavascriptFile('test.mjs')).toBe(true);
  36. expect(isJavascriptFile('test.ts')).toBe(true);
  37. expect(isJavascriptFile('test.cts')).toBe(true);
  38. expect(isJavascriptFile('test.mts')).toBe(true);
  39. expect(isJavascriptFile('test.txt')).toBe(false);
  40. expect(isJavascriptFile('test.py')).toBe(false);
  41. });
  42. });
  43. describe('isImageFile', () => {
  44. it('identifies image files correctly', () => {
  45. expect(isImageFile('photo.jpg')).toBe(true);
  46. expect(isImageFile('image.jpeg')).toBe(true);
  47. expect(isImageFile('icon.png')).toBe(true);
  48. expect(isImageFile('anim.gif')).toBe(true);
  49. expect(isImageFile('image.bmp')).toBe(true);
  50. expect(isImageFile('photo.webp')).toBe(true);
  51. expect(isImageFile('icon.svg')).toBe(true);
  52. expect(isImageFile('doc.pdf')).toBe(false);
  53. expect(isImageFile('noextension')).toBe(false);
  54. });
  55. });
  56. describe('isVideoFile', () => {
  57. it('identifies video files correctly', () => {
  58. expect(isVideoFile('video.mp4')).toBe(true);
  59. expect(isVideoFile('clip.webm')).toBe(true);
  60. expect(isVideoFile('video.ogg')).toBe(true);
  61. expect(isVideoFile('movie.mov')).toBe(true);
  62. expect(isVideoFile('video.avi')).toBe(true);
  63. expect(isVideoFile('clip.wmv')).toBe(true);
  64. expect(isVideoFile('movie.mkv')).toBe(true);
  65. expect(isVideoFile('video.m4v')).toBe(true);
  66. expect(isVideoFile('doc.pdf')).toBe(false);
  67. expect(isVideoFile('noextension')).toBe(false);
  68. });
  69. });
  70. describe('isAudioFile', () => {
  71. it('identifies audio files correctly', () => {
  72. expect(isAudioFile('sound.wav')).toBe(true);
  73. expect(isAudioFile('music.mp3')).toBe(true);
  74. expect(isAudioFile('audio.ogg')).toBe(true);
  75. expect(isAudioFile('sound.aac')).toBe(true);
  76. expect(isAudioFile('music.m4a')).toBe(true);
  77. expect(isAudioFile('audio.flac')).toBe(true);
  78. expect(isAudioFile('sound.wma')).toBe(true);
  79. expect(isAudioFile('music.aiff')).toBe(true);
  80. expect(isAudioFile('voice.opus')).toBe(true);
  81. expect(isAudioFile('doc.pdf')).toBe(false);
  82. expect(isAudioFile('noextension')).toBe(false);
  83. });
  84. });
  85. describe('maybeLoadFromExternalFile', () => {
  86. const mockFileContent = 'test content';
  87. const originalBasePath = cliState.basePath;
  88. beforeEach(() => {
  89. jest.resetAllMocks();
  90. jest.mocked(fs.existsSync).mockReturnValue(true);
  91. jest.mocked(fs.readFileSync).mockReturnValue(mockFileContent);
  92. cliState.basePath = '/mock/base/path';
  93. });
  94. afterEach(() => {
  95. cliState.basePath = originalBasePath;
  96. });
  97. it('should return non-string inputs as-is', () => {
  98. expect(maybeLoadFromExternalFile({ foo: 'bar' })).toEqual({ foo: 'bar' });
  99. expect(maybeLoadFromExternalFile(null)).toBeNull();
  100. expect(maybeLoadFromExternalFile(undefined)).toBeUndefined();
  101. });
  102. it('should return strings that do not start with file:// as-is', () => {
  103. expect(maybeLoadFromExternalFile('just a string')).toBe('just a string');
  104. expect(maybeLoadFromExternalFile('/path/to/file')).toBe('/path/to/file');
  105. });
  106. it('should load JSON files', () => {
  107. const mockData = { key: 'value' };
  108. jest.mocked(fs.existsSync).mockReturnValue(true);
  109. jest.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(mockData));
  110. const result = maybeLoadFromExternalFile('file://test.json');
  111. expect(result).toEqual(mockData);
  112. });
  113. it('should load YAML files', () => {
  114. const mockData = { key: 'value' };
  115. jest.mocked(fs.existsSync).mockReturnValue(true);
  116. jest.mocked(fs.readFileSync).mockReturnValue(yaml.dump(mockData));
  117. const result = maybeLoadFromExternalFile('file://test.yaml');
  118. expect(result).toEqual(mockData);
  119. });
  120. it('should load CSV files', () => {
  121. const csvContent = 'name,age\nJohn,30\nJane,25';
  122. jest.mocked(fs.existsSync).mockReturnValue(true);
  123. jest.mocked(fs.readFileSync).mockReturnValue(csvContent);
  124. const result = maybeLoadFromExternalFile('file://test.csv');
  125. expect(result).toEqual([
  126. { name: 'John', age: '30' },
  127. { name: 'Jane', age: '25' },
  128. ]);
  129. });
  130. it('should handle glob patterns for YAML files', () => {
  131. const mockFiles = ['/mock/base/path/scenario1.yaml', '/mock/base/path/scenario2.yaml'];
  132. const mockData1 = { test: 'scenario1' };
  133. const mockData2 = { test: 'scenario2' };
  134. jest.mocked(globSync).mockReturnValue(mockFiles);
  135. jest
  136. .mocked(fs.readFileSync)
  137. .mockReturnValueOnce(yaml.dump(mockData1))
  138. .mockReturnValueOnce(yaml.dump(mockData2));
  139. const result = maybeLoadFromExternalFile('file://scenarios/*.yaml');
  140. expect(result).toEqual([mockData1, mockData2]);
  141. expect(globSync).toHaveBeenCalledWith(path.resolve('/mock/base/path', 'scenarios/*.yaml'), {
  142. windowsPathsNoEscape: true,
  143. });
  144. });
  145. it('should handle glob patterns for JSON files', () => {
  146. const mockFiles = ['/mock/base/path/data1.json', '/mock/base/path/data2.json'];
  147. const mockData1 = { id: 1 };
  148. const mockData2 = { id: 2 };
  149. jest.mocked(globSync).mockReturnValue(mockFiles);
  150. jest
  151. .mocked(fs.readFileSync)
  152. .mockReturnValueOnce(JSON.stringify(mockData1))
  153. .mockReturnValueOnce(JSON.stringify(mockData2));
  154. const result = maybeLoadFromExternalFile('file://data*.json');
  155. expect(result).toEqual([mockData1, mockData2]);
  156. });
  157. it('should handle glob patterns with arrays in files', () => {
  158. const mockFiles = ['/mock/base/path/tests1.yaml', '/mock/base/path/tests2.yaml'];
  159. const mockData1 = [{ test: 'a' }, { test: 'b' }];
  160. const mockData2 = [{ test: 'c' }, { test: 'd' }];
  161. jest.mocked(globSync).mockReturnValue(mockFiles);
  162. jest
  163. .mocked(fs.readFileSync)
  164. .mockReturnValueOnce(yaml.dump(mockData1))
  165. .mockReturnValueOnce(yaml.dump(mockData2));
  166. const result = maybeLoadFromExternalFile('file://tests*.yaml');
  167. expect(result).toEqual([{ test: 'a' }, { test: 'b' }, { test: 'c' }, { test: 'd' }]);
  168. });
  169. it('should handle single-column CSV files consistently with glob patterns', () => {
  170. const mockFiles = ['/mock/base/path/data1.csv', '/mock/base/path/data2.csv'];
  171. const csvContent1 = 'name\nAlice\nBob';
  172. const csvContent2 = 'name\nCharlie\nDavid';
  173. jest.mocked(globSync).mockReturnValue(mockFiles);
  174. jest
  175. .mocked(fs.readFileSync)
  176. .mockReturnValueOnce(csvContent1)
  177. .mockReturnValueOnce(csvContent2);
  178. const result = maybeLoadFromExternalFile('file://data*.csv');
  179. // Should return array of values, not objects
  180. expect(result).toEqual(['Alice', 'Bob', 'Charlie', 'David']);
  181. });
  182. it('should handle multi-column CSV files with glob patterns', () => {
  183. const mockFiles = ['/mock/base/path/users.csv'];
  184. const csvContent = 'name,age\nAlice,30\nBob,25';
  185. jest.mocked(globSync).mockReturnValue(mockFiles);
  186. jest.mocked(fs.readFileSync).mockReturnValue(csvContent);
  187. const result = maybeLoadFromExternalFile('file://users*.csv');
  188. // Should return array of objects for multi-column CSV
  189. expect(result).toEqual([
  190. { name: 'Alice', age: '30' },
  191. { name: 'Bob', age: '25' },
  192. ]);
  193. });
  194. it('should handle empty YAML files in glob patterns', () => {
  195. const mockFiles = ['/mock/base/path/empty.yaml', '/mock/base/path/data.yaml'];
  196. const mockData = { test: 'data' };
  197. jest.mocked(globSync).mockReturnValue(mockFiles);
  198. jest
  199. .mocked(fs.readFileSync)
  200. .mockReturnValueOnce('') // Empty file
  201. .mockReturnValueOnce(yaml.dump(mockData));
  202. const result = maybeLoadFromExternalFile('file://**.yaml');
  203. // Should skip empty file and only include valid data
  204. expect(result).toEqual([mockData]);
  205. });
  206. it('should throw error when glob pattern matches no files', () => {
  207. jest.mocked(globSync).mockReturnValue([]);
  208. expect(() => maybeLoadFromExternalFile('file://nonexistent/*.yaml')).toThrow(
  209. `No files found matching pattern: ${path.resolve('/mock/base/path', 'nonexistent/*.yaml')}`,
  210. );
  211. });
  212. it('should throw error when file does not exist', () => {
  213. jest.mocked(fs.existsSync).mockReturnValue(false);
  214. expect(() => maybeLoadFromExternalFile('file://nonexistent.yaml')).toThrow(
  215. `File does not exist: ${path.resolve('/mock/base/path', 'nonexistent.yaml')}`,
  216. );
  217. });
  218. it('should handle arrays of file paths', () => {
  219. const mockData1 = { key: 'value1' };
  220. const mockData2 = { key: 'value2' };
  221. jest.mocked(fs.existsSync).mockReturnValue(true);
  222. jest
  223. .mocked(fs.readFileSync)
  224. .mockReturnValueOnce(JSON.stringify(mockData1))
  225. .mockReturnValueOnce(JSON.stringify(mockData2));
  226. const result = maybeLoadFromExternalFile(['file://test1.json', 'file://test2.json']);
  227. expect(result).toEqual([mockData1, mockData2]);
  228. });
  229. it('should use basePath when resolving file paths', () => {
  230. const basePath = '/base/path';
  231. cliState.basePath = basePath;
  232. jest.mocked(fs.readFileSync).mockReturnValue(mockFileContent);
  233. maybeLoadFromExternalFile('file://test.txt');
  234. const expectedPath = path.resolve(basePath, 'test.txt');
  235. expect(fs.existsSync).toHaveBeenCalledWith(expectedPath);
  236. expect(fs.readFileSync).toHaveBeenCalledWith(expectedPath, 'utf8');
  237. cliState.basePath = undefined;
  238. });
  239. it('should handle relative paths correctly', () => {
  240. const basePath = './relative/path';
  241. cliState.basePath = basePath;
  242. jest.mocked(fs.readFileSync).mockReturnValue(mockFileContent);
  243. maybeLoadFromExternalFile('file://test.txt');
  244. const expectedPath = path.resolve(basePath, 'test.txt');
  245. expect(fs.existsSync).toHaveBeenCalledWith(expectedPath);
  246. expect(fs.readFileSync).toHaveBeenCalledWith(expectedPath, 'utf8');
  247. cliState.basePath = undefined;
  248. });
  249. it('should handle a path with environment variables in Nunjucks template', () => {
  250. process.env.TEST_ROOT_PATH = '/root/dir';
  251. const input = 'file://{{ env.TEST_ROOT_PATH }}/test.txt';
  252. jest.mocked(fs.existsSync).mockReturnValue(true);
  253. const expectedPath = path.resolve(`${process.env.TEST_ROOT_PATH}/test.txt`);
  254. maybeLoadFromExternalFile(input);
  255. expect(fs.existsSync).toHaveBeenCalledWith(expectedPath);
  256. expect(fs.readFileSync).toHaveBeenCalledWith(expectedPath, 'utf8');
  257. delete process.env.TEST_ROOT_PATH;
  258. });
  259. it('should ignore basePath when file path is absolute', () => {
  260. const basePath = '/base/path';
  261. cliState.basePath = basePath;
  262. jest.mocked(fs.readFileSync).mockReturnValue(mockFileContent);
  263. maybeLoadFromExternalFile('file:///absolute/path/test.txt');
  264. const expectedPath = path.resolve('/absolute/path/test.txt');
  265. expect(fs.existsSync).toHaveBeenCalledWith(expectedPath);
  266. expect(fs.readFileSync).toHaveBeenCalledWith(expectedPath, 'utf8');
  267. cliState.basePath = undefined;
  268. });
  269. it('should handle list of paths', () => {
  270. const basePath = './relative/path';
  271. cliState.basePath = basePath;
  272. const input = ['file://test1.txt', 'file://test2.txt', 'file://test3.txt'];
  273. // Mock readFileSync to return consistent data
  274. const mockFileData = 'test content';
  275. jest.mocked(fs.readFileSync).mockReturnValue(mockFileData);
  276. maybeLoadFromExternalFile(input);
  277. expect(fs.existsSync).toHaveBeenCalledTimes(3);
  278. expect(fs.existsSync).toHaveBeenCalledWith(path.resolve(basePath, 'test1.txt'));
  279. expect(fs.existsSync).toHaveBeenCalledWith(path.resolve(basePath, 'test2.txt'));
  280. expect(fs.existsSync).toHaveBeenCalledWith(path.resolve(basePath, 'test3.txt'));
  281. expect(fs.readFileSync).toHaveBeenCalledTimes(3);
  282. expect(fs.readFileSync).toHaveBeenCalledWith(path.resolve(basePath, 'test1.txt'), 'utf8');
  283. expect(fs.readFileSync).toHaveBeenCalledWith(path.resolve(basePath, 'test2.txt'), 'utf8');
  284. expect(fs.readFileSync).toHaveBeenCalledWith(path.resolve(basePath, 'test3.txt'), 'utf8');
  285. cliState.basePath = undefined;
  286. });
  287. it('should recursively load file references in objects', () => {
  288. jest.mocked(fs.readFileSync).mockReturnValueOnce('{"foo": 1}').mockReturnValueOnce('bar');
  289. const config = {
  290. data: 'file://data.json',
  291. nested: {
  292. text: 'file://note.txt',
  293. },
  294. };
  295. const result = maybeLoadConfigFromExternalFile(config);
  296. expect(fs.readFileSync).toHaveBeenCalledTimes(2);
  297. expect(result).toEqual({ data: { foo: 1 }, nested: { text: 'bar' } });
  298. });
  299. it('should handle arrays and nested structures', () => {
  300. jest.mocked(fs.readFileSync).mockReturnValueOnce('test content');
  301. const config = {
  302. items: ['file://test.txt', 'normal string'],
  303. nullValue: null,
  304. emptyArray: [],
  305. nested: {
  306. deep: {
  307. value: 'file://test.txt',
  308. },
  309. },
  310. };
  311. const result = maybeLoadConfigFromExternalFile(config);
  312. expect(fs.readFileSync).toHaveBeenCalledTimes(2);
  313. expect(result).toEqual({
  314. items: ['test content', 'normal string'],
  315. nullValue: null,
  316. emptyArray: [],
  317. nested: {
  318. deep: {
  319. value: 'test content',
  320. },
  321. },
  322. });
  323. });
  324. it('should handle primitive values safely', () => {
  325. expect(maybeLoadConfigFromExternalFile('normal string')).toBe('normal string');
  326. expect(maybeLoadConfigFromExternalFile(42)).toBe(42);
  327. expect(maybeLoadConfigFromExternalFile(true)).toBe(true);
  328. expect(maybeLoadConfigFromExternalFile(null)).toBeNull();
  329. expect(maybeLoadConfigFromExternalFile(undefined)).toBeUndefined();
  330. });
  331. it('should handle deeply nested objects with multiple file references', () => {
  332. jest
  333. .mocked(fs.readFileSync)
  334. .mockReturnValueOnce('{"nested": {"value": 123}}')
  335. .mockReturnValueOnce('["item1", "item2"]')
  336. .mockReturnValueOnce('deeply nested content');
  337. const config = {
  338. level1: {
  339. level2: {
  340. level3: {
  341. data: 'file://deep.json',
  342. items: 'file://items.json',
  343. level4: {
  344. content: 'file://content.txt',
  345. static: 'unchanged',
  346. },
  347. },
  348. },
  349. },
  350. topLevel: 'unchanged',
  351. };
  352. const result = maybeLoadConfigFromExternalFile(config);
  353. expect(fs.readFileSync).toHaveBeenCalledTimes(3);
  354. expect(result).toEqual({
  355. level1: {
  356. level2: {
  357. level3: {
  358. data: { nested: { value: 123 } },
  359. items: ['item1', 'item2'],
  360. level4: {
  361. content: 'deeply nested content',
  362. static: 'unchanged',
  363. },
  364. },
  365. },
  366. },
  367. topLevel: 'unchanged',
  368. });
  369. });
  370. it('should handle arrays with mixed content types including file references', () => {
  371. jest
  372. .mocked(fs.readFileSync)
  373. .mockReturnValueOnce('{"config": "loaded"}')
  374. .mockReturnValueOnce('text content')
  375. .mockReturnValueOnce('{"config": "loaded"}');
  376. const config = {
  377. mixedArray: [
  378. 'string value',
  379. 42,
  380. true,
  381. { normal: 'object' },
  382. 'file://config.json',
  383. ['nested', 'array', 'file://text.txt'],
  384. null,
  385. { nested: { file: 'file://config.json' } },
  386. ],
  387. };
  388. const result = maybeLoadConfigFromExternalFile(config);
  389. expect(result).toEqual({
  390. mixedArray: [
  391. 'string value',
  392. 42,
  393. true,
  394. { normal: 'object' },
  395. { config: 'loaded' },
  396. ['nested', 'array', 'text content'],
  397. null,
  398. { nested: { file: { config: 'loaded' } } },
  399. ],
  400. });
  401. });
  402. it('should handle edge cases with empty objects and arrays', () => {
  403. const config = {
  404. emptyObject: {},
  405. emptyArray: [],
  406. arrayWithEmpties: [{}, [], null, undefined, ''],
  407. nested: {
  408. empty: {},
  409. moreNested: {
  410. stillEmpty: {},
  411. emptyArray: [],
  412. },
  413. },
  414. };
  415. const result = maybeLoadConfigFromExternalFile(config);
  416. expect(result).toEqual(config);
  417. });
  418. it('should preserve object keys that contain special characters', () => {
  419. jest.mocked(fs.readFileSync).mockReturnValueOnce('special content');
  420. const config = {
  421. 'key-with-dashes': 'file://special.txt',
  422. 'key.with.dots': 'normal value',
  423. 'key with spaces': { nested: 'value' },
  424. 'key@with#symbols': ['array', 'value'],
  425. 123: 'numeric key',
  426. '': 'empty key',
  427. };
  428. const result = maybeLoadConfigFromExternalFile(config);
  429. expect(result).toEqual({
  430. 'key-with-dashes': 'special content',
  431. 'key.with.dots': 'normal value',
  432. 'key with spaces': { nested: 'value' },
  433. 'key@with#symbols': ['array', 'value'],
  434. 123: 'numeric key',
  435. '': 'empty key',
  436. });
  437. });
  438. it('should handle objects with prototype pollution attempts safely', () => {
  439. jest.mocked(fs.readFileSync).mockReturnValueOnce('malicious content');
  440. const config = {
  441. __proto__: 'file://malicious.txt',
  442. constructor: { normal: 'value' },
  443. prototype: ['safe', 'array'],
  444. normal: 'safe value',
  445. };
  446. const result = maybeLoadConfigFromExternalFile(config);
  447. expect(result).toEqual({
  448. __proto__: 'malicious content',
  449. constructor: { normal: 'value' },
  450. prototype: ['safe', 'array'],
  451. normal: 'safe value',
  452. });
  453. });
  454. it('should handle very large nested structures efficiently', () => {
  455. jest.mocked(fs.readFileSync).mockReturnValue('file content');
  456. // Create a large nested structure
  457. const createNestedConfig = (depth: number): any => {
  458. if (depth === 0) {
  459. return 'file://test.txt';
  460. }
  461. return {
  462. [`level${depth}`]: createNestedConfig(depth - 1),
  463. [`static${depth}`]: `value at depth ${depth}`,
  464. };
  465. };
  466. const config = createNestedConfig(10);
  467. const result = maybeLoadConfigFromExternalFile(config);
  468. // Should have loaded the file reference at the deepest level
  469. expect(fs.readFileSync).toHaveBeenCalledTimes(1);
  470. // Verify the structure is preserved
  471. let current = result;
  472. for (let i = 10; i > 0; i--) {
  473. expect(current).toHaveProperty(`level${i}`);
  474. expect(current).toHaveProperty(`static${i}`, `value at depth ${i}`);
  475. current = current[`level${i}`];
  476. }
  477. expect(current).toBe('file content');
  478. });
  479. it('should handle functions and undefined values in objects gracefully', () => {
  480. const testFunction = () => 'test';
  481. const config = {
  482. func: testFunction,
  483. undef: undefined,
  484. normal: 'value',
  485. nested: {
  486. func2: testFunction,
  487. undef2: undefined,
  488. },
  489. };
  490. const result = maybeLoadConfigFromExternalFile(config);
  491. expect(result).toEqual(config);
  492. expect(result.func).toBe(testFunction);
  493. expect(result.nested.func2).toBe(testFunction);
  494. });
  495. });
  496. describe('getResolvedRelativePath', () => {
  497. const originalCwd = process.cwd();
  498. beforeEach(() => {
  499. jest.spyOn(process, 'cwd').mockReturnValue('/mock/cwd');
  500. });
  501. afterEach(() => {
  502. jest.spyOn(process, 'cwd').mockReturnValue(originalCwd);
  503. });
  504. it('returns absolute path unchanged', () => {
  505. const absolutePath = path.resolve('/absolute/path/file.txt');
  506. expect(getResolvedRelativePath(absolutePath, false)).toBe(absolutePath);
  507. });
  508. it('uses process.cwd() when isCloudConfig is true', () => {
  509. expect(getResolvedRelativePath('relative/file.txt', true)).toBe(
  510. path.join('/mock/cwd', 'relative/file.txt'),
  511. );
  512. });
  513. });
  514. describe('safeResolve', () => {
  515. it('returns absolute path unchanged', () => {
  516. const absolutePath = path.resolve('/absolute/path/file.txt');
  517. expect(safeResolve('some/base/path', absolutePath)).toBe(absolutePath);
  518. });
  519. it('returns file URL unchanged', () => {
  520. const fileUrl = getFileUrl('absolute/path/file.txt');
  521. expect(safeResolve('some/base/path', fileUrl)).toBe(fileUrl);
  522. });
  523. it('resolves relative paths', () => {
  524. const expected = path.resolve('base/path', 'relative/file.txt');
  525. expect(safeResolve('base/path', 'relative/file.txt')).toBe(expected);
  526. });
  527. it('handles multiple path segments', () => {
  528. const absolutePath = path.resolve('/absolute/path/file.txt');
  529. expect(safeResolve('base', 'path', absolutePath)).toBe(absolutePath);
  530. const expected = path.resolve('base', 'path', 'relative/file.txt');
  531. expect(safeResolve('base', 'path', 'relative/file.txt')).toBe(expected);
  532. });
  533. it('handles empty input', () => {
  534. expect(safeResolve()).toBe(path.resolve());
  535. expect(safeResolve('')).toBe(path.resolve(''));
  536. });
  537. });
  538. describe('safeJoin', () => {
  539. it('returns absolute path unchanged', () => {
  540. const absolutePath = path.resolve('/absolute/path/file.txt');
  541. expect(safeJoin('some/base/path', absolutePath)).toBe(absolutePath);
  542. });
  543. it('returns file URL unchanged', () => {
  544. const fileUrl = getFileUrl('absolute/path/file.txt');
  545. expect(safeJoin('some/base/path', fileUrl)).toBe(fileUrl);
  546. });
  547. it('joins relative paths', () => {
  548. const expected = path.join('base/path', 'relative/file.txt');
  549. expect(safeJoin('base/path', 'relative/file.txt')).toBe(expected);
  550. });
  551. it('handles multiple path segments', () => {
  552. const absolutePath = path.resolve('/absolute/path/file.txt');
  553. expect(safeJoin('base', 'path', absolutePath)).toBe(absolutePath);
  554. const expected = path.join('base', 'path', 'relative/file.txt');
  555. expect(safeJoin('base', 'path', 'relative/file.txt')).toBe(expected);
  556. });
  557. it('handles empty input', () => {
  558. expect(safeJoin()).toBe(path.join());
  559. expect(safeJoin('')).toBe(path.join(''));
  560. });
  561. });
  562. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...