-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
executable file
·963 lines (907 loc) · 32.9 KB
/
index.js
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
import {
commonInternalPaths,
invalidJsxExtensions,
knownBrowserishConditions
} from './constants.js'
import {
exportsGlob,
getCodeFormat,
getFilePathFormat,
getCodeFormatExtension,
isExplicitExtension,
createPromiseQueue,
getPublishedField,
objectHasKeyNested,
isFilePathLintable,
isFileContentLintable,
getAdjacentDtsPath,
resolveExports,
isDtsFile,
getDtsFilePathFormat,
getDtsCodeFormatExtension,
getPkgPathValue,
replaceLast
} from './utils.js'
/**
* Includes internal _include that used to filter paths that is packed.
* Mainly for node.js local usage only. So that we lint files that are packed only.
* Currently only used if pkg has no `exports`
* @typedef {Required<import('../index.d.ts').Options> & {
* _packedFiles?: string[]
* }} Options
*/
/**
* @param {Options} options
* @returns {Promise<import('../index.d.ts').Result>}
*/
export async function publint({ pkgDir, vfs, level, strict, _packedFiles }) {
/** @type {import('../index.d.ts').Message[]} */
const messages = []
/**
* A promise queue is created to run all linting tasks in parallel
*/
const promiseQueue = createPromiseQueue()
const rootPkgPath = vfs.pathJoin(pkgDir, 'package.json')
const rootPkgContent = await readFile(rootPkgPath, [])
if (rootPkgContent === false) return { messages }
const rootPkg = JSON.parse(rootPkgContent)
const [main, mainPkgPath] = getPublishedField(rootPkg, 'main')
const [module, modulePkgPath] = getPublishedField(rootPkg, 'module')
const [exports, exportsPkgPath] = getPublishedField(rootPkg, 'exports')
// Check if package published internal tests or config files
if (rootPkg.files == null) {
promiseQueue.push(async () => {
for (const p of commonInternalPaths) {
const internalPath = vfs.pathJoin(pkgDir, p)
if (
_packedFiles &&
_packedFiles.every((f) => !f.startsWith(internalPath))
) {
continue
}
if (await vfs.isPathExist(internalPath)) {
messages.push({
code: 'USE_FILES',
args: {},
path: ['name'],
type: 'suggestion'
})
break
}
}
})
}
// Check if "type" field is specified, help Node.js push towards an ESM default future:
// https://nodejs.org/en/blog/release/v20.10.0
if (rootPkg.type == null) {
messages.push({
code: 'USE_TYPE',
args: {},
path: ['name'],
type: 'suggestion'
})
}
// Relies on default node resolution
// https://nodejs.org/api/modules.html#all-together
// LOAD_INDEX(X)
if (main == null && module == null && exports == null) {
promiseQueue.push(async () => {
// check index.js only, others aren't our problem
const defaultPath = vfs.pathJoin(pkgDir, 'index.js')
if (await vfs.isPathExist(defaultPath)) {
const defaultContent = await readFile(defaultPath, [])
if (defaultContent === false) return
const actualFormat = getCodeFormat(defaultContent)
const expectFormat = await getFilePathFormat(defaultPath, vfs)
if (
actualFormat !== expectFormat &&
actualFormat !== 'unknown' &&
actualFormat !== 'mixed'
) {
messages.push({
code: 'IMPLICIT_INDEX_JS_INVALID_FORMAT',
args: {
actualFormat,
expectFormat
},
path: ['name'],
type: 'warning'
})
}
}
})
}
/**
* Rules for main:
* - It's mostly used for CJS
* - It can be used for ESM, but if you're doing so, might as well use exports
*/
if (main != null) {
promiseQueue.push(async () => {
if (!ensureTypeOfField(main, ['string'], mainPkgPath)) return
const mainPath = vfs.pathJoin(pkgDir, main)
const mainContent = await readFile(mainPath, mainPkgPath, [
'.js',
'/index.js'
])
if (mainContent === false) return
if (hasInvalidJsxExtension(main, mainPkgPath)) return
if (!isFilePathLintable(main)) return
const actualFormat = getCodeFormat(mainContent)
const expectFormat = await getFilePathFormat(mainPath, vfs)
if (
actualFormat !== expectFormat &&
actualFormat !== 'unknown' &&
actualFormat !== 'mixed'
) {
const actualExtension = vfs.getExtName(mainPath)
messages.push({
code: isExplicitExtension(actualExtension)
? 'FILE_INVALID_EXPLICIT_FORMAT'
: 'FILE_INVALID_FORMAT',
args: {
actualFormat,
expectFormat,
actualExtension,
expectExtension: getCodeFormatExtension(actualFormat)
},
path: mainPkgPath,
type: 'warning'
})
}
if (actualFormat === 'ESM' && exports == null) {
messages.push({
code: 'HAS_ESM_MAIN_BUT_NO_EXPORTS',
args: {},
path: mainPkgPath,
type: 'suggestion'
})
}
})
}
/**
* Rules for module:
* - Bundler-specific
* - Is not a way to support dual packages in NodeJS
* - Should be MJS always!!
*/
if (module != null) {
promiseQueue.push(async () => {
if (!ensureTypeOfField(module, ['string'], modulePkgPath)) return
const modulePath = vfs.pathJoin(pkgDir, module)
const moduleContent = await readFile(modulePath, modulePkgPath, [
'.js',
'/index.js'
])
if (moduleContent === false) return
if (hasInvalidJsxExtension(module, modulePkgPath)) return
if (!isFilePathLintable(module)) return
const actualFormat = getCodeFormat(moduleContent)
if (actualFormat === 'CJS') {
messages.push({
code: 'MODULE_SHOULD_BE_ESM',
args: {},
path: modulePkgPath,
type: 'error'
})
}
// TODO: Check valid content too?
if (!exports) {
messages.push({
code: 'HAS_MODULE_BUT_NO_EXPORTS',
args: {},
path: modulePkgPath,
type: 'suggestion'
})
}
})
}
// if main or module is exists, and exports exists, check if there's a root
// entrypoint in exports. it may be mistaken that exports can be used to define
// nested entrypoints only (missing the root entrypoint)
if ((main != null || module != null) && exports != null) {
let hasRootExports = true
if (typeof exports == 'object') {
const exportsKeys = Object.keys(exports)
// an exports object could contain conditions, or paths that maps to other objects.
// we can determine the type of the object by checking one of the keys ([0])
// if it's a path, which we can then proceed to check if it has the root path
if (exportsKeys[0]?.startsWith('.') && !exportsKeys.includes('.')) {
hasRootExports = false
}
}
if (!hasRootExports) {
const mainFields = []
if (main) mainFields.push('main')
if (module) mainFields.push('module')
messages.push({
code: 'EXPORTS_MISSING_ROOT_ENTRYPOINT',
args: { mainFields },
path: exportsPkgPath,
type: 'warning'
})
}
}
// check file existence for other known package fields
const knownFields = [
'types',
'typings',
'jsnext:main',
'jsnext',
'unpkg',
'jsdelivr'
]
// if has typesVersions field, it complicates `types`/`typings` field resolution a lot.
// for now skip it, but further improvements are tracked at
// https://github.com/bluwy/publint/issues/42
if (getPublishedField(rootPkg, 'typesVersions')[0]) {
knownFields.splice(0, 2)
}
for (const fieldName of knownFields) {
const [fieldValue, fieldPkgPath] = getPublishedField(rootPkg, fieldName)
if (
fieldValue != null &&
ensureTypeOfField(fieldValue, ['string'], fieldPkgPath)
) {
promiseQueue.push(async () => {
const fieldPath = vfs.pathJoin(pkgDir, fieldValue)
const hasContent =
(await readFile(fieldPath, fieldPkgPath, ['.js', '/index.js'])) !==
false
if (
hasContent &&
(fieldName === 'jsnext:main' || fieldName === 'jsnext')
) {
messages.push({
code: 'DEPRECATED_FIELD_JSNEXT',
args: {},
path: fieldPkgPath,
// `module` should be used instead, but if it's already specified, downgrade as a suggestion
// as the jsnext fields are likely for compat only.
type: module ? 'suggestion' : 'warning'
})
}
})
}
}
// check file existence for browser field
const [browser, browserPkgPath] = getPublishedField(rootPkg, 'browser')
if (browser) {
crawlBrowser(browser, browserPkgPath)
// if the package has both the `browser` and `exports` fields, recommend to use
// the browser condition instead
if (exports) {
if (typeof browser === 'string') {
messages.push({
code: 'USE_EXPORTS_BROWSER',
args: {},
path: browserPkgPath,
type: 'suggestion'
})
} else {
messages.push({
code: 'USE_EXPORTS_OR_IMPORTS_BROWSER',
args: {},
path: browserPkgPath,
type: 'suggestion'
})
}
}
}
if (exports) {
// recursively check exports
crawlExports(exports, exportsPkgPath)
// make sure types are exported for moduleResolution bundler
doCheckTypesExported()
} else {
// all files can be accessed. verify them all
promiseQueue.push(async () => {
const files = await exportsGlob(
vfs.pathJoin(pkgDir, './*'),
vfs,
_packedFiles
)
const pq = createPromiseQueue()
for (const filePath of files) {
if (
hasInvalidJsxExtension(
filePath,
['name'],
'/' + vfs.pathRelative(pkgDir, filePath)
)
)
continue
if (!isFilePathLintable(filePath)) continue
pq.push(async () => {
const fileContent = await readFile(filePath, [])
if (fileContent === false) return
if (!isFileContentLintable(fileContent)) return
const actualFormat = getCodeFormat(fileContent)
const expectFormat = await getFilePathFormat(filePath, vfs)
if (
actualFormat !== expectFormat &&
actualFormat !== 'unknown' &&
actualFormat !== 'mixed'
) {
// special case where if the file path contains the keyword "browser" or
// "bundler", but it has problems. allow skipping the problem if it's ESM.
const isSafeEsm =
actualFormat === 'ESM' &&
(filePath.includes('browser') || filePath.includes('bundler'))
if (isSafeEsm) return
const actualExtension = vfs.getExtName(filePath)
const expectExtension = getCodeFormatExtension(actualFormat)
// test if the expected extension and file path already exist. if so, skip warning as
// this invalid format file is probably intentional for other use.
// NOTE: only relax this for globbed files, as they're implicitly exported.
const expectFilePath = replaceLast(
filePath,
actualExtension,
expectExtension
)
if (await vfs.isPathExist(expectFilePath)) return
messages.push({
code: isExplicitExtension(actualExtension)
? 'FILE_INVALID_EXPLICIT_FORMAT'
: 'FILE_INVALID_FORMAT',
args: {
actualFormat,
expectFormat,
actualExtension,
expectExtension,
actualFilePath: '/' + vfs.pathRelative(pkgDir, filePath)
},
path: ['name'],
type: 'warning'
})
}
})
}
await pq.wait()
})
}
await promiseQueue.wait()
if (strict) {
for (const message of messages) {
if (message.type === 'warning') {
message.type = 'error'
}
}
}
if (level === 'warning') {
return { messages: messages.filter((m) => m.type !== 'suggestion') }
} else if (level === 'error') {
return { messages: messages.filter((m) => m.type === 'error') }
}
return { messages }
/**
* @param {string} path file path to read
* @param {string[]} [pkgPath] current path that tries to read this file.
* pass `undefined` to prevent error reporting if the file is missing.
* @param {string[]} tryExtensions list of extensions to try before giving up
* @returns {Promise<string | false>}
*/
async function readFile(path, pkgPath = undefined, tryExtensions = []) {
try {
const content = await vfs.readFile(path)
if (pkgPath && _packedFiles && !_packedFiles.includes(path)) {
fileNotPublished(pkgPath)
}
return content
} catch {
for (let ext of tryExtensions) {
// remove duplicated slashes
if (ext[0] === '/' && path[path.length - 1] === '/') {
ext = ext.slice(1)
}
try {
const content = await vfs.readFile(path + ext)
if (pkgPath && _packedFiles && !_packedFiles.includes(path + ext)) {
fileNotPublished(pkgPath)
}
return content
} catch {}
}
if (pkgPath) {
messages.push({
code: 'FILE_DOES_NOT_EXIST',
args: {},
path: pkgPath,
type: 'error'
})
}
return false
}
}
/**
* @param {string[]} pkgPath
*/
function fileNotPublished(pkgPath) {
messages.push({
code: 'FILE_NOT_PUBLISHED',
args: {},
path: pkgPath,
type: 'error'
})
}
/**
* @param {string} filePath
* @param {string[]} currentPath
* @param {string} [globbedFilePath] only needed for globs
*/
function hasInvalidJsxExtension(filePath, currentPath, globbedFilePath) {
const matched = invalidJsxExtensions.find((ext) => filePath.endsWith(ext))
if (matched) {
messages.push({
code: 'FILE_INVALID_JSX_EXTENSION',
args: {
actualExtension: matched,
globbedFilePath
},
path: currentPath,
type: 'error'
})
return true
}
return false
}
/**
* @param {any} fieldValue
* @param {('string' | 'number' | 'boolean' | 'object')[]} expectTypes
* @param {string[]} pkgPath
*/
function ensureTypeOfField(fieldValue, expectTypes, pkgPath) {
// @ts-expect-error typeof doesn't need to match `expectedTypes` type but TS panics
if (!expectTypes.includes(typeof fieldValue)) {
messages.push({
code: 'FIELD_INVALID_VALUE_TYPE',
args: {
actualType: typeof fieldValue,
expectTypes
},
path: pkgPath,
type: 'error'
})
return false
}
return true
}
/**
* @param {string | Record<string, any>} fieldValue
* @param {string[]} currentPath
*/
function crawlBrowser(fieldValue, currentPath) {
if (typeof fieldValue === 'string') {
promiseQueue.push(async () => {
const browserPath = vfs.pathJoin(pkgDir, fieldValue)
await readFile(browserPath, currentPath, ['.js', '/index.js'])
})
} else if (typeof fieldValue === 'object') {
for (const key in fieldValue) {
crawlBrowser(fieldValue[key], currentPath.concat(key))
}
}
}
/**
* @param {string} exportsValue
*/
async function getExportsFiles(exportsValue) {
const exportsPath = vfs.pathJoin(pkgDir, exportsValue)
const isGlob = exportsValue.includes('*')
return isGlob
? await exportsGlob(exportsPath, vfs, _packedFiles)
: [exportsPath]
}
/**
* @param {any} exportsValue
* @param {string[]} currentPath
* @param {boolean} isAfterNodeCondition
*/
function crawlExports(
exportsValue,
currentPath,
isAfterNodeCondition = false
) {
if (typeof exportsValue === 'string') {
promiseQueue.push(async () => {
// warn deprecated subpath mapping
// https://nodejs.org/docs/latest-v16.x/api/packages.html#subpath-folder-mappings
if (exportsValue.endsWith('/')) {
const expectPath = currentPath.map((part) => {
return part.endsWith('/') ? part + '*' : part
})
const expectPathAlreadyExist = !!getPkgPathValue(rootPkg, expectPath)
messages.push({
code: 'EXPORTS_GLOB_NO_DEPRECATED_SUBPATH_MAPPING',
args: {
expectPath,
expectValue: exportsValue + '*'
},
path: currentPath,
// if a trailing glob is also specified, that means this key is for backwards compat only.
// lower severity to suggestion instead.
type: expectPathAlreadyExist ? 'suggestion' : 'warning'
})
// help fix glob so we can further analyze other issues
exportsValue += '*'
}
// error incorrect exports value
if (!exportsValue.startsWith('./')) {
messages.push({
code: 'EXPORTS_VALUE_INVALID',
args: {
suggestValue: './' + exportsValue.replace(/^[\/]+/, '')
},
path: currentPath,
type: 'error'
})
}
const isGlob = exportsValue.includes('*')
const exportsFiles = await getExportsFiles(exportsValue)
if (isGlob && !exportsFiles.length) {
messages.push({
code: 'EXPORTS_GLOB_NO_MATCHED_FILES',
args: {},
path: currentPath,
type: 'warning'
})
return
}
// types. check file existence only
if (currentPath.includes('types')) {
const pq = createPromiseQueue()
for (const filePath of exportsFiles) {
pq.push(async () => await readFile(filePath, currentPath))
}
await pq.wait()
return
}
// if the exports value matches a key in `pkg.browser` (meaning it'll be remapped
// if in a browser-ish environment), check if this is a browser-ish environment/condition.
// if so, warn about this conflict as it's often unexpected behaviour.
if (typeof browser === 'object' && exportsValue in browser) {
const browserishCondition = knownBrowserishConditions.find((c) =>
currentPath.includes(c)
)
if (browserishCondition) {
messages.push({
code: 'EXPORTS_VALUE_CONFLICTS_WITH_BROWSER',
args: {
browserPath: browserPkgPath.concat(exportsValue),
browserishCondition
},
path: currentPath,
type: 'warning'
})
}
}
const pq = createPromiseQueue()
// TODO: group glob warnings
for (const filePath of exportsFiles) {
if (
hasInvalidJsxExtension(
filePath,
currentPath,
isGlob ? './' + vfs.pathRelative(pkgDir, filePath) : undefined
)
)
return
// TODO: maybe check .ts in the future
if (!isFilePathLintable(filePath)) continue
pq.push(async () => {
// could fail if in !isGlob
const fileContent = await readFile(filePath, currentPath)
if (fileContent === false) return
if (!isFileContentLintable(fileContent)) return
// the `module` condition is only used by bundlers and must be ESM
if (currentPath.includes('module')) {
const actualFormat = getCodeFormat(fileContent)
if (actualFormat === 'CJS') {
messages.push({
code: 'EXPORTS_MODULE_SHOULD_BE_ESM',
args: {},
path: currentPath,
type: 'error'
})
}
return
}
// file format checks isn't required for `browser` condition or exports
// after the node condtion, as nodejs doesn't use it, only bundlers do,
// which doesn't care of the format
if (isAfterNodeCondition || currentPath.includes('browser')) return
const actualFormat = getCodeFormat(fileContent)
const expectFormat = await getFilePathFormat(filePath, vfs)
if (
actualFormat !== expectFormat &&
actualFormat !== 'unknown' &&
actualFormat !== 'mixed'
) {
// special case where if the file path contains the keyword "browser" or
// "bundler", but it has problems. allow skipping the problem if it's ESM.
const isSafeEsm =
actualFormat === 'ESM' &&
(filePath.includes('browser') || filePath.includes('bundler'))
if (isSafeEsm) return
const actualExtension = vfs.getExtName(filePath)
const expectExtension = getCodeFormatExtension(actualFormat)
// test if the expected extension and file path already exist. if so, skip warning as
// this invalid format file is probably intentional for other use.
// NOTE: only relax this for globbed files, as they're implicitly exported.
if (isGlob) {
const expectFilePath = replaceLast(
filePath,
actualExtension,
expectExtension
)
if (await vfs.isPathExist(expectFilePath)) return
}
messages.push({
code: isExplicitExtension(actualExtension)
? 'FILE_INVALID_EXPLICIT_FORMAT'
: 'FILE_INVALID_FORMAT',
args: {
actualFormat,
expectFormat,
actualExtension,
expectExtension,
actualFilePath: isGlob
? './' + vfs.pathRelative(pkgDir, filePath)
: exportsValue
},
path: currentPath,
type: 'warning'
})
}
})
}
await pq.wait()
})
}
// `exports` could be null to disallow exports of globs from another key
else if (exportsValue) {
const exportsKeys = Object.keys(exportsValue)
// the types export should be the first condition
if ('types' in exportsValue && exportsKeys[0] !== 'types') {
// check preceding conditions before the `types` condition, if there are nested
// conditions, check if they also have the `types` condition. If they do, there's
// a good chance those take precendence over this non-first `types` condition, which
// is fine and is usually used as fallback instead.
const precedingKeys = exportsKeys.slice(0, exportsKeys.indexOf('types'))
let isPrecededByNestedTypesCondition = false
for (const key of precedingKeys) {
if (
typeof exportsValue[key] === 'object' &&
objectHasKeyNested(exportsValue[key], 'types')
) {
isPrecededByNestedTypesCondition = true
break
}
}
if (!isPrecededByNestedTypesCondition) {
messages.push({
code: 'EXPORTS_TYPES_SHOULD_BE_FIRST',
args: {},
path: currentPath.concat('types'),
type: 'error'
})
}
}
// if there is a 'require' and a 'module' condition at the same level,
// then 'module' should always precede 'require'
if (
'module' in exportsValue &&
'require' in exportsValue &&
exportsKeys.indexOf('module') > exportsKeys.indexOf('require')
) {
messages.push({
code: 'EXPORTS_MODULE_SHOULD_PRECEDE_REQUIRE',
args: {},
path: currentPath.concat('module'),
type: 'error'
})
}
// the default export should be the last condition
if (
'default' in exportsValue &&
exportsKeys[exportsKeys.length - 1] !== 'default'
) {
messages.push({
code: 'EXPORTS_DEFAULT_SHOULD_BE_LAST',
args: {},
path: currentPath.concat('default'),
type: 'error'
})
}
// keep special state of whether the next `crawlExports` iterations are after a node condition.
// if there are, we can skip code format check as nodejs doesn't touch them, except bundlers
// which are fine with any format.
let isKeyAfterNodeCondition = isAfterNodeCondition
for (const key of exportsKeys) {
crawlExports(
exportsValue[key],
currentPath.concat(key),
isKeyAfterNodeCondition
)
if (key === 'node') {
isKeyAfterNodeCondition = true
}
}
}
}
function doCheckTypesExported() {
if (typeof exports === 'string') {
checkTypesExported()
} else if (typeof exports === 'object') {
const exportsKeys = Object.keys(exports)
if (exportsKeys.length === 0) return
// check if the `exports` directly map to condition keys (doesn't start with '.').
// if so, we work on it directly.
if (!exportsKeys[0].startsWith('.')) {
checkTypesExported()
}
// else this `exports` may have multiple export entrypoints, check for '.'
// TODO: check for other entrypoints, move logic into `crawlExports`
else if ('.' in exports) {
checkTypesExported('.')
}
}
}
/**
* @param {string | undefined} exportsRootKey
*/
function checkTypesExported(exportsRootKey = undefined) {
promiseQueue.push(async () => {
const typesFilePath = await findTypesFilePath(exportsRootKey)
const exportsRootValue = exportsRootKey
? exports[exportsRootKey]
: exports
// detect if this package intend to ship types
if (typesFilePath) {
const exportsPath = exportsRootKey
? exportsPkgPath.concat(exportsRootKey)
: exportsPkgPath
// keyed strings for seen resolved paths, so we don't trigger duplicate messages for the same thing
const seenResolvedKeys = new Set()
// NOTE: got lazy. here we check for the import/require result in different environments
// to make sure we cover possible cases. however, a better way it to resolve the exports
// and scan also the possible environment conditions, and return an array instead.
for (const env of [undefined, 'node', 'browser', 'worker']) {
for (const format of ['import', 'require']) {
const result = resolveExports(
exportsRootValue,
// @ts-expect-error till this day, ts still doesn't understand `filter(Boolean)`
['types', format, env].filter(Boolean),
exportsPath
)
if (!result) continue
// check if we've seen this resolve before. we also key by format as we want to distinguish
// incorrect exports, but only when the "exports -> path" contains that format, otherwise
// it's intentional fallback behaviour by libraries and we don't want to trigger a false alarm.
// e.g. libraries that only `"exports": "./index.mjs"` means it's ESM only, so we don't key
// the format, so the next run with `"require"` condition is skipped.
// different env can share the same key as code can usually be used for multiple environments.
const seenKey =
result.path.join('.') + (result.dualPublish ? format : '')
if (seenResolvedKeys.has(seenKey)) continue
seenResolvedKeys.add(seenKey)
const resolvedPath = vfs.pathJoin(pkgDir, result.value)
// if path doesn't exist, let the missing file error message take over instead
if (!(await vfs.isPathExist(resolvedPath))) continue
if (isDtsFile(result.value)) {
// if we have resolve to a dts file, it might not be ours because typescript requires
// `.d.mts` and `.d.cts` for esm and cjs (`.js` and nearest type: module behaviour applies).
// check if we're hitting this case :(
const dtsActualFormat = await getDtsFilePathFormat(
resolvedPath,
vfs
)
/** @type {'ESM' | 'CJS' | undefined} */
let dtsExpectFormat = undefined
// get the intended format from the conditions without types, e.g. if the adjacent file
// is a CJS file, despite resolving with the "import" condition, make sure the dts format
// is expected to be CJS too.
// only run this if not dual publish since we know dual publish should have both ESM and CJS
// versions of the dts file, and we don't need to be lenient.
// NOTE: could there be setups with CJS code and ESM types? seems a bit weird.
if (!result.dualPublish) {
const nonTypesResult = resolveExports(
exportsRootValue,
// @ts-expect-error till this day, ts still doesn't understand `filter(Boolean)`
[format, env].filter(Boolean),
exportsPath
)
if (nonTypesResult?.value) {
const nonTypesResolvedPath = vfs.pathJoin(
pkgDir,
nonTypesResult.value
)
if (await vfs.isPathExist(nonTypesResolvedPath)) {
dtsExpectFormat = await getFilePathFormat(
nonTypesResolvedPath,
vfs
)
}
}
}
// fallback if we can't determine the non types format, we base on the condition instead.
// NOTE: this favours "import" condition over "require" when the library doesn't dual publish
// because we run "import" first in the for loop.
if (dtsExpectFormat == null) {
dtsExpectFormat = format === 'import' ? 'ESM' : 'CJS'
}
if (dtsActualFormat !== dtsExpectFormat) {
messages.push({
code: 'EXPORT_TYPES_INVALID_FORMAT',
args: {
condition: format,
actualFormat: dtsActualFormat,
expectFormat: dtsExpectFormat,
actualExtension: vfs.getExtName(result.value),
expectExtension: getDtsCodeFormatExtension(dtsExpectFormat)
},
path: result.path,
type: 'warning'
})
}
} else {
// adjacent dts file here is always in the correct format
const hasAdjacentDtsFile = await vfs.isPathExist(
vfs.pathJoin(pkgDir, getAdjacentDtsPath(result.value))
)
// if there's no adjacent dts file, it's likely they don't support moduleResolution: bundler.
// try to provide a warning.
if (!hasAdjacentDtsFile) {
// before we recommend using `typesFilePath` for this export condition, we need to make sure
// it's of a matching format
const dtsActualFormat = await getDtsFilePathFormat(
vfs.pathJoin(pkgDir, typesFilePath),
vfs
)
const dtsExpectFormat = format === 'import' ? 'ESM' : 'CJS'
// if it's a matching format, we can recommend using the types file for this exports condition too.
// if not, we need to tell them to create a `.d.[mc]ts` file and not use `typesFilePath`.
// this is signalled in `matchingFormat`, where the message handler should check for it.
const isMatchingFormat = dtsActualFormat === dtsExpectFormat
messages.push({
code: 'TYPES_NOT_EXPORTED',
args: {
typesFilePath,
actualExtension: isMatchingFormat
? undefined
: vfs.getExtName(typesFilePath),
expectExtension: isMatchingFormat
? undefined
: getDtsCodeFormatExtension(dtsExpectFormat)
},
path: result.path,
type: 'warning'
})
}
}
}
}
}
})
}
/**
* @param {string | undefined} exportsKey
*/
async function findTypesFilePath(exportsKey) {
let typesFilePath
if (exportsKey == null || exportsKey === '.') {
const [types] = getPublishedField(rootPkg, 'types')
const [typings] = getPublishedField(rootPkg, 'typings')
if (types) {
typesFilePath = types
} else if (typings) {
typesFilePath = typings
} else if (await readFile(vfs.pathJoin(pkgDir, './index.d.ts'))) {
typesFilePath = './index.d.ts'
}
} else {
// TODO: handle nested exports key
}
return typesFilePath
}
}