extensions.ts 6.0 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as es from 'event-stream';
J
Joao Moreno 已提交
7 8 9 10 11 12 13 14 15 16
import { Stream } from 'stream';
import assign = require('object-assign');
import remote = require('gulp-remote-src');
const flatmap = require('gulp-flatmap');
const vzip = require('gulp-vinyl-zip');
const filter = require('gulp-filter');
const rename = require('gulp-rename');
const util = require('gulp-util');
const buffer = require('gulp-buffer');
const json = require('gulp-json-editor');
17 18
const webpack = require('webpack');
const webpackGulp = require('webpack-stream');
19 20 21 22 23
import * as fs from 'fs';
import * as path from 'path';
import * as vsce from 'vsce';
import * as File from 'vinyl';

24
export function fromLocal(extensionPath: string, sourceMappingURLBase?: string): Stream {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
	let result = es.through();

	vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn }).then(fileNames => {
		const files = fileNames
			.map(fileName => path.join(extensionPath, fileName))
			.map(filePath => new File({
				path: filePath,
				stat: fs.statSync(filePath),
				base: extensionPath,
				contents: fs.createReadStream(filePath) as any
			}));

		const filesStream = es.readArray(files);

		// check for a webpack configuration file, then invoke webpack
		// and merge its output with the files stream. also rewrite the package.json
		// file to a new entry point
		if (fs.existsSync(path.join(extensionPath, 'extension.webpack.config.js'))) {
			const packageJsonFilter = filter('package.json', { restore: true });
44

45 46 47
			const patchFilesStream = filesStream
				.pipe(packageJsonFilter)
				.pipe(buffer())
48 49 50 51 52
				.pipe(json(data => {
					// hardcoded entry point directory!
					data.main = data.main.replace('/out/', /dist/);
					return data;
				}))
53 54 55 56 57
				.pipe(packageJsonFilter.restore);

			const webpackConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
			const webpackStream = webpackGulp(webpackConfig, webpack)
				.pipe(es.through(function (data) {
58
					data.stat = data.stat || {};
59 60
					data.base = extensionPath;
					this.emit('data', data);
61
				}))
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
				.pipe(es.through(function (data: File) {
					// source map handling:
					// * rewrite sourceMappingURL
					// * save to disk so that upload-task picks this up
					if (sourceMappingURLBase && /\.js\.map$/.test(data.path)) {
						const contents = (<Buffer>data.contents).toString('utf8');
						data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
							return `${sourceMappingURLBase}/extensions/${path.basename(extensionPath)}/out/${g1}`;
						}), 'utf8');

						if (!fs.existsSync(path.dirname(data.path))) {
							fs.mkdirSync(path.dirname(data.path));
						}
						fs.writeFileSync(data.path, data.contents);

					}
					this.emit('data', data);
				}))
				;
81

82 83 84
			es.merge(webpackStream, patchFilesStream)
				// .pipe(es.through(function (data) {
				// 	// debug
85
				// 	console.log('out', data.path, data.contents.length);
86 87 88 89 90 91 92 93 94
				// 	this.emit('data', data);
				// }))
				.pipe(result);

		} else {
			filesStream.pipe(result);
		}

	}).catch(err => result.emit('error', err));
95 96 97

	return result;
}
J
Joao Moreno 已提交
98 99

function error(err: any): Stream {
100
	const result = es.through();
J
Joao Moreno 已提交
101 102 103 104 105 106 107
	setTimeout(() => result.emit('error', err));
	return result;
}

const baseHeaders = {
	'X-Market-Client-Id': 'VSCode Build',
	'User-Agent': 'VSCode Build',
108
	'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
J
Joao Moreno 已提交
109 110
};

111
export function fromMarketplace(extensionName: string, version: string): Stream {
J
Joao Moreno 已提交
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
	const filterType = 7;
	const value = extensionName;
	const criterium = { filterType, value };
	const criteria = [criterium];
	const pageNumber = 1;
	const pageSize = 1;
	const sortBy = 0;
	const sortOrder = 0;
	const flags = 0x1 | 0x2 | 0x80;
	const assetTypes = ['Microsoft.VisualStudio.Services.VSIXPackage'];
	const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
	const body = JSON.stringify({ filters, assetTypes, flags });
	const headers: any = assign({}, baseHeaders, {
		'Content-Type': 'application/json',
		'Accept': 'application/json;api-version=3.0-preview.1',
		'Content-Length': body.length
	});

	const options = {
		base: 'https://marketplace.visualstudio.com/_apis/public/gallery',
		requestOptions: {
			method: 'POST',
			gzip: true,
			headers,
			body: body
		}
	};

	return remote('/extensionquery', options)
		.pipe(flatmap((stream, f) => {
			const rawResult = f.contents.toString('utf8');
			const result = JSON.parse(rawResult);
			const extension = result.results[0].extensions[0];
			if (!extension) {
146
				return error(`No such extension: ${extension}`);
J
Joao Moreno 已提交
147 148 149 150 151 152 153 154 155 156
			}

			const metadata = {
				id: extension.extensionId,
				publisherId: extension.publisher,
				publisherDisplayName: extension.publisher.displayName
			};

			const extensionVersion = extension.versions.filter(v => v.version === version)[0];
			if (!extensionVersion) {
157
				return error(`No such extension version: ${extensionName} @ ${version}`);
J
Joao Moreno 已提交
158 159 160 161
			}

			const asset = extensionVersion.files.filter(f => f.assetType === 'Microsoft.VisualStudio.Services.VSIXPackage')[0];
			if (!asset) {
162
				return error(`No VSIX found for extension version: ${extensionName} @ ${version}`);
J
Joao Moreno 已提交
163 164
			}

165
			util.log('Downloading extension:', util.colors.yellow(`${extensionName}@${version}`), '...');
J
Joao Moreno 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

			const options = {
				base: asset.source,
				requestOptions: {
					gzip: true,
					headers: baseHeaders
				}
			};

			return remote('', options)
				.pipe(flatmap(stream => {
					const packageJsonFilter = filter('package.json', { restore: true });

					return stream
						.pipe(vzip.src())
						.pipe(filter('extension/**'))
						.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\/?/, '')))
						.pipe(packageJsonFilter)
						.pipe(buffer())
						.pipe(json({ __metadata: metadata }))
						.pipe(packageJsonFilter.restore);
				}));
		}));
}