forked from aws/aws-cdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rules.ts
1878 lines (1595 loc) · 60.7 KB
/
rules.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
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
import * as fs from 'fs';
import * as path from 'path';
import { Bundle } from '@aws-cdk/node-bundle';
import * as caseUtils from 'case';
import * as glob from 'glob';
import * as semver from 'semver';
import { LICENSE, NOTICE } from './licensing';
import { PackageJson, ValidationRule } from './packagejson';
import { cfnOnlyReadmeContents } from './readme-contents';
import {
deepGet, deepSet,
expectDevDependency, expectJSON,
fileShouldBe, fileShouldBeginWith, fileShouldContain,
fileShouldNotContain,
findInnerPackages,
monoRepoRoot,
} from './util';
const AWS_SERVICE_NAMES = require('./aws-service-official-names.json'); // eslint-disable-line @typescript-eslint/no-require-imports
const PKGLINT_VERSION = require('../package.json').version; // eslint-disable-line @typescript-eslint/no-require-imports
/**
* Verify that the package name matches the directory name
*/
export class PackageNameMatchesDirectoryName extends ValidationRule {
public readonly name = 'naming/package-matches-directory';
public validate(pkg: PackageJson): void {
const parts = pkg.packageRoot.split(path.sep);
const expectedName = parts[parts.length - 2].startsWith('@')
? parts.slice(parts.length - 2).join('/')
: parts[parts.length - 1];
expectJSON(this.name, pkg, 'name', expectedName);
}
}
/**
* Verify that all packages have a description
*/
export class DescriptionIsRequired extends ValidationRule {
public readonly name = 'package-info/require-description';
public validate(pkg: PackageJson): void {
if (!pkg.json.description) {
pkg.report({ ruleName: this.name, message: 'Description is required' });
}
}
}
/**
* Verify that all packages have a publishConfig with a publish tag set.
*/
export class PublishConfigTagIsRequired extends ValidationRule {
public readonly name = 'package-info/publish-config-tag';
public validate(pkg: PackageJson): void {
if (pkg.json.private) { return; }
const defaultPublishTag = 'latest';
if (pkg.json.publishConfig?.tag !== defaultPublishTag) {
pkg.report({
ruleName: this.name,
message: `publishConfig.tag must be ${defaultPublishTag}`,
fix: (() => {
const publishConfig = pkg.json.publishConfig ?? {};
publishConfig.tag = defaultPublishTag;
pkg.json.publishConfig = publishConfig;
}),
});
}
}
}
/**
* Verify cdk.out directory is included in npmignore since we should not be
* publishing it.
*/
export class CdkOutMustBeNpmIgnored extends ValidationRule {
public readonly name = 'package-info/npm-ignore-cdk-out';
public validate(pkg: PackageJson): void {
const npmIgnorePath = path.join(pkg.packageRoot, '.npmignore');
if (fs.existsSync(npmIgnorePath)) {
const npmIgnore = fs.readFileSync(npmIgnorePath);
if (!npmIgnore.includes('**/cdk.out')) {
pkg.report({
ruleName: this.name,
message: `${npmIgnorePath}: Must exclude **/cdk.out`,
fix: () => fs.writeFileSync(
npmIgnorePath,
`${npmIgnore}\n# exclude cdk artifacts\n**/cdk.out`,
),
});
}
}
}
}
/**
* Repository must be our GitHub repo
*/
export class RepositoryCorrect extends ValidationRule {
public readonly name = 'package-info/repository';
public validate(pkg: PackageJson): void {
expectJSON(this.name, pkg, 'repository.type', 'git');
expectJSON(this.name, pkg, 'repository.url', 'https://github.com/aws/aws-cdk.git');
const pkgDir = path.relative(monoRepoRoot(), pkg.packageRoot);
// Enforcing '/' separator for builds to work in Windows.
const osPkgDir = pkgDir.split(path.sep).join('/');
expectJSON(this.name, pkg, 'repository.directory', osPkgDir);
}
}
/**
* Homepage must point to the GitHub repository page.
*/
export class HomepageCorrect extends ValidationRule {
public readonly name = 'package-info/homepage';
public validate(pkg: PackageJson): void {
expectJSON(this.name, pkg, 'homepage', 'https://github.com/aws/aws-cdk');
}
}
/**
* The license must be Apache-2.0.
*/
export class License extends ValidationRule {
public readonly name = 'package-info/license';
public validate(pkg: PackageJson): void {
expectJSON(this.name, pkg, 'license', 'Apache-2.0');
}
}
/**
* There must be a license file that corresponds to the Apache-2.0 license.
*/
export class LicenseFile extends ValidationRule {
public readonly name = 'license/license-file';
public validate(pkg: PackageJson): void {
fileShouldBe(this.name, pkg, 'LICENSE', LICENSE);
}
}
/**
* There must be a NOTICE file.
*/
export class NoticeFile extends ValidationRule {
public readonly name = 'license/notice-file';
public validate(pkg: PackageJson): void {
fileShouldBeginWith(this.name, pkg, 'NOTICE', ...NOTICE.split('\n'));
}
}
/**
* NOTICE files must contain 3rd party attributions
*/
export class ThirdPartyAttributions extends ValidationRule {
public readonly name = 'license/3p-attributions';
public validate(pkg: PackageJson): void {
const alwaysCheck = ['aws-cdk-lib'];
if (pkg.json.private && !alwaysCheck.includes(pkg.json.name)) {
return;
}
const bundled = pkg.getAllBundledDependencies().filter(dep => !dep.startsWith('@aws-cdk'));
const attribution = pkg.json.pkglint?.attribution ?? [];
const noticePath = path.join(pkg.packageRoot, 'NOTICE');
const lines = fs.existsSync(noticePath)
? fs.readFileSync(noticePath, { encoding: 'utf8' }).split('\n')
: [];
const re = /^\*\* (\S+)/;
const attributions = lines.filter(l => re.test(l)).map(l => l.match(re)![1]);
for (const dep of bundled) {
if (!attributions.includes(dep)) {
pkg.report({
message: `Missing attribution for bundled dependency '${dep}' in NOTICE file.`,
ruleName: this.name,
});
}
}
for (const attr of attributions) {
if (!bundled.includes(attr) && !attribution.includes(attr)) {
pkg.report({
message: `Unnecessary attribution found for dependency '${attr}' in NOTICE file. Attribution is determined from package.json (all "bundledDependencies" or the list in "pkglint.attribution")`,
ruleName: this.name,
});
}
}
}
}
export class NodeBundleValidation extends ValidationRule {
public readonly name = '@aws-cdk/node-bundle';
public validate(pkg: PackageJson): void {
const bundleConfig = pkg.json['cdk-package']?.bundle;
if (bundleConfig == null) {
return;
}
const bundle = new Bundle({
...bundleConfig,
packageDir: pkg.packageRoot,
});
const result = bundle.validate({ fix: false });
if (result.success) {
return;
}
for (const violation of result.violations) {
pkg.report({
fix: violation.fix,
message: violation.message,
ruleName: `${this.name} => ${violation.type}`,
});
}
}
}
/**
* Author must be AWS (as an Organization)
*/
export class AuthorAWS extends ValidationRule {
public readonly name = 'package-info/author';
public validate(pkg: PackageJson): void {
expectJSON(this.name, pkg, 'author.name', 'Amazon Web Services');
expectJSON(this.name, pkg, 'author.url', 'https://aws.amazon.com');
expectJSON(this.name, pkg, 'author.organization', true);
}
}
/**
* There must be a README.md file.
*/
export class ReadmeFile extends ValidationRule {
public readonly name = 'package-info/README.md';
public validate(pkg: PackageJson): void {
const readmeFile = path.join(pkg.packageRoot, 'README.md');
const scopes = pkg.json['cdk-build'] && pkg.json['cdk-build'].cloudformation;
if (!scopes) {
return;
}
// elasticsearch is renamed to opensearch service, so its readme does not follow these rules
if (pkg.packageName === '@aws-cdk/core' || pkg.packageName === '@aws-cdk/aws-elasticsearch') {
return;
}
const scope: string = typeof scopes === 'string' ? scopes : scopes[0];
const serviceName = AWS_SERVICE_NAMES[scope];
// If this is a 'cfn-only' package, we fix the README to specific file contents, and
// don't do any other checks.
if (pkg.json.maturity === 'cfn-only') {
fileShouldBe(this.name, pkg, 'README.md', cfnOnlyReadmeContents({
cfnNamespace: scope,
packageName: pkg.packageName,
}));
return;
}
// Otherwise, the cfn-specific disclaimer in it MUST NOT exist.
const disclaimerRegex = beginEndRegex('CFNONLY DISCLAIMER');
const currentReadme = readIfExists(readmeFile);
if (currentReadme && disclaimerRegex.test(currentReadme)) {
pkg.report({
ruleName: this.name,
message: 'README must not include CFNONLY DISCLAIMER section',
fix: () => fs.writeFileSync(readmeFile, currentReadme.replace(disclaimerRegex, '')),
});
}
const headline = serviceName && `${serviceName} Construct Library`;
if (!fs.existsSync(readmeFile)) {
pkg.report({
ruleName: this.name,
message: 'There must be a README.md file at the root of the package',
fix: () => fs.writeFileSync(
readmeFile,
[
`# ${headline || pkg.json.description}`,
'This module is part of the[AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.',
].join('\n'),
),
});
} else if (headline) {
const requiredFirstLine = `# ${headline}`;
const [firstLine, ...rest] = fs.readFileSync(readmeFile, { encoding: 'utf8' }).split('\n');
if (firstLine !== requiredFirstLine) {
pkg.report({
ruleName: this.name,
message: `The title of the README.md file must be "${headline}"`,
fix: () => fs.writeFileSync(readmeFile, [requiredFirstLine, ...rest].join('\n')),
});
}
}
}
}
/**
* All packages must have a "maturity" declaration.
*
* The banner in the README must match the package maturity.
*
* As a way to seed the settings, if 'maturity' is missing but can
* be auto-derived from 'stability', that will be the fix (otherwise
* there is no fix).
*/
export class MaturitySetting extends ValidationRule {
public readonly name = 'package-info/maturity';
public validate(pkg: PackageJson): void {
if (pkg.json.private) {
// Does not apply to private packages!
return;
}
if (pkg.json.features) {
// Skip this in favour of the FeatureStabilityRule.
return;
}
let maturity = pkg.json.maturity as string | undefined;
const stability = pkg.json.stability as string | undefined;
if (!maturity) {
let fix;
if (stability && ['stable', 'deprecated'].includes(stability)) {
// We can autofix!
fix = () => pkg.json.maturity = stability;
maturity = stability;
}
pkg.report({
ruleName: this.name,
message: `Package is missing "maturity" setting (expected one of ${Object.keys(MATURITY_TO_STABILITY)})`,
fix,
});
}
if (pkg.json.deprecated && maturity !== 'deprecated') {
pkg.report({
ruleName: this.name,
message: `Package is deprecated, but is marked with maturity "${maturity}"`,
fix: () => pkg.json.maturity = 'deprecated',
});
maturity = 'deprecated';
}
const packageLevels = this.determinePackageLevels(pkg);
const hasL1s = packageLevels.some(level => level === 'l1');
const hasL2s = packageLevels.some(level => level === 'l2');
if (hasL2s) {
// validate that a package that contains L2s does not declare a 'cfn-only' maturity
if (maturity === 'cfn-only') {
pkg.report({
ruleName: this.name,
message: "Package that contains any L2s cannot declare a 'cfn-only' maturity",
fix: () => pkg.json.maturity = 'experimental',
});
}
} else if (hasL1s) {
// validate that a package that contains only L1s declares a 'cfn-only' maturity
if (maturity !== 'cfn-only') {
pkg.report({
ruleName: this.name,
message: "Package that contains only L1s cannot declare a maturity other than 'cfn-only'",
fix: () => pkg.json.maturity = 'cfn-only',
});
}
}
if (maturity) {
this.validateReadmeHasBanner(pkg, maturity, packageLevels);
}
}
private validateReadmeHasBanner(pkg: PackageJson, maturity: string, levelsPresent: string[]) {
if (pkg.packageName === '@aws-cdk/aws-elasticsearch') {
// Special case for elasticsearch, which is labeled as stable in package.json
// but all APIs are now marked 'deprecated'
return;
}
const badge = this.readmeBadge(maturity, levelsPresent);
if (!badge) {
// Somehow, we don't have a badge for this stability level
return;
}
const readmeFile = path.join(pkg.packageRoot, 'README.md');
if (!fs.existsSync(readmeFile)) {
// Presence of the file is asserted by another rule
return;
}
const readmeContent = fs.readFileSync(readmeFile, { encoding: 'utf8' });
const badgeRegex = toRegExp(badge);
if (!badgeRegex.test(readmeContent)) {
// Removing a possible old, now invalid stability indication from the README.md before adding a new one
const [title, ...body] = readmeContent.replace(/<!--BEGIN STABILITY BANNER-->(?:.|\n)+<!--END STABILITY BANNER-->\n+/m, '').split('\n');
pkg.report({
ruleName: this.name,
message: `Missing stability banner for ${maturity} in README.md file`,
fix: () => fs.writeFileSync(readmeFile, [title, badge, ...body].join('\n')),
});
}
}
private readmeBadge(maturity: string, levelsPresent: string[]) {
const bannerContents = levelsPresent
.map(level => fs.readFileSync(path.join(__dirname, 'banners', `${level}.${maturity}.md`), { encoding: 'utf-8' }).trim())
.join('\n\n')
.trim();
const bannerLines = bannerContents.split('\n').map(s => s.trimRight());
return [
'<!--BEGIN STABILITY BANNER-->',
'',
'---',
'',
...bannerLines,
'',
'---',
'',
'<!--END STABILITY BANNER-->',
'',
].join('\n');
}
private determinePackageLevels(pkg: PackageJson): string[] {
// Used to determine L1 by the presence of a .generated.ts file, but that depends
// on the source having been built. Much more robust to look at the build INSTRUCTIONS
// to see if this package has L1s.
const hasL1 = !!pkg.json['cdk-build']?.cloudformation;
const libFiles = glob.sync('lib/**/*.ts', {
ignore: 'lib/**/*.d.ts', // ignore the generated TS declaration files
});
const hasL2 = libFiles.some(f => !f.endsWith('.generated.ts') && !f.endsWith('index.ts'));
return [
...hasL1 ? ['l1'] : [],
// If we don't have L1, then at least always paste in the L2 banner
...hasL2 || !hasL1 ? ['l2'] : [],
];
}
}
const MATURITY_TO_STABILITY: Record<string, string> = {
'cfn-only': 'experimental',
'experimental': 'experimental',
'developer-preview': 'experimental',
'stable': 'stable',
'deprecated': 'deprecated',
};
/**
* There must be a stability setting, and it must match the package maturity.
*
* Maturity setting is leading here (as there are more options than the
* stability setting), but the stability setting must be present for `jsii`
* to properly read and encode it into the assembly.
*/
export class StabilitySetting extends ValidationRule {
public readonly name = 'package-info/stability';
public validate(pkg: PackageJson): void {
if (pkg.json.private) {
// Does not apply to private packages!
return;
}
if (pkg.json.features) {
// Skip this in favour of the FeatureStabilityRule.
return;
}
const maturity = pkg.json.maturity as string | undefined;
const stability = pkg.json.stability as string | undefined;
const expectedStability = maturity ? MATURITY_TO_STABILITY[maturity] : undefined;
if (!stability || (expectedStability && stability !== expectedStability)) {
pkg.report({
ruleName: this.name,
message: `stability is '${stability}', but based on maturity is expected to be '${expectedStability}'`,
fix: expectedStability ? (() => pkg.json.stability = expectedStability) : undefined,
});
}
}
}
export class FeatureStabilityRule extends ValidationRule {
public readonly name = 'package-info/feature-stability';
private readonly badges: { [key: string]: string } = {
'Not Implemented': 'https://img.shields.io/badge/not--implemented-black.svg?style=for-the-badge',
'Experimental': 'https://img.shields.io/badge/experimental-important.svg?style=for-the-badge',
'Developer Preview': 'https://img.shields.io/badge/developer--preview-informational.svg?style=for-the-badge',
'Stable': 'https://img.shields.io/badge/stable-success.svg?style=for-the-badge',
};
public validate(pkg: PackageJson): void {
if (pkg.json.private || !pkg.json.features) {
return;
}
const featuresColumnWitdh = Math.max(
13, // 'CFN Resources'.length
...pkg.json.features.map((feat: { name: string; }) => feat.name.length),
);
const stabilityBanner: string = [
'<!--BEGIN STABILITY BANNER-->',
'',
'---',
'',
`Features${' '.repeat(featuresColumnWitdh - 8)} | Stability`,
`--------${'-'.repeat(featuresColumnWitdh - 8)}-|-----------${'-'.repeat(Math.max(0, 100 - featuresColumnWitdh - 13))}`,
...this.featureEntries(pkg, featuresColumnWitdh),
'',
...this.bannerNotices(pkg),
'---',
'',
'<!--END STABILITY BANNER-->',
'',
].join('\n');
const readmeFile = path.join(pkg.packageRoot, 'README.md');
if (!fs.existsSync(readmeFile)) {
// Presence of the file is asserted by another rule
return;
}
const readmeContent = fs.readFileSync(readmeFile, { encoding: 'utf8' });
const stabilityRegex = toRegExp(stabilityBanner);
if (!stabilityRegex.test(readmeContent)) {
const [title, ...body] = readmeContent.replace(/<!--BEGIN STABILITY BANNER-->(?:.|\n)+<!--END STABILITY BANNER-->\n+/m, '').split('\n');
pkg.report({
ruleName: this.name,
message: 'Stability banner does not match as expected',
fix: () => fs.writeFileSync(readmeFile, [title, stabilityBanner, ...body].join('\n')),
});
}
}
private featureEntries(pkg: PackageJson, featuresColumnWitdh: number): string[] {
const entries: string[] = [];
if (pkg.json['cdk-build']?.cloudformation) {
entries.push(`CFN Resources${' '.repeat(featuresColumnWitdh - 13)} | ![Stable](${this.badges.Stable})`);
}
pkg.json.features.forEach((feature: { [key: string]: string }) => {
const badge = this.badges[feature.stability];
if (!badge) {
throw new Error(`Unknown stability - ${feature.stability}`);
}
entries.push(`${feature.name}${' '.repeat(featuresColumnWitdh - feature.name.length)} | ![${feature.stability}](${badge})`);
});
return entries;
}
private bannerNotices(pkg: PackageJson): string[] {
const notices: string[] = [];
if (pkg.json['cdk-build']?.cloudformation) {
notices.push(readBannerFile('features-cfn-stable.md'));
notices.push('');
}
const noticeOrder = ['Experimental', 'Developer Preview', 'Stable'];
const stabilities = pkg.json.features.map((f: { [k: string]: string }) => f.stability);
const filteredNotices = noticeOrder.filter(v => stabilities.includes(v));
for (const notice of filteredNotices) {
if (notices.length !== 0) {
// This delimiter helps ensure proper parsing & rendering with various parsers
notices.push('<!-- -->', '');
}
const lowerTrainCase = notice.toLowerCase().replace(/\s/g, '-');
notices.push(readBannerFile(`features-${lowerTrainCase}.md`));
notices.push('');
}
return notices;
}
}
/**
* Keywords must contain CDK keywords and be sorted
*/
export class CDKKeywords extends ValidationRule {
public readonly name = 'package-info/keywords';
public validate(pkg: PackageJson): void {
if (!pkg.json.keywords) {
pkg.report({
ruleName: this.name,
message: 'Must have keywords',
fix: () => { pkg.json.keywords = []; },
});
}
const keywords = pkg.json.keywords || [];
if (keywords.indexOf('cdk') === -1) {
pkg.report({
ruleName: this.name,
message: 'Keywords must mention CDK',
fix: () => { pkg.json.keywords.splice(0, 0, 'cdk'); },
});
}
if (keywords.indexOf('aws') === -1) {
pkg.report({
ruleName: this.name,
message: 'Keywords must mention AWS',
fix: () => { pkg.json.keywords.splice(0, 0, 'aws'); },
});
}
}
}
/**
* Requires projectReferences to be set in the jsii configuration.
*/
export class JSIIProjectReferences extends ValidationRule {
public readonly name = 'jsii/project-references';
public validate(pkg: PackageJson): void {
if (!isJSII(pkg)) {
return;
}
expectJSON(
this.name,
pkg,
'jsii.projectReferences',
pkg.json.name !== 'aws-cdk-lib',
);
}
}
export class NoPeerDependenciesAwsCdkLib extends ValidationRule {
public readonly name = 'aws-cdk-lib/no-peer';
private readonly allowedPeer = ['constructs'];
private readonly modules = ['aws-cdk-lib'];
public validate(pkg: PackageJson): void {
if (!this.modules.includes(pkg.packageName)) {
return;
}
const peers = Object.keys(pkg.peerDependencies).filter(peer => !this.allowedPeer.includes(peer));
if (peers.length > 0) {
pkg.report({
ruleName: this.name,
message: `Adding a peer dependency to the monolithic package ${pkg.packageName} is a breaking change, and thus not allowed.
Added ${peers.join(' ')}`,
});
}
}
}
/**
* Validates that the same version of `constructs` is used wherever a dependency
* is specified, so that they must all be udpated at the same time (through an
* update to this rule).
*
* Note: v1 and v2 use different versions respectively.
*/
export class ConstructsVersion extends ValidationRule {
public static readonly VERSION = cdkMajorVersion() === 2
? '^10.0.0'
: '^3.3.69';
public readonly name = 'deps/constructs';
public validate(pkg: PackageJson) {
const toCheck = new Array<string>();
if ('constructs' in pkg.dependencies) {
toCheck.push('dependencies');
}
if ('constructs' in pkg.devDependencies) {
toCheck.push('devDependencies');
}
if ('constructs' in pkg.peerDependencies) {
toCheck.push('peerDependencies');
}
for (const cfg of toCheck) {
expectJSON(this.name, pkg, `${cfg}.constructs`, ConstructsVersion.VERSION);
}
}
}
/**
* JSII Java package is required and must look sane
*/
export class JSIIJavaPackageIsRequired extends ValidationRule {
public readonly name = 'jsii/java';
public validate(pkg: PackageJson): void {
if (!isJSII(pkg)) { return; }
const moduleName = cdkModuleName(pkg.json.name);
expectJSON(this.name, pkg, 'jsii.targets.java.maven.groupId', 'software.amazon.awscdk');
expectJSON(this.name, pkg, 'jsii.targets.java.maven.artifactId', moduleName.mavenArtifactId, /-/g);
const java = deepGet(pkg.json, ['jsii', 'targets', 'java', 'package']) as string | undefined;
expectJSON(this.name, pkg, 'jsii.targets.java.package', moduleName.javaPackage, /\./g);
if (java) {
const expectedPrefix = moduleName.javaPackage.split('.').slice(0, 3).join('.');
const actualPrefix = java.split('.').slice(0, 3).join('.');
if (expectedPrefix !== actualPrefix) {
pkg.report({
ruleName: this.name,
message: `JSII "java" package must share the first 3 elements of the expected one: ${expectedPrefix} vs ${actualPrefix}`,
fix: () => deepSet(pkg.json, ['jsii', 'targets', 'java', 'package'], moduleName.javaPackage),
});
}
}
}
}
export class JSIIPythonTarget extends ValidationRule {
public readonly name = 'jsii/python';
public validate(pkg: PackageJson): void {
if (!isJSII(pkg)) { return; }
const moduleName = cdkModuleName(pkg.json.name);
// See: https://aws.github.io/jsii/user-guides/lib-author/configuration/targets/python/
expectJSON(this.name, pkg, 'jsii.targets.python.distName', moduleName.python.distName);
expectJSON(this.name, pkg, 'jsii.targets.python.module', moduleName.python.module);
expectJSON(this.name, pkg, 'jsii.targets.python.classifiers', ['Framework :: AWS CDK', `Framework :: AWS CDK :: ${cdkMajorVersion()}`]);
}
}
export class CDKPackage extends ValidationRule {
public readonly name = 'package-info/scripts/package';
public validate(pkg: PackageJson): void {
// skip private packages
if (pkg.json.private) { return; }
const merkleMarker = '.LAST_PACKAGE';
if (!shouldUseCDKBuildTools(pkg)) { return; }
expectJSON(this.name, pkg, 'scripts.package', 'cdk-package');
const outdir = 'dist';
// if this is
if (isJSII(pkg)) {
expectJSON(this.name, pkg, 'jsii.outdir', outdir);
}
fileShouldContain(this.name, pkg, '.npmignore', outdir);
fileShouldContain(this.name, pkg, '.gitignore', outdir);
fileShouldContain(this.name, pkg, '.npmignore', merkleMarker);
fileShouldContain(this.name, pkg, '.gitignore', merkleMarker);
}
}
export class NoTsBuildInfo extends ValidationRule {
public readonly name = 'npmignore/tsbuildinfo';
public validate(pkg: PackageJson): void {
// skip private packages
if (pkg.json.private) { return; }
// Stop 'tsconfig.tsbuildinfo' and regular '.tsbuildinfo' files from being
// published to NPM.
// We might at some point also want to strip tsconfig.json but for now,
// the TypeScript DOCS BUILD needs to it to load the typescript source.
fileShouldContain(this.name, pkg, '.npmignore', '*.tsbuildinfo');
}
}
export class NoTestsInNpmPackage extends ValidationRule {
public readonly name = 'npmignore/test';
public validate(pkg: PackageJson): void {
// skip private packages
if (pkg.json.private) { return; }
// Skip the CLI package, as its 'test' subdirectory is used at runtime.
if (pkg.packageName === 'aws-cdk') { return; }
// Exclude 'test/' directories from being packaged
fileShouldContain(this.name, pkg, '.npmignore', 'test/');
}
}
export class NoTsConfig extends ValidationRule {
public readonly name = 'npmignore/tsconfig';
public validate(pkg: PackageJson): void {
// skip private packages
if (pkg.json.private) { return; }
fileShouldContain(this.name, pkg, '.npmignore', 'tsconfig.json');
}
}
export class IncludeJsiiInNpmTarball extends ValidationRule {
public readonly name = 'npmignore/jsii-included';
public validate(pkg: PackageJson): void {
// only jsii modules
if (!isJSII(pkg)) { return; }
// skip private packages
if (pkg.json.private) { return; }
fileShouldNotContain(this.name, pkg, '.npmignore', '.jsii');
fileShouldContain(this.name, pkg, '.npmignore', '!.jsii'); // make sure .jsii is included
}
}
/**
* Verifies there is no dependency on "jsii" since it's defined at the repo
* level.
*/
export class NoJsiiDep extends ValidationRule {
public readonly name = 'dependencies/no-jsii';
public validate(pkg: PackageJson): void {
const predicate = (s: string) => s.startsWith('jsii');
if (pkg.getDevDependency(predicate)) {
pkg.report({
ruleName: this.name,
message: 'packages should not have a devDep on jsii since it is defined at the repo level',
fix: () => pkg.removeDevDependency(predicate),
});
}
}
}
function isCdkModuleName(name: string) {
return !!name.match(/^@aws-cdk\//);
}
/**
* Computes the module name for various other purposes (java package, ...)
*/
function cdkModuleName(name: string) {
const isCdkPkg = name === '@aws-cdk/core';
const isLegacyCdkPkg = name === '@aws-cdk/cdk';
let suffix = name;
suffix = suffix.replace(/^aws-cdk-/, '');
suffix = suffix.replace(/^@aws-cdk\//, '');
const dotnetSuffix = suffix.split('-')
.map(s => s === 'aws' ? 'AWS' : caseUtils.pascal(s))
.join('.');
const pythonName = suffix.replace(/^@/g, '').replace(/\//g, '.').split('.').map(caseUtils.kebab).join('.');
// list of packages with special-cased Maven ArtifactId.
const mavenIdMap: Record<string, string> = {
'@aws-cdk/core': 'core',
'@aws-cdk/cdk': 'cdk',
'@aws-cdk/assertions': 'assertions',
'@aws-cdk/assertions-alpha': 'assertions-alpha',
};
/* eslint-disable @typescript-eslint/indent */
const mavenArtifactId =
name in mavenIdMap ? mavenIdMap[name] :
(suffix.startsWith('aws-') || suffix.startsWith('alexa-')) ? suffix.replace(/aws-/, '') :
suffix.startsWith('cdk-') ? suffix : `cdk-${suffix}`;
/* eslint-enable @typescript-eslint/indent */
return {
javaPackage: `software.amazon.awscdk${isLegacyCdkPkg ? '' : `.${suffix.replace(/aws-/, 'services-').replace(/-/g, '.')}`}`,
mavenArtifactId,
dotnetNamespace: `Amazon.CDK${isCdkPkg ? '' : `.${dotnetSuffix}`}`,
dotnetPackageId: `Amazon.CDK${isCdkPkg ? '' : `.${dotnetSuffix}`}`,
python: {
distName: `aws-cdk.${pythonName}`,
module: `aws_cdk.${pythonName.replace(/-/g, '_')}`,
},
};
}
/**
* JSII .NET namespace is required and must look sane
*/
export class JSIIDotNetNamespaceIsRequired extends ValidationRule {
public readonly name = 'jsii/dotnet';
public validate(pkg: PackageJson): void {
if (!isJSII(pkg)) { return; }
const dotnet = deepGet(pkg.json, ['jsii', 'targets', 'dotnet', 'namespace']) as string | undefined;
const moduleName = cdkModuleName(pkg.json.name);
expectJSON(this.name, pkg, 'jsii.targets.dotnet.namespace', moduleName.dotnetNamespace, /\./g, /*case insensitive*/ true);
if (dotnet) {
const actualPrefix = dotnet.split('.').slice(0, 2).join('.');
const expectedPrefix = moduleName.dotnetNamespace.split('.').slice(0, 2).join('.');
if (actualPrefix !== expectedPrefix) {
pkg.report({
ruleName: this.name,
message: `.NET namespace must share the first two segments of the default namespace, '${expectedPrefix}' vs '${actualPrefix}'`,
fix: () => deepSet(pkg.json, ['jsii', 'targets', 'dotnet', 'namespace'], moduleName.dotnetNamespace),
});
}
}
}
}
/**
* JSII .NET packageId is required and must look sane
*/
export class JSIIDotNetPackageIdIsRequired extends ValidationRule {
public readonly name = 'jsii/dotnet';
public validate(pkg: PackageJson): void {
if (!isJSII(pkg)) { return; }
const dotnet = deepGet(pkg.json, ['jsii', 'targets', 'dotnet', 'namespace']) as string | undefined;
const moduleName = cdkModuleName(pkg.json.name);
expectJSON(this.name, pkg, 'jsii.targets.dotnet.packageId', moduleName.dotnetPackageId, /\./g, /*case insensitive*/ true);
if (dotnet) {
const actualPrefix = dotnet.split('.').slice(0, 2).join('.');
const expectedPrefix = moduleName.dotnetPackageId.split('.').slice(0, 2).join('.');
if (actualPrefix !== expectedPrefix) {
pkg.report({
ruleName: this.name,
message: `.NET packageId must share the first two segments of the default namespace, '${expectedPrefix}' vs '${actualPrefix}'`,
fix: () => deepSet(pkg.json, ['jsii', 'targets', 'dotnet', 'packageId'], moduleName.dotnetPackageId),
});
}
}
}
}
/**
* JSII .NET icon url is required and must look sane
*/
export class JSIIDotNetIconUrlIsRequired extends ValidationRule {
public readonly name = 'jsii/dotnet/icon-url';
public validate(pkg: PackageJson): void {
if (!isJSII(pkg)) { return; }
const CDK_LOGO_URL = 'https://raw.githubusercontent.com/aws/aws-cdk/main/logo/default-256-dark.png';
expectJSON(this.name, pkg, 'jsii.targets.dotnet.iconUrl', CDK_LOGO_URL);
}
}
/**
* The package must depend on cdk-build-tools
*/
export class MustDependOnBuildTools extends ValidationRule {
public readonly name = 'dependencies/build-tools';
public validate(pkg: PackageJson): void {
if (!shouldUseCDKBuildTools(pkg)) { return; }
// We can't ACTUALLY require cdk-build-tools/package.json here,
// because WE don't depend on cdk-build-tools and we don't know if
// the package does.
expectDevDependency(this.name,
pkg,
'@aws-cdk/cdk-build-tools',
`${PKGLINT_VERSION}`); // eslint-disable-line @typescript-eslint/no-require-imports
}
}
/**
* Build script must be 'cdk-build'
*/
export class MustUseCDKBuild extends ValidationRule {
public readonly name = 'package-info/scripts/build';
public validate(pkg: PackageJson): void {