-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathsmoke.ts
646 lines (547 loc) · 16.4 KB
/
smoke.ts
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
import path from 'path';
import { pathToFileURL } from 'url';
import { testSuite, expect } from 'manten';
import { createFixture } from 'fs-fixture';
import type { NodeApis } from '../utils/tsx';
const cjsContextCheck = 'typeof module !== \'undefined\'';
const tsCheck = '1 as number';
const declareReact = `
const React = {
createElement: (...args) => Array.from(args),
};
`;
const jsxCheck = '<><div>JSX</div></>';
const preserveName = `
assert(
(function functionName() {}).name === 'functionName',
'Name should be preserved'
);
`;
const wasmPath = path.resolve('tests/fixtures/test.wasm');
const wasmPathUrl = pathToFileURL(wasmPath).toString();
const syntaxLowering = `
// es2016 - Exponentiation operator
10 ** 4;
// es2017 - Async functions
(async () => {});
// es2018 - Spread properties
({...Object});
// es2018 - Rest properties
const {...x} = Object;
// es2019 - Optional catch binding
try {} catch {}
// es2020 - Optional chaining
Object?.keys;
// es2020 - Nullish coalescing
Object ?? true
// es2020 - import.meta
// import.meta
// es2021 - Logical assignment operators
// let a = false; a ??= true; a ||= true; a &&= true;
// es2022 - Class instance fields
(class { x });
// es2022 - Static class fields
(class { static x });
// es2022 - Private instance methods
(class { #x() {} });
// es2022 - Private instance fields
(class { #x });
// es2022 - Private static methods
(class { static #x() {} });
// es2022 - Private static fields
(class { static #x });
// es2022 - Class static blocks
(class { static {} });
export const named = 2;
export default 1;
`;
const sourcemap = {
test: 'const { stack } = new Error(); assert(stack.includes(\':SOURCEMAP_LINE\'), \'Expected SOURCEMAP_LINE in stack:\' + stack)',
tag: (
strings: TemplateStringsArray,
...values: string[]
) => {
const finalString = String.raw({ raw: strings }, ...values);
const lineNumber = finalString.split('\n').findIndex(line => line.includes('SOURCEMAP_LINE')) + 1;
return finalString.replaceAll('SOURCEMAP_LINE', lineNumber.toString());
},
};
const files = {
'js/index.js': `
import assert from 'assert';
${syntaxLowering}
${preserveName}
export const cjsContext = ${cjsContextCheck};
`,
'json/index.json': JSON.stringify({ loaded: 'json' }),
'cjs/index.cjs': sourcemap.tag`
const assert = require('node:assert');
assert(${cjsContextCheck}, 'Should have CJS context');
${preserveName}
${sourcemap.test}
exports.named = 'named';
`,
'mjs/index.mjs': `
export const mjsHasCjsContext = ${cjsContextCheck};
`,
'ts/index.ts': sourcemap.tag`
import assert from 'assert';
import type {Type} from 'resolved-by-tsc'
interface Foo {}
type Foo = number
declare module 'foo' {}
enum BasicEnum {
Left,
Right,
}
enum NamedEnum {
SomeEnum = 'some-value',
}
export const a = BasicEnum.Left;
export const b = NamedEnum.SomeEnum;
export default function foo(): string {
return 'foo'
}
// For "ts as tsx" test
const bar = <T>(value: T) => fn<T>();
${preserveName}
${sourcemap.test}
export const cjsContext = ${cjsContextCheck};
${tsCheck};
`,
// TODO: test resolution priority for files 'index.tsx` & 'index.tsx.ts` via 'index.tsx'
'jsx/index.jsx': sourcemap.tag`
import assert from 'assert';
export const cjsContext = ${cjsContextCheck};
${declareReact}
export const jsx = ${jsxCheck};
${preserveName}
${sourcemap.test}
`,
'tsx/index.tsx': sourcemap.tag`
import assert from 'assert';
export const cjsContext = ${cjsContextCheck};
${tsCheck};
${declareReact}
export const jsx = ${jsxCheck};
${preserveName}
${sourcemap.test}
`,
'mts/index.mts': sourcemap.tag`
import assert from 'assert';
export const mjsHasCjsContext = ${cjsContextCheck};
${tsCheck};
${preserveName}
${sourcemap.test}
`,
'cts/index.cts': sourcemap.tag`
const assert = require('assert');
assert(${cjsContextCheck}, 'Should have CJS context');
${tsCheck};
${preserveName}
${sourcemap.test}
`,
'expect-errors.js': `
export const expectErrors = async (...assertions) => {
let errors = await Promise.all(
assertions.map(async ([fn, expectedError]) => {
let thrown;
try {
await fn();
} catch (error) {
thrown = error;
}
if (!thrown) {
return new Error('No error thrown');
} else if (!thrown.message.includes(expectedError)) {
return new Error(\`Message \${JSON.stringify(expectedError)} not found in \${JSON.stringify(thrown.message)}\`);
}
}),
);
errors = errors.filter(Boolean);
if (errors.length > 0) {
console.error(errors);
process.exitCode = 1;
}
};
`,
'file.txt': 'hello',
node_modules: {
'pkg-commonjs': {
'package.json': JSON.stringify({
type: 'commonjs',
}),
'index.js': syntaxLowering,
},
'pkg-module': {
'package.json': JSON.stringify({
type: 'module',
exports: './index.js',
}),
'index.js': syntaxLowering,
},
},
tsconfig: {
'file.ts': '',
'jsx.jsx': `
// tsconfig not applied to jsx because allowJs is not set
import { expectErrors } from '../expect-errors';
expectErrors(
[() => ${jsxCheck}, 'React is not defined'],
// These should throw unless allowJs is set
// [() => import('prefix/file'), "Cannot find package 'prefix'"],
// [() => import('paths-exact-match'), "Cannot find package 'paths-exact-match'"],
// [() => import('file'), "Cannot find package 'file'"],
);
`,
'node_modules/tsconfig-should-not-apply': {
'package.json': JSON.stringify({
exports: {
import: './index.mjs',
default: './index.cjs',
},
}),
'index.mjs': `
import { expectErrors } from '../../../expect-errors';
expectErrors(
[() => import('prefix/file'), "Cannot find package 'prefix'"],
[() => import('paths-exact-match'), "Cannot find package 'paths-exact-match'"],
[() => import('file'), "Cannot find package 'file'"],
);
`,
'index.cjs': `
const { expectErrors } = require('../../../expect-errors');
expectErrors(
[() => require('prefix/file'), "Cannot find module"],
[() => require('paths-exact-match'), "Cannot find module"],
[() => require('file'), "Cannot find module"],
);
`,
},
'index.tsx': `
${jsxCheck};
import './jsx';
// Resolves relative to baseUrl
import 'file';
// Resolves paths - exact match
import 'paths-exact-match';
// Resolves paths - prefix match
import 'prefix/file';
// Resolves paths - suffix match
import 'file/suffix';
// tsconfig should not apply to dependency
import "tsconfig-should-not-apply";
`,
'tsconfig.json': JSON.stringify({
compilerOptions: {
jsxFactory: 'Array',
jsxFragmentFactory: 'null',
baseUrl: '.',
paths: {
'paths-exact-match': ['file'],
'prefix/*': ['*'],
'*/suffix': ['*'],
},
},
}),
'tsconfig-allowJs.json': JSON.stringify({
extends: './tsconfig.json',
compilerOptions: {
allowJs: true,
},
}),
},
};
const packageTypes = [
'module',
'commonjs',
] as const;
export default testSuite(async ({ describe }, { tsx }: NodeApis) => {
describe('Smoke', ({ describe }) => {
for (const packageType of packageTypes) {
const isCommonJs = packageType === 'commonjs';
describe(packageType, ({ test, describe }) => {
test('from .js', async ({ onTestFinish, onTestFail }) => {
const fixture = await createFixture({
...files,
'package.json': JSON.stringify({ type: packageType }),
'import-from-js.js': `
import assert from 'assert';
import { expectErrors } from './expect-errors';
// node: prefix
import 'node:fs';
import * as pkgCommonjs from 'pkg-commonjs';
import * as pkgModule from 'pkg-module';
// .js
import * as js from './js/index.js';
import './js/index.js?query=123';
import './js/index';
import './js/';
// No double .default.default in Dynamic Import
import('./js/index.js').then(m => {
if (typeof m.default === 'object') {
assert(
!('default' in m.default),
'Should not have double .default.default in Dynamic Import',
);
}
});
// .json
import * as json from './json/index.json';
import './json/index';
import './json/';
// .cjs
import * as cjs from './cjs/index.cjs';
expectErrors(
[() => import('./cjs/index'), 'Cannot find module'],
[() => import('./cjs/'), 'Cannot find module'],
${
isCommonJs
? `
[() => require('./cjs/index'), 'Cannot find module'],
[() => require('./cjs/'), 'Cannot find module'],
`
: ''
}
);
// .mjs
import * as mjs from './mjs/index.mjs';
expectErrors(
[() => import('./mjs/index'), 'Cannot find module'],
[() => import('./mjs/'), 'Cannot find module'],
${
isCommonJs
? `
[() => require('./mjs/index'), 'Cannot find module'],
[() => require('./mjs/'), 'Cannot find module'],
`
: ''
}
);
// Is TS loadable here?
// Import jsx?
// Unsupported files
expectErrors(
[() => import('./file.txt'), 'Unknown file extension'],
[() => import(${JSON.stringify(wasmPathUrl)}), 'Unknown file extension'],
${
isCommonJs
? `
[() => require('./file.txt'), 'hello is not defined'],
[() => require(${JSON.stringify(wasmPath)}), 'Invalid or unexpected token'],
`
: ''
}
);
console.log(JSON.stringify({
js,
json,
cjs,
mjs,
pkgCommonjs,
pkgModule,
}));
// Could .js import TS files?
`,
});
onTestFinish(async () => await fixture.rm());
const p = await tsx(['import-from-js.js'], fixture.path);
onTestFail((error) => {
console.error(error);
console.log(p);
});
expect(p.failed).toBe(false);
expect(p.stdout).toMatch(`"js":{"cjsContext":${isCommonJs},"default":1,"named":2}`);
expect(p.stdout).toMatch('"json":{"default":{"loaded":"json"},"loaded":"json"}');
expect(p.stdout).toMatch('"cjs":{"default":{"named":"named"},"named":"named"}');
expect(p.stdout).toMatch('"pkgModule":{"default":1,"named":2}');
if (isCommonJs) {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":1,"named":2}');
} else {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":{"default":1,"named":2}}');
}
// By "require()"ing an ESM file, it forces it to be compiled in a CJS context
expect(p.stdout).toMatch(`"mjs":{"mjsHasCjsContext":${isCommonJs}}`);
expect(p.stderr).toBe('');
});
describe('from .ts', async ({ test, onFinish }) => {
const fixture = await createFixture({
...files,
'package.json': JSON.stringify({ type: packageType }),
'import-from-ts.ts': `
import assert from 'assert';
import { expectErrors } from './expect-errors';
// node: prefix
import 'node:fs';
// Dependencies
import * as pkgCommonjs from 'pkg-commonjs';
import * as pkgModule from 'pkg-module';
// TODO: Test resolving TS files in dependencies (e.g. implicit extensions & export maps)
// .js
import * as js from './js/index.js';
import './js/index.js?query=123';
import './js/index';
import './js/';
// No double .default.default in Dynamic Import
import('./js/index.js').then(m => {
if (typeof m.default === 'object') {
assert(
!('default' in m.default),
'Should not have double .default.default in Dynamic Import',
);
}
});
// .json
import * as json from './json/index.json';
import './json/index';
import './json/';
// .cjs
import * as cjs from './cjs/index.cjs';
expectErrors(
[() => import('./cjs/index'), 'Cannot find module'],
[() => import('./cjs/'), 'Cannot find module'],
${
isCommonJs
? `
[() => require('./cjs/index'), 'Cannot find module'],
[() => require('./cjs/'), 'Cannot find module'],
`
: ''
}
);
// .mjs
import * as mjs from './mjs/index.mjs';
expectErrors(
[() => import('./mjs/index'), 'Cannot find module'],
[() => import('./mjs/'), 'Cannot find module'],
${
isCommonJs
? `
[() => require('./mjs/index'), 'Cannot find module'],
[() => require('./mjs/'), 'Cannot find module'],
`
: ''
}
);
// .ts
import './ts/index.ts';
import './ts/index.js';
import './ts/index.jsx';
import './ts/index';
import './ts/';
// .jsx
import * as jsx from './jsx/index.jsx';
import './jsx/index.js';
import './jsx/index';
import './jsx/';
// .tsx
import './tsx/index.tsx';
import './tsx/index.js';
import './tsx/index.jsx';
import './tsx/index';
import './tsx/';
// .cts
import './cts/index.cjs';
expectErrors(
// TODO:
// [() => import('./cts/index.cts'), 'Cannot find module'],
[() => import('./cts/index'), 'Cannot find module'],
[() => import('./cts/'), 'Cannot find module'],
${
isCommonJs
? `
[() => require('./cts/index'), 'Cannot find module'],
[() => require('./cts/'), 'Cannot find module'],
`
: ''
}
);
// Loading via Node arg should not work via .cjs but with .cts
// .mts
import './mts/index.mjs';
expectErrors(
// TODO:
// [() => import('./mts/index.mts'), 'Cannot find module'],
[() => import('./mts/index'), 'Cannot find module'],
[() => import('./mts/'), 'Cannot find module'],
${
isCommonJs
? `
[() => require('./mts/index'), 'Cannot find module'],
[() => require('./mts/'), 'Cannot find module'],
`
: ''
}
);
// Loading via Node arg should not work via .mjs but with .mts
// Unsupported files
expectErrors(
[() => import('./file.txt'), 'Unknown file extension'],
[() => import(${JSON.stringify(wasmPathUrl)}), 'Unknown file extension'],
${
isCommonJs
? `
[() => require('./file.txt'), 'hello is not defined'],
[() => require(${JSON.stringify(wasmPath)}), 'Invalid or unexpected token'],
`
: ''
}
);
console.log(JSON.stringify({
js,
json,
jsx,
cjs,
mjs,
pkgCommonjs,
pkgModule,
}));
`,
});
onFinish(async () => await fixture.rm());
test('import all', async ({ onTestFail }) => {
const p = await tsx(['import-from-ts.ts'], fixture.path);
onTestFail((error) => {
console.error(error);
console.log(p);
});
expect(p.failed).toBe(false);
expect(p.stdout).toMatch(`"js":{"cjsContext":${isCommonJs},"default":1,"named":2}`);
expect(p.stdout).toMatch('"json":{"default":{"loaded":"json"},"loaded":"json"}');
expect(p.stdout).toMatch('"cjs":{"default":{"named":"named"},"named":"named"}');
expect(p.stdout).toMatch(`"jsx":{"cjsContext":${isCommonJs},"jsx":[null,null,["div",null,"JSX"]]}`);
expect(p.stdout).toMatch('"pkgModule":{"default":1,"named":2}');
if (isCommonJs) {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":1,"named":2}');
} else {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":{"default":1,"named":2}}');
}
// By "require()"ing an ESM file, it forces it to be compiled in a CJS context
expect(p.stdout).toMatch(`"mjs":{"mjsHasCjsContext":${isCommonJs}}`);
expect(p.stderr).toBe('');
});
test('tsconfig', async ({ onTestFail }) => {
const pTsconfig = await tsx(['index.tsx'], path.join(fixture.path, 'tsconfig'));
onTestFail((error) => {
console.error(error);
console.log(pTsconfig);
});
expect(pTsconfig.failed).toBe(false);
expect(pTsconfig.stderr).toBe('');
expect(pTsconfig.stdout).toBe('');
});
test('custom tsconfig', async ({ onTestFail }) => {
const pTsconfigAllowJs = await tsx(['--tsconfig', 'tsconfig-allowJs.json', 'jsx.jsx'], path.join(fixture.path, 'tsconfig'));
onTestFail((error) => {
console.error(error);
console.log(pTsconfigAllowJs);
});
expect(pTsconfigAllowJs.failed).toBe(true);
expect(pTsconfigAllowJs.stderr).toMatch('Error: No error thrown');
expect(pTsconfigAllowJs.stdout).toBe('');
});
});
});
}
});
});