-
Notifications
You must be signed in to change notification settings - Fork 205
/
package.ts
1823 lines (1555 loc) · 53.6 KB
/
package.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 { promisify } from 'util';
import * as cp from 'child_process';
import * as yazl from 'yazl';
import { ExtensionKind, Manifest } from './manifest';
import { ITranslations, patchNLS } from './nls';
import * as util from './util';
import glob from 'glob';
import minimatch from 'minimatch';
import markdownit from 'markdown-it';
import * as cheerio from 'cheerio';
import * as url from 'url';
import mime from 'mime';
import * as semver from 'semver';
import urljoin from 'url-join';
import {
validateExtensionName,
validateVersion,
validateEngineCompatibility,
validateVSCodeTypesCompatibility,
} from './validation';
import { detectYarn, getDependencies } from './npm';
import * as GitHost from 'hosted-git-info';
import parseSemver from 'parse-semver';
import * as jsonc from 'jsonc-parser';
const MinimatchOptions: minimatch.IOptions = { dot: true };
export interface IInMemoryFile {
path: string;
mode?: number;
readonly contents: Buffer | string;
}
export interface ILocalFile {
path: string;
mode?: number;
readonly localPath: string;
}
export type IFile = IInMemoryFile | ILocalFile;
function isInMemoryFile(file: IFile): file is IInMemoryFile {
return !!(file as IInMemoryFile).contents;
}
export function read(file: IFile): Promise<string> {
if (isInMemoryFile(file)) {
return Promise.resolve(file.contents).then(b => (typeof b === 'string' ? b : b.toString('utf8')));
} else {
return fs.promises.readFile(file.localPath, 'utf8');
}
}
export interface IPackage {
manifest: Manifest;
packagePath: string;
}
export interface IPackageResult extends IPackage {
files: IFile[];
}
export interface IAsset {
type: string;
path: string;
}
/**
* Options for the `createVSIX` function.
* @public
*/
export interface IPackageOptions {
/**
* The destination of the packaged the VSIX.
*
* Defaults to `NAME-VERSION.vsix`.
*/
readonly packagePath?: string;
readonly version?: string;
/**
* Optional target the extension should run on.
*
* https://code.visualstudio.com/api/working-with-extensions/publishing-extension#platformspecific-extensions
*/
readonly target?: string;
readonly commitMessage?: string;
readonly gitTagVersion?: boolean;
readonly updatePackageJson?: boolean;
/**
* The location of the extension in the file system.
*
* Defaults to `process.cwd()`.
*/
readonly cwd?: string;
/**
* GitHub branch used to publish the package. Used to automatically infer
* the base content and images URI.
*/
readonly githubBranch?: string;
/**
* GitLab branch used to publish the package. Used to automatically infer
* the base content and images URI.
*/
readonly gitlabBranch?: string;
readonly rewriteRelativeLinks?: boolean;
/**
* The base URL for links detected in Markdown files.
*/
readonly baseContentUrl?: string;
/**
* The base URL for images detected in Markdown files.
*/
readonly baseImagesUrl?: string;
/**
* Should use Yarn instead of NPM.
*/
readonly useYarn?: boolean;
readonly dependencyEntryPoints?: string[];
readonly ignoreFile?: string;
readonly gitHubIssueLinking?: boolean;
readonly gitLabIssueLinking?: boolean;
readonly dependencies?: boolean;
/**
* Mark this package as a pre-release
*/
readonly preRelease?: boolean;
readonly allowStarActivation?: boolean;
readonly allowMissingRepository?: boolean;
}
export interface IProcessor {
onFile(file: IFile): Promise<IFile>;
onEnd(): Promise<void>;
assets: IAsset[];
tags: string[];
vsix: any;
}
export interface VSIX {
id: string;
displayName: string;
version: string;
publisher: string;
target?: string;
engine: string;
description: string;
categories: string;
flags: string;
icon?: string;
license?: string;
assets: IAsset[];
tags: string;
links: {
repository?: string;
bugs?: string;
homepage?: string;
github?: string;
};
galleryBanner: NonNullable<Manifest['galleryBanner']>;
badges?: Manifest['badges'];
githubMarkdown: boolean;
enableMarketplaceQnA?: boolean;
customerQnALink?: Manifest['qna'];
extensionDependencies: string;
extensionPack: string;
extensionKind: string;
localizedLanguages: string;
preRelease: boolean;
sponsorLink: string;
pricing: string;
}
export class BaseProcessor implements IProcessor {
constructor(protected manifest: Manifest) { }
assets: IAsset[] = [];
tags: string[] = [];
vsix: VSIX = Object.create(null);
async onFile(file: IFile): Promise<IFile> {
return file;
}
async onEnd() {
// noop
}
}
// https://github.com/npm/cli/blob/latest/lib/utils/hosted-git-info-from-manifest.js
function getGitHost(manifest: Manifest): GitHost | undefined {
const url = getRepositoryUrl(manifest);
return url ? GitHost.fromUrl(url, { noGitPlus: true }) : undefined;
}
// https://github.com/npm/cli/blob/latest/lib/repo.js
function getRepositoryUrl(manifest: Manifest, gitHost?: GitHost | null): string | undefined {
if (gitHost) {
return gitHost.https();
}
let url: string | undefined = undefined;
if (manifest.repository) {
if (typeof manifest.repository === 'string') {
url = manifest.repository;
} else if (
typeof manifest.repository === 'object' &&
manifest.repository.url &&
typeof manifest.repository.url === 'string'
) {
url = manifest.repository.url;
}
}
return url;
}
// https://github.com/npm/cli/blob/latest/lib/bugs.js
function getBugsUrl(manifest: Manifest, gitHost: GitHost | undefined): string | undefined {
if (manifest.bugs) {
if (typeof manifest.bugs === 'string') {
return manifest.bugs;
}
if (typeof manifest.bugs === 'object' && manifest.bugs.url) {
return manifest.bugs.url;
}
if (typeof manifest.bugs === 'object' && manifest.bugs.email) {
return `mailto:${manifest.bugs.email}`;
}
}
if (gitHost) {
return gitHost.bugs();
}
return undefined;
}
// https://github.com/npm/cli/blob/latest/lib/docs.js
function getHomepageUrl(manifest: Manifest, gitHost: GitHost | undefined): string | undefined {
if (manifest.homepage) {
return manifest.homepage;
}
if (gitHost) {
return gitHost.docs();
}
return undefined;
}
// Contributed by Mozilla developer authors
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(value: string) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function toExtensionTags(extensions: string[]): string[] {
return extensions
.map(s => s.replace(/\W/g, ''))
.filter(s => !!s)
.map(s => `__ext_${s}`);
}
function toLanguagePackTags(translations: { id: string }[], languageId: string): string[] {
return (translations ?? [])
.map(({ id }) => [`__lp_${id}`, `__lp-${languageId}_${id}`])
.reduce((r, t) => [...r, ...t], []);
}
/* This list is also maintained by the Marketplace team.
* Remember to reach out to them when adding new domains.
*/
const TrustedSVGSources = [
'api.bintray.com',
'api.travis-ci.com',
'api.travis-ci.org',
'app.fossa.io',
'badge.buildkite.com',
'badge.fury.io',
'badge.waffle.io',
'badgen.net',
'badges.frapsoft.com',
'badges.gitter.im',
'badges.greenkeeper.io',
'cdn.travis-ci.com',
'cdn.travis-ci.org',
'ci.appveyor.com',
'circleci.com',
'cla.opensource.microsoft.com',
'codacy.com',
'codeclimate.com',
'codecov.io',
'coveralls.io',
'david-dm.org',
'deepscan.io',
'dev.azure.com',
'docs.rs',
'flat.badgen.net',
'gemnasium.com',
'githost.io',
'gitlab.com',
'godoc.org',
'goreportcard.com',
'img.shields.io',
'isitmaintained.com',
'marketplace.visualstudio.com',
'nodesecurity.io',
'opencollective.com',
'snyk.io',
'travis-ci.com',
'travis-ci.org',
'visualstudio.com',
'vsmarketplacebadges.dev',
'www.bithound.io',
'www.versioneye.com',
];
function isGitHubRepository(repository: string | undefined): boolean {
return /^https:\/\/github\.com\/|^git@github\.com:/.test(repository ?? '');
}
function isGitLabRepository(repository: string | undefined): boolean {
return /^https:\/\/gitlab\.com\/|^git@gitlab\.com:/.test(repository ?? '');
}
function isGitHubBadge(href: string): boolean {
return /^https:\/\/github\.com\/[^/]+\/[^/]+\/(actions\/)?workflows\/.*badge\.svg/.test(href || '');
}
function isHostTrusted(url: url.URL): boolean {
return (url.host && TrustedSVGSources.indexOf(url.host.toLowerCase()) > -1) || isGitHubBadge(url.href);
}
export interface IVersionBumpOptions {
readonly cwd?: string;
readonly version?: string;
readonly commitMessage?: string;
readonly gitTagVersion?: boolean;
readonly updatePackageJson?: boolean;
}
export async function versionBump(options: IVersionBumpOptions): Promise<void> {
if (!options.version) {
return;
}
if (!(options.updatePackageJson ?? true)) {
return;
}
const cwd = options.cwd ?? process.cwd();
const manifest = await readManifest(cwd);
if (manifest.version === options.version) {
return;
}
switch (options.version) {
case 'major':
case 'minor':
case 'patch':
break;
case 'premajor':
case 'preminor':
case 'prepatch':
case 'prerelease':
case 'from-git':
return Promise.reject(`Not supported: ${options.version}`);
default:
if (!semver.valid(options.version)) {
return Promise.reject(`Invalid version ${options.version}`);
}
}
let command = `npm version ${options.version}`;
if (options.commitMessage) {
command = `${command} -m "${options.commitMessage}"`;
}
if (!(options.gitTagVersion ?? true)) {
command = `${command} --no-git-tag-version`;
}
// call `npm version` to do our dirty work
const { stdout, stderr } = await promisify(cp.exec)(command, { cwd });
if (!process.env['VSCE_TESTS']) {
process.stdout.write(stdout);
process.stderr.write(stderr);
}
}
export const Targets = new Set([
'win32-x64',
'win32-ia32',
'win32-arm64',
'linux-x64',
'linux-arm64',
'linux-armhf',
'darwin-x64',
'darwin-arm64',
'alpine-x64',
'alpine-arm64',
'web',
]);
export class ManifestProcessor extends BaseProcessor {
constructor(manifest: Manifest, private readonly options: IPackageOptions = {}) {
super(manifest);
const flags = ['Public'];
if (manifest.preview) {
flags.push('Preview');
}
const gitHost = getGitHost(manifest);
const repository = getRepositoryUrl(manifest, gitHost);
const isGitHub = isGitHubRepository(repository);
let enableMarketplaceQnA: boolean | undefined;
let customerQnALink: string | undefined;
if (manifest.qna === 'marketplace') {
enableMarketplaceQnA = true;
} else if (typeof manifest.qna === 'string') {
customerQnALink = manifest.qna;
} else if (manifest.qna === false) {
enableMarketplaceQnA = false;
}
const extensionKind = getExtensionKind(manifest);
const target = options.target;
const preRelease = options.preRelease;
if (target || preRelease) {
let engineVersion: string;
try {
const engineSemver = parseSemver(`vscode@${manifest.engines['vscode']}`);
engineVersion = engineSemver.version;
} catch (err) {
throw new Error('Failed to parse semver of engines.vscode');
}
if (target) {
if (engineVersion !== 'latest' && !semver.satisfies(engineVersion, '>=1.61', { includePrerelease: true })) {
throw new Error(
`Platform specific extension is supported by VS Code >=1.61. Current 'engines.vscode' is '${manifest.engines['vscode']}'.`
);
}
if (!Targets.has(target)) {
throw new Error(`'${target}' is not a valid VS Code target. Valid targets: ${[...Targets].join(', ')}`);
}
}
if (preRelease) {
if (engineVersion !== 'latest' && !semver.satisfies(engineVersion, '>=1.63', { includePrerelease: true })) {
throw new Error(
`Pre-release versions are supported by VS Code >=1.63. Current 'engines.vscode' is '${manifest.engines['vscode']}'.`
);
}
}
}
this.vsix = {
...this.vsix,
id: manifest.name,
displayName: manifest.displayName ?? manifest.name,
version: options.version && !(options.updatePackageJson ?? true) ? options.version : manifest.version,
publisher: manifest.publisher,
target,
engine: manifest.engines['vscode'],
description: manifest.description ?? '',
pricing: manifest.pricing ?? 'Free',
categories: (manifest.categories ?? []).join(','),
flags: flags.join(' '),
links: {
repository,
bugs: getBugsUrl(manifest, gitHost),
homepage: getHomepageUrl(manifest, gitHost),
},
galleryBanner: manifest.galleryBanner ?? {},
badges: manifest.badges,
githubMarkdown: manifest.markdown !== 'standard',
enableMarketplaceQnA,
customerQnALink,
extensionDependencies: [...new Set(manifest.extensionDependencies ?? [])].join(','),
extensionPack: [...new Set(manifest.extensionPack ?? [])].join(','),
extensionKind: extensionKind.join(','),
localizedLanguages:
manifest.contributes && manifest.contributes.localizations
? manifest.contributes.localizations
.map(loc => loc.localizedLanguageName ?? loc.languageName ?? loc.languageId)
.join(',')
: '',
preRelease: !!this.options.preRelease,
sponsorLink: manifest.sponsor?.url || '',
};
if (isGitHub) {
this.vsix.links.github = repository;
}
}
async onFile(file: IFile): Promise<IFile> {
const path = util.normalize(file.path);
if (!/^extension\/package.json$/i.test(path)) {
return Promise.resolve(file);
}
if (this.options.version && !(this.options.updatePackageJson ?? true)) {
const contents = await read(file);
const packageJson = JSON.parse(contents);
packageJson.version = this.options.version;
file = { ...file, contents: JSON.stringify(packageJson, undefined, 2) };
}
// Ensure that package.json is writable as VS Code needs to
// store metadata in the extracted file.
return { ...file, mode: 0o100644 };
}
async onEnd(): Promise<void> {
if (typeof this.manifest.extensionKind === 'string') {
util.log.warn(
`The 'extensionKind' property should be of type 'string[]'. Learn more at: https://aka.ms/vscode/api/incorrect-execution-location`
);
}
if (this.manifest.publisher === 'vscode-samples') {
throw new Error(
"It's not allowed to use the 'vscode-samples' publisher. Learn more at: https://code.visualstudio.com/api/working-with-extensions/publishing-extension."
);
}
if (!this.options.allowMissingRepository && !this.manifest.repository) {
util.log.warn(`A 'repository' field is missing from the 'package.json' manifest file.`);
if (!/^y$/i.test(await util.read('Do you want to continue? [y/N] '))) {
throw new Error('Aborted');
}
}
if (!this.options.allowStarActivation && this.manifest.activationEvents?.some(e => e === '*')) {
util.log.warn(
`Using '*' activation is usually a bad idea as it impacts performance.\nMore info: https://code.visualstudio.com/api/references/activation-events#Start-up`
);
if (!/^y$/i.test(await util.read('Do you want to continue? [y/N] '))) {
throw new Error('Aborted');
}
}
}
}
export class TagsProcessor extends BaseProcessor {
private static Keywords: Record<string, string[]> = {
git: ['git'],
npm: ['node'],
spell: ['markdown'],
bootstrap: ['bootstrap'],
lint: ['linters'],
linting: ['linters'],
react: ['javascript'],
js: ['javascript'],
node: ['javascript', 'node'],
'c++': ['c++'],
Cplusplus: ['c++'],
xml: ['xml'],
angular: ['javascript'],
jquery: ['javascript'],
php: ['php'],
python: ['python'],
latex: ['latex'],
ruby: ['ruby'],
java: ['java'],
erlang: ['erlang'],
sql: ['sql'],
nodejs: ['node'],
'c#': ['c#'],
css: ['css'],
javascript: ['javascript'],
ftp: ['ftp'],
haskell: ['haskell'],
unity: ['unity'],
terminal: ['terminal'],
powershell: ['powershell'],
laravel: ['laravel'],
meteor: ['meteor'],
emmet: ['emmet'],
eslint: ['linters'],
tfs: ['tfs'],
rust: ['rust'],
};
async onEnd(): Promise<void> {
const keywords = this.manifest.keywords ?? [];
const contributes = this.manifest.contributes;
const activationEvents = this.manifest.activationEvents ?? [];
const doesContribute = (...properties: string[]) => {
let obj = contributes;
for (const property of properties) {
if (!obj) {
return false;
}
obj = obj[property];
}
return obj && obj.length > 0;
};
const colorThemes = doesContribute('themes') ? ['theme', 'color-theme'] : [];
const iconThemes = doesContribute('iconThemes') ? ['theme', 'icon-theme'] : [];
const productIconThemes = doesContribute('productIconThemes') ? ['theme', 'product-icon-theme'] : [];
const snippets = doesContribute('snippets') ? ['snippet'] : [];
const keybindings = doesContribute('keybindings') ? ['keybindings'] : [];
const debuggers = doesContribute('debuggers') ? ['debuggers'] : [];
const json = doesContribute('jsonValidation') ? ['json'] : [];
const remoteMenu = doesContribute('menus', 'statusBar/remoteIndicator') ? ['remote-menu'] : [];
const localizationContributions = ((contributes && contributes['localizations']) ?? []).reduce<string[]>(
(r, l) => [...r, `lp-${l.languageId}`, ...toLanguagePackTags(l.translations, l.languageId)],
[]
);
const languageContributions = ((contributes && contributes['languages']) ?? []).reduce<string[]>(
(r, l) => [...r, l.id, ...(l.aliases ?? []), ...toExtensionTags(l.extensions ?? [])],
[]
);
const languageActivations = activationEvents
.map(e => /^onLanguage:(.*)$/.exec(e))
.filter(util.nonnull)
.map(r => r[1]);
const grammars = ((contributes && contributes['grammars']) ?? []).map(g => g.language);
const description = this.manifest.description || '';
const descriptionKeywords = Object.keys(TagsProcessor.Keywords).reduce<string[]>(
(r, k) =>
r.concat(
new RegExp('\\b(?:' + escapeRegExp(k) + ')(?!\\w)', 'gi').test(description) ? TagsProcessor.Keywords[k] : []
),
[]
);
const webExtensionTags = isWebKind(this.manifest) ? ['__web_extension'] : [];
const sponsorTags = this.manifest.sponsor?.url ? ['__sponsor_extension'] : [];
const tags = new Set([
...keywords,
...colorThemes,
...iconThemes,
...productIconThemes,
...snippets,
...keybindings,
...debuggers,
...json,
...remoteMenu,
...localizationContributions,
...languageContributions,
...languageActivations,
...grammars,
...descriptionKeywords,
...webExtensionTags,
...sponsorTags,
]);
this.tags = [...tags].filter(tag => !!tag);
}
}
export class MarkdownProcessor extends BaseProcessor {
private baseContentUrl: string | undefined;
private baseImagesUrl: string | undefined;
private rewriteRelativeLinks: boolean;
private isGitHub: boolean;
private isGitLab: boolean;
private repositoryUrl: string | undefined;
private gitHubIssueLinking: boolean;
private gitLabIssueLinking: boolean;
constructor(
manifest: Manifest,
private name: string,
private regexp: RegExp,
private assetType: string,
options: IPackageOptions = {}
) {
super(manifest);
const guess = this.guessBaseUrls(options.githubBranch || options.gitlabBranch);
this.baseContentUrl = options.baseContentUrl || (guess && guess.content);
this.baseImagesUrl = options.baseImagesUrl || options.baseContentUrl || (guess && guess.images);
this.rewriteRelativeLinks = options.rewriteRelativeLinks ?? true;
this.repositoryUrl = guess && guess.repository;
this.isGitHub = isGitHubRepository(this.repositoryUrl);
this.isGitLab = isGitLabRepository(this.repositoryUrl);
this.gitHubIssueLinking = typeof options.gitHubIssueLinking === 'boolean' ? options.gitHubIssueLinking : true;
this.gitLabIssueLinking = typeof options.gitLabIssueLinking === 'boolean' ? options.gitLabIssueLinking : true;
}
async onFile(file: IFile): Promise<IFile> {
const filePath = util.normalize(file.path);
if (!this.regexp.test(filePath)) {
return Promise.resolve(file);
}
this.assets.push({ type: this.assetType, path: filePath });
let contents = await read(file);
if (/This is the README for your extension /.test(contents)) {
throw new Error(`It seems the README.md still contains template text. Make sure to edit the README.md file before you package or publish your extension.`);
}
if (this.rewriteRelativeLinks) {
const markdownPathRegex = /(!?)\[([^\]\[]*|!\[[^\]\[]*]\([^\)]+\))\]\(([^\)]+)\)/g;
const urlReplace = (_: string, isImage: string, title: string, link: string) => {
if (/^mailto:/i.test(link)) {
return `${isImage}[${title}](${link})`;
}
const isLinkRelative = !/^\w+:\/\//.test(link) && link[0] !== '#';
if (!this.baseContentUrl && !this.baseImagesUrl) {
const asset = isImage ? 'image' : 'link';
if (isLinkRelative) {
throw new Error(
`Couldn't detect the repository where this extension is published. The ${asset} '${link}' will be broken in ${this.name}. GitHub/GitLab repositories will be automatically detected. Otherwise, please provide the repository URL in package.json or use the --baseContentUrl and --baseImagesUrl options.`
);
}
}
title = title.replace(markdownPathRegex, urlReplace);
const prefix = isImage ? this.baseImagesUrl : this.baseContentUrl;
if (!prefix || !isLinkRelative) {
return `${isImage}[${title}](${link})`;
}
return `${isImage}[${title}](${urljoin(prefix, path.posix.normalize(link))})`;
};
// Replace Markdown links with urls
contents = contents.replace(markdownPathRegex, urlReplace);
// Replace <img> links with urls
contents = contents.replace(/<img.+?src=["']([/.\w\s#-]+)['"].*?>/g, (all, link) => {
const isLinkRelative = !/^\w+:\/\//.test(link) && link[0] !== '#';
if (!this.baseImagesUrl && isLinkRelative) {
throw new Error(
`Couldn't detect the repository where this extension is published. The image will be broken in ${this.name}. GitHub/GitLab repositories will be automatically detected. Otherwise, please provide the repository URL in package.json or use the --baseContentUrl and --baseImagesUrl options.`
);
}
const prefix = this.baseImagesUrl;
if (!prefix || !isLinkRelative) {
return all;
}
return all.replace(link, urljoin(prefix, path.posix.normalize(link)));
});
if ((this.gitHubIssueLinking && this.isGitHub) || (this.gitLabIssueLinking && this.isGitLab)) {
const markdownIssueRegex = /(\s|\n)([\w\d_-]+\/[\w\d_-]+)?#(\d+)\b/g;
const issueReplace = (
all: string,
prefix: string,
ownerAndRepositoryName: string,
issueNumber: string
): string => {
let result = all;
let owner: string | undefined;
let repositoryName: string | undefined;
if (ownerAndRepositoryName) {
[owner, repositoryName] = ownerAndRepositoryName.split('/', 2);
}
if (owner && repositoryName && issueNumber) {
// Issue in external repository
const issueUrl = this.isGitHub
? urljoin('https://github.com', owner, repositoryName, 'issues', issueNumber)
: urljoin('https://gitlab.com', owner, repositoryName, '-', 'issues', issueNumber);
result = prefix + `[${owner}/${repositoryName}#${issueNumber}](${issueUrl})`;
} else if (!owner && !repositoryName && issueNumber && this.repositoryUrl) {
// Issue in own repository
result =
prefix +
`[#${issueNumber}](${this.isGitHub
? urljoin(this.repositoryUrl, 'issues', issueNumber)
: urljoin(this.repositoryUrl, '-', 'issues', issueNumber)
})`;
}
return result;
};
// Replace Markdown issue references with urls
contents = contents.replace(markdownIssueRegex, issueReplace);
}
}
const html = markdownit({ html: true }).render(contents);
const $ = cheerio.load(html);
if (this.rewriteRelativeLinks) {
$('img').each((_, img) => {
const rawSrc = $(img).attr('src');
if (!rawSrc) {
throw new Error(`Images in ${this.name} must have a source.`);
}
const src = decodeURI(rawSrc);
const srcUrl = new url.URL(src);
if (/^data:$/i.test(srcUrl.protocol) && /^image$/i.test(srcUrl.host) && /\/svg/i.test(srcUrl.pathname)) {
throw new Error(`SVG data URLs are not allowed in ${this.name}: ${src}`);
}
if (!/^https:$/i.test(srcUrl.protocol)) {
throw new Error(`Images in ${this.name} must come from an HTTPS source: ${src}`);
}
if (/\.svg$/i.test(srcUrl.pathname) && !isHostTrusted(srcUrl)) {
throw new Error(
`SVGs are restricted in ${this.name}; please use other file image formats, such as PNG: ${src}`
);
}
});
}
$('svg').each(() => {
throw new Error(`SVG tags are not allowed in ${this.name}.`);
});
return {
path: file.path,
contents: Buffer.from(contents, 'utf8'),
};
}
// GitHub heuristics
private guessBaseUrls(
githostBranch: string | undefined
): { content: string; images: string; repository: string } | undefined {
let repository = null;
if (typeof this.manifest.repository === 'string') {
repository = this.manifest.repository;
} else if (this.manifest.repository && typeof this.manifest.repository['url'] === 'string') {
repository = this.manifest.repository['url'];
}
if (!repository) {
return undefined;
}
const gitHubRegex = /(?<domain>github(\.com\/|:))(?<project>(?:[^/]+)\/(?:[^/]+))(\/|$)/;
const gitLabRegex = /(?<domain>gitlab(\.com\/|:))(?<project>(?:[^/]+)(\/(?:[^/]+))+)(\/|$)/;
const match = ((gitHubRegex.exec(repository) || gitLabRegex.exec(repository)) as unknown) as {
groups: Record<string, string>;
};
if (!match) {
return undefined;
}
const project = match.groups.project.replace(/\.git$/i, '');
const branchName = githostBranch ? githostBranch : 'HEAD';
if (/^github/.test(match.groups.domain)) {
return {
content: `https://github.com/${project}/blob/${branchName}`,
images: `https://github.com/${project}/raw/${branchName}`,
repository: `https://github.com/${project}`,
};
} else if (/^gitlab/.test(match.groups.domain)) {
return {
content: `https://gitlab.com/${project}/-/blob/${branchName}`,
images: `https://gitlab.com/${project}/-/raw/${branchName}`,
repository: `https://gitlab.com/${project}`,
};
}
return undefined;
}
}
export class ReadmeProcessor extends MarkdownProcessor {
constructor(manifest: Manifest, options: IPackageOptions = {}) {
super(manifest, 'README.md', /^extension\/readme.md$/i, 'Microsoft.VisualStudio.Services.Content.Details', options);
}
}
export class ChangelogProcessor extends MarkdownProcessor {
constructor(manifest: Manifest, options: IPackageOptions = {}) {
super(
manifest,
'CHANGELOG.md',
/^extension\/changelog.md$/i,
'Microsoft.VisualStudio.Services.Content.Changelog',
options
);
}
}
class LicenseProcessor extends BaseProcessor {
private didFindLicense = false;
private expectedLicenseName: string;
filter: (name: string) => boolean;
constructor(manifest: Manifest) {
super(manifest);
const match = /^SEE LICENSE IN (.*)$/.exec(manifest.license || '');
if (!match || !match[1]) {
this.expectedLicenseName = 'LICENSE.md, LICENSE.txt or LICENSE';
this.filter = name => /^extension\/license(\.(md|txt))?$/i.test(name);
} else {
this.expectedLicenseName = match[1];
const regexp = new RegExp('^extension/' + match[1] + '$');
this.filter = regexp.test.bind(regexp);
}
delete this.vsix.license;
}
onFile(file: IFile): Promise<IFile> {
if (!this.didFindLicense) {
let normalizedPath = util.normalize(file.path);
if (this.filter(normalizedPath)) {
if (!path.extname(normalizedPath)) {
file.path += '.txt';
normalizedPath += '.txt';
}
this.assets.push({ type: 'Microsoft.VisualStudio.Services.Content.License', path: normalizedPath });
this.vsix.license = normalizedPath;
this.didFindLicense = true;
}
}
return Promise.resolve(file);
}
async onEnd(): Promise<void> {
if (!this.didFindLicense) {
util.log.warn(`${this.expectedLicenseName} not found`);
if (!/^y$/i.test(await util.read('Do you want to continue? [y/N] '))) {
throw new Error('Aborted');
}
}
}
}
class LaunchEntryPointProcessor extends BaseProcessor {
private entryPoints: Set<string> = new Set<string>();
constructor(manifest: Manifest) {
super(manifest);
if (manifest.main) {
this.entryPoints.add(util.normalize(path.join('extension', this.appendJSExt(manifest.main))));
}
if (manifest.browser) {
this.entryPoints.add(util.normalize(path.join('extension', this.appendJSExt(manifest.browser))));
}
}
appendJSExt(filePath: string): string {
if (filePath.endsWith('.js') || filePath.endsWith('.cjs')) {
return filePath;
}
return filePath + '.js';
}
onFile(file: IFile): Promise<IFile> {
this.entryPoints.delete(util.normalize(file.path));
return Promise.resolve(file);
}
async onEnd(): Promise<void> {
if (this.entryPoints.size > 0) {