hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 1, "code_window": [ " if (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n", " continue;\n", " }\n", " if (/\\.d\\.ts$/.test(file.name)) {\n", " signature = crypto.createHash('md5')\n", " .update(file.text)\n", " .digest('base64');\n", " if (!userWantsDeclarations) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " signature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.js", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; import { formatOptions, Option, OptionDescriptions, Subcommand, parseArgs, ErrorReporter } from 'vs/platform/environment/node/argv'; import { addArg } from 'vs/platform/environment/node/argvHelper'; function o(description: string, type: 'boolean' | 'string' | 'string[]' = 'string'): Option<any> { return { description, type }; } function c(description: string, options: OptionDescriptions<any>): Subcommand<any> { return { description, type: 'subcommand', options }; } suite('formatOptions', () => { test('Text should display small columns correctly', () => { assert.deepStrictEqual( formatOptions({ 'add': o('bar') }, 80), [' --add bar'] ); assert.deepStrictEqual( formatOptions({ 'add': o('bar'), 'wait': o('ba'), 'trace': o('b') }, 80), [ ' --add bar', ' --wait ba', ' --trace b' ]); }); test('Text should wrap', () => { assert.deepStrictEqual( formatOptions({ 'add': o((<any>'bar ').repeat(9)) }, 40), [ ' --add bar bar bar bar bar bar', ' bar bar bar' ]); }); test('Text should revert to the condensed view when the terminal is too narrow', () => { assert.deepStrictEqual( formatOptions({ 'add': o((<any>'bar ').repeat(9)) }, 30), [ ' --add', ' bar bar bar bar bar bar bar bar bar ' ]); }); test('addArg', () => { assert.deepStrictEqual(addArg([], 'foo'), ['foo']); assert.deepStrictEqual(addArg([], 'foo', 'bar'), ['foo', 'bar']); assert.deepStrictEqual(addArg(['foo'], 'bar'), ['foo', 'bar']); assert.deepStrictEqual(addArg(['--wait'], 'bar'), ['--wait', 'bar']); assert.deepStrictEqual(addArg(['--wait', '--', '--foo'], 'bar'), ['--wait', 'bar', '--', '--foo']); assert.deepStrictEqual(addArg(['--', '--foo'], 'bar'), ['bar', '--', '--foo']); }); test('subcommands', () => { assert.deepStrictEqual( formatOptions({ 'testcmd': c('A test command', { add: o('A test command option') }) }, 30), [ ' --testcmd', ' A test command' ]); }); ensureNoDisposablesAreLeakedInTestSuite(); }); suite('parseArgs', () => { function newErrorReporter(result: string[] = [], command = ''): ErrorReporter & { result: string[] } { const commandPrefix = command ? command + '-' : ''; return { onDeprecatedOption: (deprecatedId) => result.push(`${commandPrefix}onDeprecatedOption ${deprecatedId}`), onUnknownOption: (id) => result.push(`${commandPrefix}onUnknownOption ${id}`), onEmptyValue: (id) => result.push(`${commandPrefix}onEmptyValue ${id}`), onMultipleValues: (id, usedValue) => result.push(`${commandPrefix}onMultipleValues ${id} ${usedValue}`), getSubcommandReporter: (c) => newErrorReporter(result, commandPrefix + c), result }; } function assertParse<T>(options: OptionDescriptions<T>, input: string[], expected: T, expectedErrors: string[]) { const errorReporter = newErrorReporter(); assert.deepStrictEqual(parseArgs(input, options, errorReporter), expected); assert.deepStrictEqual(errorReporter.result, expectedErrors); } test('subcommands', () => { interface TestArgs1 { testcmd?: { testArg?: string; _: string[]; }; _: string[]; } const options1 = { 'testcmd': c('A test command', { testArg: o('A test command option'), _: { type: 'string[]' } }), _: { type: 'string[]' } } as OptionDescriptions<TestArgs1>; assertParse( options1, ['testcmd', '--testArg=foo'], { testcmd: { testArg: 'foo', '_': [] }, '_': [] }, [] ); assertParse( options1, ['testcmd', '--testArg=foo', '--testX'], { testcmd: { testArg: 'foo', '_': [] }, '_': [] }, ['testcmd-onUnknownOption testX'] ); interface TestArgs2 { testcmd?: { testArg?: string; testX?: boolean; _: string[]; }; testX?: boolean; _: string[]; } const options2 = { 'testcmd': c('A test command', { testArg: o('A test command option') }), testX: { type: 'boolean', global: true, description: '' }, _: { type: 'string[]' } } as OptionDescriptions<TestArgs2>; assertParse( options2, ['testcmd', '--testArg=foo', '--testX'], { testcmd: { testArg: 'foo', testX: true, '_': [] }, '_': [] }, [] ); }); ensureNoDisposablesAreLeakedInTestSuite(); });
src/vs/platform/environment/test/node/argv.test.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.00017387192929163575, 0.00017009626026265323, 0.00016590078303124756, 0.00016964157111942768, 0.0000021955868305667536 ]
{ "id": 1, "code_window": [ " if (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n", " continue;\n", " }\n", " if (/\\.d\\.ts$/.test(file.name)) {\n", " signature = crypto.createHash('md5')\n", " .update(file.text)\n", " .digest('base64');\n", " if (!userWantsDeclarations) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " signature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.js", "type": "replace", "edit_start_line_idx": 108 }
// Type definitions for DOM Purify 3.0 // Project: https://github.com/cure53/DOMPurify // Definitions by: Dave Taylor https://github.com/davetayls // Samira Bazuzi <https://github.com/bazuzi> // FlowCrypt <https://github.com/FlowCrypt> // Exigerr <https://github.com/Exigerr> // Piotr Błażejewicz <https://github.com/peterblazejewicz> // Nicholas Ellul <https://github.com/NicholasEllul> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 4.5 export as namespace DOMPurify; export = DOMPurify; declare const DOMPurify: createDOMPurifyI; type WindowLike = Pick< typeof globalThis, | 'NodeFilter' | 'Node' | 'Element' | 'HTMLTemplateElement' | 'DocumentFragment' | 'HTMLFormElement' | 'DOMParser' | 'NamedNodeMap' >; interface createDOMPurifyI extends DOMPurify.DOMPurifyI { (window?: Window | WindowLike): DOMPurify.DOMPurifyI; } declare namespace DOMPurify { interface DOMPurifyI { sanitize(source: string | Node): string; sanitize(source: string | Node, config: Config & { RETURN_TRUSTED_TYPE: true }): TrustedHTML; sanitize( source: string | Node, config: Config & { RETURN_DOM_FRAGMENT?: false | undefined; RETURN_DOM?: false | undefined }, ): string; sanitize(source: string | Node, config: Config & { RETURN_DOM_FRAGMENT: true }): DocumentFragment; sanitize(source: string | Node, config: Config & { RETURN_DOM: true }): HTMLElement; sanitize(source: string | Node, config: Config): string | HTMLElement | DocumentFragment; addHook( hook: 'uponSanitizeElement', cb: (currentNode: Element, data: SanitizeElementHookEvent, config: Config) => void, ): void; addHook( hook: 'uponSanitizeAttribute', cb: (currentNode: Element, data: SanitizeAttributeHookEvent, config: Config) => void, ): void; addHook(hook: HookName, cb: (currentNode: Element, data: HookEvent, config: Config) => void): void; setConfig(cfg: Config): void; clearConfig(): void; isValidAttribute(tag: string, attr: string, value: string): boolean; removeHook(entryPoint: HookName): void; removeHooks(entryPoint: HookName): void; removeAllHooks(): void; version: string; removed: any[]; isSupported: boolean; } interface Config { ADD_ATTR?: string[] | undefined; ADD_DATA_URI_TAGS?: string[] | undefined; ADD_TAGS?: string[] | undefined; ADD_URI_SAFE_ATTR?: string[] | undefined; ALLOW_ARIA_ATTR?: boolean | undefined; ALLOW_DATA_ATTR?: boolean | undefined; ALLOW_UNKNOWN_PROTOCOLS?: boolean | undefined; ALLOW_SELF_CLOSE_IN_ATTR?: boolean | undefined; ALLOWED_ATTR?: string[] | undefined; ALLOWED_TAGS?: string[] | undefined; ALLOWED_NAMESPACES?: string[] | undefined; ALLOWED_URI_REGEXP?: RegExp | undefined; FORBID_ATTR?: string[] | undefined; FORBID_CONTENTS?: string[] | undefined; FORBID_TAGS?: string[] | undefined; FORCE_BODY?: boolean | undefined; IN_PLACE?: boolean | undefined; KEEP_CONTENT?: boolean | undefined; /** * change the default namespace from HTML to something different */ NAMESPACE?: string | undefined; PARSER_MEDIA_TYPE?: string | undefined; RETURN_DOM_FRAGMENT?: boolean | undefined; /** * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false` * might cause XSS from attacks hidden in closed shadowroots in case the browser * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/ */ RETURN_DOM_IMPORT?: boolean | undefined; RETURN_DOM?: boolean | undefined; RETURN_TRUSTED_TYPE?: boolean | undefined; SAFE_FOR_TEMPLATES?: boolean | undefined; SANITIZE_DOM?: boolean | undefined; /** @default false */ SANITIZE_NAMED_PROPS?: boolean | undefined; USE_PROFILES?: | false | { mathMl?: boolean | undefined; svg?: boolean | undefined; svgFilters?: boolean | undefined; html?: boolean | undefined; } | undefined; WHOLE_DOCUMENT?: boolean | undefined; CUSTOM_ELEMENT_HANDLING?: { tagNameCheck?: RegExp | ((tagName: string) => boolean) | null | undefined; attributeNameCheck?: RegExp | ((lcName: string) => boolean) | null | undefined; allowCustomizedBuiltInElements?: boolean | undefined; }; } type HookName = | 'beforeSanitizeElements' | 'uponSanitizeElement' | 'afterSanitizeElements' | 'beforeSanitizeAttributes' | 'uponSanitizeAttribute' | 'afterSanitizeAttributes' | 'beforeSanitizeShadowDOM' | 'uponSanitizeShadowNode' | 'afterSanitizeShadowDOM'; type HookEvent = SanitizeElementHookEvent | SanitizeAttributeHookEvent | null; interface SanitizeElementHookEvent { tagName: string; allowedTags: { [key: string]: boolean }; } interface SanitizeAttributeHookEvent { attrName: string; attrValue: string; keepAttr: boolean; allowedAttributes: { [key: string]: boolean }; forceKeepAttr?: boolean | undefined; } }
src/vs/base/browser/dompurify/dompurify.d.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.00042918696999549866, 0.0001879957999335602, 0.0001643991272430867, 0.00016991127631627023, 0.00006469999789260328 ]
{ "id": 2, "code_window": [ "\t\t\t\t\tif (/\\.d\\.ts$/.test(fileName)) {\n", "\t\t\t\t\t\t// if it's already a d.ts file just emit it signature\n", "\t\t\t\t\t\tconst snapshot = host.getScriptSnapshot(fileName);\n", "\t\t\t\t\t\tconst signature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t.update(snapshot.getText(0, snapshot.getLength()))\n", "\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\treturn resolve({\n", "\t\t\t\t\t\t\tfileName,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\tconst signature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fs from 'fs'; import * as path from 'path'; import * as crypto from 'crypto'; import * as utils from './utils'; import * as colors from 'ansi-colors'; import * as ts from 'typescript'; import * as Vinyl from 'vinyl'; import { RawSourceMap, SourceMapConsumer, SourceMapGenerator } from 'source-map'; export interface IConfiguration { logFn: (topic: string, message: string) => void; _emitWithoutBasePath?: boolean; } export interface CancellationToken { isCancellationRequested(): boolean; } export namespace CancellationToken { export const None: CancellationToken = { isCancellationRequested() { return false; } }; } export interface ITypeScriptBuilder { build(out: (file: Vinyl) => void, onError: (err: ts.Diagnostic) => void, token?: CancellationToken): Promise<any>; file(file: Vinyl): void; languageService: ts.LanguageService; } function normalize(path: string): string { return path.replace(/\\/g, '/'); } export function createTypeScriptBuilder(config: IConfiguration, projectFile: string, cmd: ts.ParsedCommandLine): ITypeScriptBuilder { const _log = config.logFn; const host = new LanguageServiceHost(cmd, projectFile, _log); const service = ts.createLanguageService(host, ts.createDocumentRegistry()); const lastBuildVersion: { [path: string]: string } = Object.create(null); const lastDtsHash: { [path: string]: string } = Object.create(null); const userWantsDeclarations = cmd.options.declaration; let oldErrors: { [path: string]: ts.Diagnostic[] } = Object.create(null); let headUsed = process.memoryUsage().heapUsed; let emitSourceMapsInStream = true; // always emit declaraction files host.getCompilationSettings().declaration = true; function file(file: Vinyl): void { // support gulp-sourcemaps if ((<any>file).sourceMap) { emitSourceMapsInStream = false; } if (!file.contents) { host.removeScriptSnapshot(file.path); } else { host.addScriptSnapshot(file.path, new VinylScriptSnapshot(file)); } } function baseFor(snapshot: ScriptSnapshot): string { if (snapshot instanceof VinylScriptSnapshot) { return cmd.options.outDir || snapshot.getBase(); } else { return ''; } } function isExternalModule(sourceFile: ts.SourceFile): boolean { return (<any>sourceFile).externalModuleIndicator || /declare\s+module\s+('|")(.+)\1/.test(sourceFile.getText()); } function build(out: (file: Vinyl) => void, onError: (err: any) => void, token = CancellationToken.None): Promise<any> { function checkSyntaxSoon(fileName: string): Promise<ts.Diagnostic[]> { return new Promise<ts.Diagnostic[]>(resolve => { process.nextTick(function () { if (!host.getScriptSnapshot(fileName, false)) { resolve([]); // no script, no problems } else { resolve(service.getSyntacticDiagnostics(fileName)); } }); }); } function checkSemanticsSoon(fileName: string): Promise<ts.Diagnostic[]> { return new Promise<ts.Diagnostic[]>(resolve => { process.nextTick(function () { if (!host.getScriptSnapshot(fileName, false)) { resolve([]); // no script, no problems } else { resolve(service.getSemanticDiagnostics(fileName)); } }); }); } function emitSoon(fileName: string): Promise<{ fileName: string; signature?: string; files: Vinyl[] }> { return new Promise(resolve => { process.nextTick(function () { if (/\.d\.ts$/.test(fileName)) { // if it's already a d.ts file just emit it signature const snapshot = host.getScriptSnapshot(fileName); const signature = crypto.createHash('md5') .update(snapshot.getText(0, snapshot.getLength())) .digest('base64'); return resolve({ fileName, signature, files: [] }); } const output = service.getEmitOutput(fileName); const files: Vinyl[] = []; let signature: string | undefined; for (const file of output.outputFiles) { if (!emitSourceMapsInStream && /\.js\.map$/.test(file.name)) { continue; } if (/\.d\.ts$/.test(file.name)) { signature = crypto.createHash('md5') .update(file.text) .digest('base64'); if (!userWantsDeclarations) { // don't leak .d.ts files if users don't want them continue; } } const vinyl = new Vinyl({ path: file.name, contents: Buffer.from(file.text), base: !config._emitWithoutBasePath && baseFor(host.getScriptSnapshot(fileName)) || undefined }); if (!emitSourceMapsInStream && /\.js$/.test(file.name)) { const sourcemapFile = output.outputFiles.filter(f => /\.js\.map$/.test(f.name))[0]; if (sourcemapFile) { const extname = path.extname(vinyl.relative); const basename = path.basename(vinyl.relative, extname); const dirname = path.dirname(vinyl.relative); const tsname = (dirname === '.' ? '' : dirname + '/') + basename + '.ts'; let sourceMap = <RawSourceMap>JSON.parse(sourcemapFile.text); sourceMap.sources[0] = tsname.replace(/\\/g, '/'); // check for an "input source" map and combine them // in step 1 we extract all line edit from the input source map, and // in step 2 we apply the line edits to the typescript source map const snapshot = host.getScriptSnapshot(fileName); if (snapshot instanceof VinylScriptSnapshot && snapshot.sourceMap) { const inputSMC = new SourceMapConsumer(snapshot.sourceMap); const tsSMC = new SourceMapConsumer(sourceMap); let didChange = false; const smg = new SourceMapGenerator({ file: sourceMap.file, sourceRoot: sourceMap.sourceRoot }); // step 1 const lineEdits = new Map<number, [from: number, to: number][]>(); inputSMC.eachMapping(m => { if (m.originalLine === m.generatedLine) { // same line mapping let array = lineEdits.get(m.originalLine); if (!array) { array = []; lineEdits.set(m.originalLine, array); } array.push([m.originalColumn, m.generatedColumn]); } else { // NOT SUPPORTED } }); // step 2 tsSMC.eachMapping(m => { didChange = true; const edits = lineEdits.get(m.originalLine); let originalColumnDelta = 0; if (edits) { for (const [from, to] of edits) { if (to >= m.originalColumn) { break; } originalColumnDelta = from - to; } } smg.addMapping({ source: m.source, name: m.name, generated: { line: m.generatedLine, column: m.generatedColumn }, original: { line: m.originalLine, column: m.originalColumn + originalColumnDelta } }); }); if (didChange) { [tsSMC, inputSMC].forEach((consumer) => { (<SourceMapConsumer & { sources: string[] }>consumer).sources.forEach((sourceFile: any) => { (<any>smg)._sources.add(sourceFile); const sourceContent = consumer.sourceContentFor(sourceFile); if (sourceContent !== null) { smg.setSourceContent(sourceFile, sourceContent); } }); }); sourceMap = JSON.parse(smg.toString()); // const filename = '/Users/jrieken/Code/vscode/src2/' + vinyl.relative + '.map'; // fs.promises.mkdir(path.dirname(filename), { recursive: true }).then(async () => { // await fs.promises.writeFile(filename, smg.toString()); // await fs.promises.writeFile('/Users/jrieken/Code/vscode/src2/' + vinyl.relative, vinyl.contents); // }); } } (<any>vinyl).sourceMap = sourceMap; } } files.push(vinyl); } resolve({ fileName, signature, files }); }); }); } const newErrors: { [path: string]: ts.Diagnostic[] } = Object.create(null); const t1 = Date.now(); const toBeEmitted: string[] = []; const toBeCheckedSyntactically: string[] = []; const toBeCheckedSemantically: string[] = []; const filesWithChangedSignature: string[] = []; const dependentFiles: string[] = []; const newLastBuildVersion = new Map<string, string>(); for (const fileName of host.getScriptFileNames()) { if (lastBuildVersion[fileName] !== host.getScriptVersion(fileName)) { toBeEmitted.push(fileName); toBeCheckedSyntactically.push(fileName); toBeCheckedSemantically.push(fileName); } } return new Promise<void>(resolve => { const semanticCheckInfo = new Map<string, number>(); const seenAsDependentFile = new Set<string>(); function workOnNext() { let promise: Promise<any> | undefined; // let fileName: string; // someone told us to stop this if (token.isCancellationRequested()) { _log('[CANCEL]', '>>This compile run was cancelled<<'); newLastBuildVersion.clear(); resolve(); return; } // (1st) emit code else if (toBeEmitted.length) { const fileName = toBeEmitted.pop()!; promise = emitSoon(fileName).then(value => { for (const file of value.files) { _log('[emit code]', file.path); out(file); } // remember when this was build newLastBuildVersion.set(fileName, host.getScriptVersion(fileName)); // remeber the signature if (value.signature && lastDtsHash[fileName] !== value.signature) { lastDtsHash[fileName] = value.signature; filesWithChangedSignature.push(fileName); } }).catch(e => { // can't just skip this or make a result up.. host.error(`ERROR emitting ${fileName}`); host.error(e); }); } // (2nd) check syntax else if (toBeCheckedSyntactically.length) { const fileName = toBeCheckedSyntactically.pop()!; _log('[check syntax]', fileName); promise = checkSyntaxSoon(fileName).then(diagnostics => { delete oldErrors[fileName]; if (diagnostics.length > 0) { diagnostics.forEach(d => onError(d)); newErrors[fileName] = diagnostics; // stop the world when there are syntax errors toBeCheckedSyntactically.length = 0; toBeCheckedSemantically.length = 0; filesWithChangedSignature.length = 0; } }); } // (3rd) check semantics else if (toBeCheckedSemantically.length) { let fileName = toBeCheckedSemantically.pop(); while (fileName && semanticCheckInfo.has(fileName)) { fileName = toBeCheckedSemantically.pop()!; } if (fileName) { _log('[check semantics]', fileName); promise = checkSemanticsSoon(fileName).then(diagnostics => { delete oldErrors[fileName!]; semanticCheckInfo.set(fileName!, diagnostics.length); if (diagnostics.length > 0) { diagnostics.forEach(d => onError(d)); newErrors[fileName!] = diagnostics; } }); } } // (4th) check dependents else if (filesWithChangedSignature.length) { while (filesWithChangedSignature.length) { const fileName = filesWithChangedSignature.pop()!; if (!isExternalModule(service.getProgram()!.getSourceFile(fileName)!)) { _log('[check semantics*]', fileName + ' is an internal module and it has changed shape -> check whatever hasn\'t been checked yet'); toBeCheckedSemantically.push(...host.getScriptFileNames()); filesWithChangedSignature.length = 0; dependentFiles.length = 0; break; } host.collectDependents(fileName, dependentFiles); } } // (5th) dependents contd else if (dependentFiles.length) { let fileName = dependentFiles.pop(); while (fileName && seenAsDependentFile.has(fileName)) { fileName = dependentFiles.pop(); } if (fileName) { seenAsDependentFile.add(fileName); const value = semanticCheckInfo.get(fileName); if (value === 0) { // already validated successfully -> look at dependents next host.collectDependents(fileName, dependentFiles); } else if (typeof value === 'undefined') { // first validate -> look at dependents next dependentFiles.push(fileName); toBeCheckedSemantically.push(fileName); } } } // (last) done else { resolve(); return; } if (!promise) { promise = Promise.resolve(); } promise.then(function () { // change to change process.nextTick(workOnNext); }).catch(err => { console.error(err); }); } workOnNext(); }).then(() => { // store the build versions to not rebuilt the next time newLastBuildVersion.forEach((value, key) => { lastBuildVersion[key] = value; }); // print old errors and keep them utils.collections.forEach(oldErrors, entry => { entry.value.forEach(diag => onError(diag)); newErrors[entry.key] = entry.value; }); oldErrors = newErrors; // print stats const headNow = process.memoryUsage().heapUsed; const MB = 1024 * 1024; _log( '[tsb]', `time: ${colors.yellow((Date.now() - t1) + 'ms')} + \nmem: ${colors.cyan(Math.ceil(headNow / MB) + 'MB')} ${colors.bgCyan('delta: ' + Math.ceil((headNow - headUsed) / MB))}` ); headUsed = headNow; }); } return { file, build, languageService: service }; } class ScriptSnapshot implements ts.IScriptSnapshot { private readonly _text: string; private readonly _mtime: Date; constructor(text: string, mtime: Date) { this._text = text; this._mtime = mtime; } getVersion(): string { return this._mtime.toUTCString(); } getText(start: number, end: number): string { return this._text.substring(start, end); } getLength(): number { return this._text.length; } getChangeRange(_oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange | undefined { return undefined; } } class VinylScriptSnapshot extends ScriptSnapshot { private readonly _base: string; readonly sourceMap?: RawSourceMap; constructor(file: Vinyl & { sourceMap?: RawSourceMap }) { super(file.contents!.toString(), file.stat!.mtime); this._base = file.base; this.sourceMap = file.sourceMap; } getBase(): string { return this._base; } } class LanguageServiceHost implements ts.LanguageServiceHost { private readonly _snapshots: { [path: string]: ScriptSnapshot }; private readonly _filesInProject: Set<string>; private readonly _filesAdded: Set<string>; private readonly _dependencies: utils.graph.Graph<string>; private readonly _dependenciesRecomputeList: string[]; private readonly _fileNameToDeclaredModule: { [path: string]: string[] }; private _projectVersion: number; constructor( private readonly _cmdLine: ts.ParsedCommandLine, private readonly _projectPath: string, private readonly _log: (topic: string, message: string) => void ) { this._snapshots = Object.create(null); this._filesInProject = new Set(_cmdLine.fileNames); this._filesAdded = new Set(); this._dependencies = new utils.graph.Graph<string>(s => s); this._dependenciesRecomputeList = []; this._fileNameToDeclaredModule = Object.create(null); this._projectVersion = 1; } log(_s: string): void { // console.log(s); } trace(_s: string): void { // console.log(s); } error(s: string): void { console.error(s); } getCompilationSettings(): ts.CompilerOptions { return this._cmdLine.options; } getProjectVersion(): string { return String(this._projectVersion); } getScriptFileNames(): string[] { const res = Object.keys(this._snapshots).filter(path => this._filesInProject.has(path) || this._filesAdded.has(path)); return res; } getScriptVersion(filename: string): string { filename = normalize(filename); const result = this._snapshots[filename]; if (result) { return result.getVersion(); } return 'UNKNWON_FILE_' + Math.random().toString(16).slice(2); } getScriptSnapshot(filename: string, resolve: boolean = true): ScriptSnapshot { filename = normalize(filename); let result = this._snapshots[filename]; if (!result && resolve) { try { result = new VinylScriptSnapshot(new Vinyl(<any>{ path: filename, contents: fs.readFileSync(filename), base: this.getCompilationSettings().outDir, stat: fs.statSync(filename) })); this.addScriptSnapshot(filename, result); } catch (e) { // ignore } } return result; } private static _declareModule = /declare\s+module\s+('|")(.+)\1/g; addScriptSnapshot(filename: string, snapshot: ScriptSnapshot): ScriptSnapshot { this._projectVersion++; filename = normalize(filename); const old = this._snapshots[filename]; if (!old && !this._filesInProject.has(filename) && !filename.endsWith('.d.ts')) { // ^^^^^^^^^^^^^^^^^^^^^^^^^^ // not very proper! this._filesAdded.add(filename); } if (!old || old.getVersion() !== snapshot.getVersion()) { this._dependenciesRecomputeList.push(filename); const node = this._dependencies.lookup(filename); if (node) { node.outgoing = Object.create(null); } // (cheap) check for declare module LanguageServiceHost._declareModule.lastIndex = 0; let match: RegExpExecArray | null | undefined; while ((match = LanguageServiceHost._declareModule.exec(snapshot.getText(0, snapshot.getLength())))) { let declaredModules = this._fileNameToDeclaredModule[filename]; if (!declaredModules) { this._fileNameToDeclaredModule[filename] = declaredModules = []; } declaredModules.push(match[2]); } } this._snapshots[filename] = snapshot; return old; } removeScriptSnapshot(filename: string): boolean { this._filesInProject.delete(filename); this._filesAdded.delete(filename); this._projectVersion++; filename = normalize(filename); delete this._fileNameToDeclaredModule[filename]; return delete this._snapshots[filename]; } getCurrentDirectory(): string { return path.dirname(this._projectPath); } getDefaultLibFileName(options: ts.CompilerOptions): string { return ts.getDefaultLibFilePath(options); } readonly directoryExists = ts.sys.directoryExists; readonly getDirectories = ts.sys.getDirectories; readonly fileExists = ts.sys.fileExists; readonly readFile = ts.sys.readFile; readonly readDirectory = ts.sys.readDirectory; // ---- dependency management collectDependents(filename: string, target: string[]): void { while (this._dependenciesRecomputeList.length) { this._processFile(this._dependenciesRecomputeList.pop()!); } filename = normalize(filename); const node = this._dependencies.lookup(filename); if (node) { utils.collections.forEach(node.incoming, entry => target.push(entry.key)); } } _processFile(filename: string): void { if (filename.match(/.*\.d\.ts$/)) { return; } filename = normalize(filename); const snapshot = this.getScriptSnapshot(filename); if (!snapshot) { this._log('processFile', `Missing snapshot for: ${filename}`); return; } const info = ts.preProcessFile(snapshot.getText(0, snapshot.getLength()), true); // (1) ///-references info.referencedFiles.forEach(ref => { const resolvedPath = path.resolve(path.dirname(filename), ref.fileName); const normalizedPath = normalize(resolvedPath); this._dependencies.inertEdge(filename, normalizedPath); }); // (2) import-require statements info.importedFiles.forEach(ref => { const stopDirname = normalize(this.getCurrentDirectory()); let dirname = filename; let found = false; while (!found && dirname.indexOf(stopDirname) === 0) { dirname = path.dirname(dirname); const resolvedPath = path.resolve(dirname, ref.fileName); const normalizedPath = normalize(resolvedPath); if (this.getScriptSnapshot(normalizedPath + '.ts')) { this._dependencies.inertEdge(filename, normalizedPath + '.ts'); found = true; } else if (this.getScriptSnapshot(normalizedPath + '.d.ts')) { this._dependencies.inertEdge(filename, normalizedPath + '.d.ts'); found = true; } } if (!found) { for (const key in this._fileNameToDeclaredModule) { if (this._fileNameToDeclaredModule[key] && ~this._fileNameToDeclaredModule[key].indexOf(ref.fileName)) { this._dependencies.inertEdge(filename, key); } } } }); } }
build/lib/tsb/builder.ts
1
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.9986745119094849, 0.09916946291923523, 0.0001622616546228528, 0.00019888310634996742, 0.28882306814193726 ]
{ "id": 2, "code_window": [ "\t\t\t\t\tif (/\\.d\\.ts$/.test(fileName)) {\n", "\t\t\t\t\t\t// if it's already a d.ts file just emit it signature\n", "\t\t\t\t\t\tconst snapshot = host.getScriptSnapshot(fileName);\n", "\t\t\t\t\t\tconst signature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t.update(snapshot.getText(0, snapshot.getLength()))\n", "\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\treturn resolve({\n", "\t\t\t\t\t\t\tfileName,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\tconst signature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { TaskDefinition, Task, TaskGroup, WorkspaceFolder, RelativePattern, ShellExecution, Uri, workspace, TaskProvider, TextDocument, tasks, TaskScope, QuickPickItem, window, Position, ExtensionContext, env, ShellQuotedString, ShellQuoting, commands, Location, CancellationTokenSource, l10n } from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; import * as minimatch from 'minimatch'; import { Utils } from 'vscode-uri'; import { findPreferredPM } from './preferred-pm'; import { readScripts } from './readScripts'; const excludeRegex = new RegExp('^(node_modules|.vscode-test)$', 'i'); export interface INpmTaskDefinition extends TaskDefinition { script: string; path?: string; } export interface IFolderTaskItem extends QuickPickItem { label: string; task: Task; } type AutoDetect = 'on' | 'off'; let cachedTasks: ITaskWithLocation[] | undefined = undefined; export const INSTALL_SCRIPT = 'install'; export interface ITaskLocation { document: Uri; line: Position; } export interface ITaskWithLocation { task: Task; location?: Location; } export class NpmTaskProvider implements TaskProvider { constructor(private context: ExtensionContext) { } get tasksWithLocation(): Promise<ITaskWithLocation[]> { return provideNpmScripts(this.context, false); } public async provideTasks() { const tasks = await provideNpmScripts(this.context, true); return tasks.map(task => task.task); } public async resolveTask(_task: Task): Promise<Task | undefined> { const npmTask = (<any>_task.definition).script; if (npmTask) { const kind: INpmTaskDefinition = (<any>_task.definition); let packageJsonUri: Uri; if (_task.scope === undefined || _task.scope === TaskScope.Global || _task.scope === TaskScope.Workspace) { // scope is required to be a WorkspaceFolder for resolveTask return undefined; } if (kind.path) { packageJsonUri = _task.scope.uri.with({ path: _task.scope.uri.path + '/' + kind.path + `${kind.path.endsWith('/') ? '' : '/'}` + 'package.json' }); } else { packageJsonUri = _task.scope.uri.with({ path: _task.scope.uri.path + '/package.json' }); } const cmd = [kind.script]; if (kind.script !== INSTALL_SCRIPT) { cmd.unshift('run'); } return createTask(await getPackageManager(this.context, _task.scope.uri), kind, cmd, _task.scope, packageJsonUri); } return undefined; } } export function invalidateTasksCache() { cachedTasks = undefined; } const buildNames: string[] = ['build', 'compile', 'watch']; function isBuildTask(name: string): boolean { for (const buildName of buildNames) { if (name.indexOf(buildName) !== -1) { return true; } } return false; } const testNames: string[] = ['test']; function isTestTask(name: string): boolean { for (const testName of testNames) { if (name === testName) { return true; } } return false; } function isPrePostScript(name: string): boolean { const prePostScripts: Set<string> = new Set([ 'preuninstall', 'postuninstall', 'prepack', 'postpack', 'preinstall', 'postinstall', 'prepack', 'postpack', 'prepublish', 'postpublish', 'preversion', 'postversion', 'prestop', 'poststop', 'prerestart', 'postrestart', 'preshrinkwrap', 'postshrinkwrap', 'pretest', 'postest', 'prepublishOnly' ]); const prepost = ['pre' + name, 'post' + name]; for (const knownScript of prePostScripts) { if (knownScript === prepost[0] || knownScript === prepost[1]) { return true; } } return false; } export function isWorkspaceFolder(value: any): value is WorkspaceFolder { return value && typeof value !== 'number'; } export async function getPackageManager(extensionContext: ExtensionContext, folder: Uri, showWarning: boolean = true): Promise<string> { let packageManagerName = workspace.getConfiguration('npm', folder).get<string>('packageManager', 'npm'); if (packageManagerName === 'auto') { const { name, multipleLockFilesDetected: multiplePMDetected } = await findPreferredPM(folder.fsPath); packageManagerName = name; const neverShowWarning = 'npm.multiplePMWarning.neverShow'; if (showWarning && multiplePMDetected && !extensionContext.globalState.get<boolean>(neverShowWarning)) { const multiplePMWarning = l10n.t('Using {0} as the preferred package manager. Found multiple lockfiles for {1}. To resolve this issue, delete the lockfiles that don\'t match your preferred package manager or change the setting "npm.packageManager" to a value other than "auto".', packageManagerName, folder.fsPath); const neverShowAgain = l10n.t("Do not show again"); const learnMore = l10n.t("Learn more"); window.showInformationMessage(multiplePMWarning, learnMore, neverShowAgain).then(result => { switch (result) { case neverShowAgain: extensionContext.globalState.update(neverShowWarning, true); break; case learnMore: env.openExternal(Uri.parse('https://docs.npmjs.com/cli/v9/configuring-npm/package-lock-json')); } }); } } return packageManagerName; } export async function hasNpmScripts(): Promise<boolean> { const folders = workspace.workspaceFolders; if (!folders) { return false; } try { for (const folder of folders) { if (isAutoDetectionEnabled(folder) && !excludeRegex.test(Utils.basename(folder.uri))) { const relativePattern = new RelativePattern(folder, '**/package.json'); const paths = await workspace.findFiles(relativePattern, '**/node_modules/**'); if (paths.length > 0) { return true; } } } return false; } catch (error) { return Promise.reject(error); } } async function detectNpmScripts(context: ExtensionContext, showWarning: boolean): Promise<ITaskWithLocation[]> { const emptyTasks: ITaskWithLocation[] = []; const allTasks: ITaskWithLocation[] = []; const visitedPackageJsonFiles: Set<string> = new Set(); const folders = workspace.workspaceFolders; if (!folders) { return emptyTasks; } try { for (const folder of folders) { if (isAutoDetectionEnabled(folder) && !excludeRegex.test(Utils.basename(folder.uri))) { const relativePattern = new RelativePattern(folder, '**/package.json'); const paths = await workspace.findFiles(relativePattern, '**/{node_modules,.vscode-test}/**'); for (const path of paths) { if (!isExcluded(folder, path) && !visitedPackageJsonFiles.has(path.fsPath)) { const tasks = await provideNpmScriptsForFolder(context, path, showWarning); visitedPackageJsonFiles.add(path.fsPath); allTasks.push(...tasks); } } } } return allTasks; } catch (error) { return Promise.reject(error); } } export async function detectNpmScriptsForFolder(context: ExtensionContext, folder: Uri): Promise<IFolderTaskItem[]> { const folderTasks: IFolderTaskItem[] = []; try { if (excludeRegex.test(Utils.basename(folder))) { return folderTasks; } const relativePattern = new RelativePattern(folder.fsPath, '**/package.json'); const paths = await workspace.findFiles(relativePattern, '**/node_modules/**'); const visitedPackageJsonFiles: Set<string> = new Set(); for (const path of paths) { if (!visitedPackageJsonFiles.has(path.fsPath)) { const tasks = await provideNpmScriptsForFolder(context, path, true); visitedPackageJsonFiles.add(path.fsPath); folderTasks.push(...tasks.map(t => ({ label: t.task.name, task: t.task }))); } } return folderTasks; } catch (error) { return Promise.reject(error); } } export async function provideNpmScripts(context: ExtensionContext, showWarning: boolean): Promise<ITaskWithLocation[]> { if (!cachedTasks) { cachedTasks = await detectNpmScripts(context, showWarning); } return cachedTasks; } export function isAutoDetectionEnabled(folder?: WorkspaceFolder): boolean { return workspace.getConfiguration('npm', folder?.uri).get<AutoDetect>('autoDetect') === 'on'; } function isExcluded(folder: WorkspaceFolder, packageJsonUri: Uri) { function testForExclusionPattern(path: string, pattern: string): boolean { return minimatch(path, pattern, { dot: true }); } const exclude = workspace.getConfiguration('npm', folder.uri).get<string | string[]>('exclude'); const packageJsonFolder = path.dirname(packageJsonUri.fsPath); if (exclude) { if (Array.isArray(exclude)) { for (const pattern of exclude) { if (testForExclusionPattern(packageJsonFolder, pattern)) { return true; } } } else if (testForExclusionPattern(packageJsonFolder, exclude)) { return true; } } return false; } function isDebugScript(script: string): boolean { const match = script.match(/--(inspect|debug)(-brk)?(=((\[[0-9a-fA-F:]*\]|[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+|[a-zA-Z0-9\.]*):)?(\d+))?/); return match !== null; } async function provideNpmScriptsForFolder(context: ExtensionContext, packageJsonUri: Uri, showWarning: boolean): Promise<ITaskWithLocation[]> { const emptyTasks: ITaskWithLocation[] = []; const folder = workspace.getWorkspaceFolder(packageJsonUri); if (!folder) { return emptyTasks; } const scripts = await getScripts(packageJsonUri); if (!scripts) { return emptyTasks; } const result: ITaskWithLocation[] = []; const packageManager = await getPackageManager(context, folder.uri, showWarning); for (const { name, value, nameRange } of scripts.scripts) { const task = await createTask(packageManager, name, ['run', name], folder!, packageJsonUri, value, undefined); result.push({ task, location: new Location(packageJsonUri, nameRange) }); } if (!workspace.getConfiguration('npm', folder).get<string[]>('scriptExplorerExclude', []).find(e => e.includes(INSTALL_SCRIPT))) { result.push({ task: await createTask(packageManager, INSTALL_SCRIPT, [INSTALL_SCRIPT], folder, packageJsonUri, 'install dependencies from package', []) }); } return result; } export function getTaskName(script: string, relativePath: string | undefined) { if (relativePath && relativePath.length) { return `${script} - ${relativePath.substring(0, relativePath.length - 1)}`; } return script; } export async function createTask(packageManager: string, script: INpmTaskDefinition | string, cmd: string[], folder: WorkspaceFolder, packageJsonUri: Uri, scriptValue?: string, matcher?: any): Promise<Task> { let kind: INpmTaskDefinition; if (typeof script === 'string') { kind = { type: 'npm', script: script }; } else { kind = script; } function getCommandLine(cmd: string[]): (string | ShellQuotedString)[] { const result: (string | ShellQuotedString)[] = new Array(cmd.length); for (let i = 0; i < cmd.length; i++) { if (/\s/.test(cmd[i])) { result[i] = { value: cmd[i], quoting: cmd[i].includes('--') ? ShellQuoting.Weak : ShellQuoting.Strong }; } else { result[i] = cmd[i]; } } if (workspace.getConfiguration('npm', folder.uri).get<boolean>('runSilent')) { result.unshift('--silent'); } return result; } function getRelativePath(packageJsonUri: Uri): string { const rootUri = folder.uri; const absolutePath = packageJsonUri.path.substring(0, packageJsonUri.path.length - 'package.json'.length); return absolutePath.substring(rootUri.path.length + 1); } const relativePackageJson = getRelativePath(packageJsonUri); if (relativePackageJson.length && !kind.path) { kind.path = relativePackageJson.substring(0, relativePackageJson.length - 1); } const taskName = getTaskName(kind.script, relativePackageJson); const cwd = path.dirname(packageJsonUri.fsPath); const task = new Task(kind, folder, taskName, 'npm', new ShellExecution(packageManager, getCommandLine(cmd), { cwd: cwd }), matcher); task.detail = scriptValue; const lowerCaseTaskName = kind.script.toLowerCase(); if (isBuildTask(lowerCaseTaskName)) { task.group = TaskGroup.Build; } else if (isTestTask(lowerCaseTaskName)) { task.group = TaskGroup.Test; } else if (isPrePostScript(lowerCaseTaskName)) { task.group = TaskGroup.Clean; // hack: use Clean group to tag pre/post scripts } else if (scriptValue && isDebugScript(scriptValue)) { // todo@connor4312: all scripts are now debuggable, what is a 'debug script'? task.group = TaskGroup.Rebuild; // hack: use Rebuild group to tag debug scripts } return task; } export function getPackageJsonUriFromTask(task: Task): Uri | null { if (isWorkspaceFolder(task.scope)) { if (task.definition.path) { return Uri.file(path.join(task.scope.uri.fsPath, task.definition.path, 'package.json')); } else { return Uri.file(path.join(task.scope.uri.fsPath, 'package.json')); } } return null; } export async function hasPackageJson(): Promise<boolean> { const token = new CancellationTokenSource(); // Search for files for max 1 second. const timeout = setTimeout(() => token.cancel(), 1000); const files = await workspace.findFiles('**/package.json', undefined, 1, token.token); clearTimeout(timeout); return files.length > 0 || await hasRootPackageJson(); } async function hasRootPackageJson(): Promise<boolean> { const folders = workspace.workspaceFolders; if (!folders) { return false; } for (const folder of folders) { if (folder.uri.scheme === 'file') { const packageJson = path.join(folder.uri.fsPath, 'package.json'); if (await exists(packageJson)) { return true; } } } return false; } async function exists(file: string): Promise<boolean> { return new Promise<boolean>((resolve, _reject) => { fs.exists(file, (value) => { resolve(value); }); }); } export async function runScript(context: ExtensionContext, script: string, document: TextDocument) { const uri = document.uri; const folder = workspace.getWorkspaceFolder(uri); if (folder) { const task = await createTask(await getPackageManager(context, folder.uri), script, ['run', script], folder, uri); tasks.executeTask(task); } } export async function startDebugging(context: ExtensionContext, scriptName: string, cwd: string, folder: WorkspaceFolder) { commands.executeCommand( 'extension.js-debug.createDebuggerTerminal', `${await getPackageManager(context, folder.uri)} run ${scriptName}`, folder, { cwd }, ); } export type StringMap = { [s: string]: string }; export function findScriptAtPosition(document: TextDocument, buffer: string, position: Position): string | undefined { const read = readScripts(document, buffer); if (!read) { return undefined; } for (const script of read.scripts) { if (script.nameRange.start.isBeforeOrEqual(position) && script.valueRange.end.isAfterOrEqual(position)) { return script.name; } } return undefined; } export async function getScripts(packageJsonUri: Uri) { if (packageJsonUri.scheme !== 'file') { return undefined; } const packageJson = packageJsonUri.fsPath; if (!await exists(packageJson)) { return undefined; } try { const document: TextDocument = await workspace.openTextDocument(packageJsonUri); return readScripts(document); } catch (e) { const localizedParseError = l10n.t("Npm task detection: failed to parse the file {0}", packageJsonUri.fsPath); throw new Error(localizedParseError); } }
extensions/npm/src/tasks.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.0008850509766489267, 0.00018590324907563627, 0.00016290065832436085, 0.0001714389945846051, 0.00010426275548525155 ]
{ "id": 2, "code_window": [ "\t\t\t\t\tif (/\\.d\\.ts$/.test(fileName)) {\n", "\t\t\t\t\t\t// if it's already a d.ts file just emit it signature\n", "\t\t\t\t\t\tconst snapshot = host.getScriptSnapshot(fileName);\n", "\t\t\t\t\t\tconst signature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t.update(snapshot.getText(0, snapshot.getLength()))\n", "\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\treturn resolve({\n", "\t\t\t\t\t\t\tfileName,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\tconst signature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { addDisposableListener, getActiveDocument } from 'vs/base/browser/dom'; import { coalesce } from 'vs/base/common/arrays'; import { CancelablePromise, createCancelablePromise, raceCancellation } from 'vs/base/common/async'; import { CancellationToken } from 'vs/base/common/cancellation'; import { UriList, VSDataTransfer, createStringDataTransferItem, matchesMimeType } from 'vs/base/common/dataTransfer'; import { Disposable } from 'vs/base/common/lifecycle'; import { Mimes } from 'vs/base/common/mime'; import * as platform from 'vs/base/common/platform'; import { generateUuid } from 'vs/base/common/uuid'; import { ClipboardEventUtils } from 'vs/editor/browser/controller/textAreaInput'; import { toExternalVSDataTransfer, toVSDataTransfer } from 'vs/editor/browser/dnd'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { IRange, Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { Handler, IEditorContribution, PastePayload } from 'vs/editor/common/editorCommon'; import { DocumentPasteContext, DocumentPasteEdit, DocumentPasteEditProvider } from 'vs/editor/common/languages'; import { ITextModel } from 'vs/editor/common/model'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { createCombinedWorkspaceEdit, sortEditsByYieldTo } from 'vs/editor/contrib/dropOrPasteInto/browser/edit'; import { CodeEditorStateFlag, EditorStateCancellationTokenSource } from 'vs/editor/contrib/editorState/browser/editorState'; import { InlineProgressManager } from 'vs/editor/contrib/inlineProgress/browser/inlineProgress'; import { localize } from 'vs/nls'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IProgressService, ProgressLocation } from 'vs/platform/progress/common/progress'; import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { PostEditWidgetManager } from './postEditWidget'; import { MessageController } from 'vs/editor/contrib/message/browser/messageController'; export const changePasteTypeCommandId = 'editor.changePasteType'; export const pasteWidgetVisibleCtx = new RawContextKey<boolean>('pasteWidgetVisible', false, localize('pasteWidgetVisible', "Whether the paste widget is showing")); const vscodeClipboardMime = 'application/vnd.code.copyMetadata'; interface CopyMetadata { readonly id?: string; readonly providerCopyMimeTypes?: readonly string[]; readonly defaultPastePayload: Omit<PastePayload, 'text'>; } export class CopyPasteController extends Disposable implements IEditorContribution { public static readonly ID = 'editor.contrib.copyPasteActionController'; public static get(editor: ICodeEditor): CopyPasteController | null { return editor.getContribution<CopyPasteController>(CopyPasteController.ID); } private readonly _editor: ICodeEditor; private _currentCopyOperation?: { readonly handle: string; readonly dataTransferPromise: CancelablePromise<VSDataTransfer>; }; private _currentPasteOperation?: CancelablePromise<void>; private _pasteAsActionContext?: { readonly preferredId: string | undefined }; private readonly _pasteProgressManager: InlineProgressManager; private readonly _postPasteWidgetManager: PostEditWidgetManager; constructor( editor: ICodeEditor, @IInstantiationService instantiationService: IInstantiationService, @IBulkEditService private readonly _bulkEditService: IBulkEditService, @IClipboardService private readonly _clipboardService: IClipboardService, @ILanguageFeaturesService private readonly _languageFeaturesService: ILanguageFeaturesService, @IQuickInputService private readonly _quickInputService: IQuickInputService, @IProgressService private readonly _progressService: IProgressService, ) { super(); this._editor = editor; const container = editor.getContainerDomNode(); this._register(addDisposableListener(container, 'copy', e => this.handleCopy(e))); this._register(addDisposableListener(container, 'cut', e => this.handleCopy(e))); this._register(addDisposableListener(container, 'paste', e => this.handlePaste(e), true)); this._pasteProgressManager = this._register(new InlineProgressManager('pasteIntoEditor', editor, instantiationService)); this._postPasteWidgetManager = this._register(instantiationService.createInstance(PostEditWidgetManager, 'pasteIntoEditor', editor, pasteWidgetVisibleCtx, { id: changePasteTypeCommandId, label: localize('postPasteWidgetTitle', "Show paste options...") })); } public changePasteType() { this._postPasteWidgetManager.tryShowSelector(); } public pasteAs(preferredId?: string) { this._editor.focus(); try { this._pasteAsActionContext = { preferredId }; getActiveDocument().execCommand('paste'); } finally { this._pasteAsActionContext = undefined; } } public clearWidgets() { this._postPasteWidgetManager.clear(); } private isPasteAsEnabled(): boolean { return this._editor.getOption(EditorOption.pasteAs).enabled && !this._editor.getOption(EditorOption.readOnly); } public async finishedPaste(): Promise<void> { await this._currentPasteOperation; } private handleCopy(e: ClipboardEvent) { if (!this._editor.hasTextFocus()) { return; } if (platform.isWeb) { // Explicitly clear the web resources clipboard. // This is needed because on web, the browser clipboard is faked out using an in-memory store. // This means the resources clipboard is not properly updated when copying from the editor. this._clipboardService.writeResources([]); } if (!e.clipboardData || !this.isPasteAsEnabled()) { return; } const model = this._editor.getModel(); const selections = this._editor.getSelections(); if (!model || !selections?.length) { return; } const enableEmptySelectionClipboard = this._editor.getOption(EditorOption.emptySelectionClipboard); let ranges: readonly IRange[] = selections; const wasFromEmptySelection = selections.length === 1 && selections[0].isEmpty(); if (wasFromEmptySelection) { if (!enableEmptySelectionClipboard) { return; } ranges = [new Range(ranges[0].startLineNumber, 1, ranges[0].startLineNumber, 1 + model.getLineLength(ranges[0].startLineNumber))]; } const toCopy = this._editor._getViewModel()?.getPlainTextToCopy(selections, enableEmptySelectionClipboard, platform.isWindows); const multicursorText = Array.isArray(toCopy) ? toCopy : null; const defaultPastePayload = { multicursorText, pasteOnNewLine: wasFromEmptySelection, mode: null }; const providers = this._languageFeaturesService.documentPasteEditProvider .ordered(model) .filter(x => !!x.prepareDocumentPaste); if (!providers.length) { this.setCopyMetadata(e.clipboardData, { defaultPastePayload }); return; } const dataTransfer = toVSDataTransfer(e.clipboardData); const providerCopyMimeTypes = providers.flatMap(x => x.copyMimeTypes ?? []); // Save off a handle pointing to data that VS Code maintains. const handle = generateUuid(); this.setCopyMetadata(e.clipboardData, { id: handle, providerCopyMimeTypes, defaultPastePayload }); const promise = createCancelablePromise(async token => { const results = coalesce(await Promise.all(providers.map(async provider => { try { return await provider.prepareDocumentPaste!(model, ranges, dataTransfer, token); } catch (err) { console.error(err); return undefined; } }))); // Values from higher priority providers should overwrite values from lower priority ones. // Reverse the array to so that the calls to `replace` below will do this results.reverse(); for (const result of results) { for (const [mime, value] of result) { dataTransfer.replace(mime, value); } } return dataTransfer; }); this._currentCopyOperation?.dataTransferPromise.cancel(); this._currentCopyOperation = { handle: handle, dataTransferPromise: promise }; } private async handlePaste(e: ClipboardEvent) { if (!e.clipboardData || !this._editor.hasTextFocus()) { return; } MessageController.get(this._editor)?.closeMessage(); this._currentPasteOperation?.cancel(); this._currentPasteOperation = undefined; const model = this._editor.getModel(); const selections = this._editor.getSelections(); if (!selections?.length || !model) { return; } if ( !this.isPasteAsEnabled() && !this._pasteAsActionContext // Still enable if paste as was explicitly requested ) { return; } const metadata = this.fetchCopyMetadata(e); const dataTransfer = toExternalVSDataTransfer(e.clipboardData); dataTransfer.delete(vscodeClipboardMime); const allPotentialMimeTypes = [ ...e.clipboardData.types, ...metadata?.providerCopyMimeTypes ?? [], // TODO: always adds `uri-list` because this get set if there are resources in the system clipboard. // However we can only check the system clipboard async. For this early check, just add it in. // We filter providers again once we have the final dataTransfer we will use. Mimes.uriList, ]; const allProviders = this._languageFeaturesService.documentPasteEditProvider .ordered(model) .filter(provider => { if (this._pasteAsActionContext?.preferredId) { if (this._pasteAsActionContext.preferredId !== provider.id) { return false; } } return provider.pasteMimeTypes?.some(type => matchesMimeType(type, allPotentialMimeTypes)); }); if (!allProviders.length) { if (this._pasteAsActionContext?.preferredId) { this.showPasteAsNoEditMessage(selections, this._pasteAsActionContext?.preferredId); } return; } // Prevent the editor's default paste handler from running. // Note that after this point, we are fully responsible for handling paste. // If we can't provider a paste for any reason, we need to explicitly delegate pasting back to the editor. e.preventDefault(); e.stopImmediatePropagation(); if (this._pasteAsActionContext) { this.showPasteAsPick(this._pasteAsActionContext.preferredId, allProviders, selections, dataTransfer, metadata, { trigger: 'explicit', only: this._pasteAsActionContext.preferredId }); } else { this.doPasteInline(allProviders, selections, dataTransfer, metadata, { trigger: 'implicit' }); } } private showPasteAsNoEditMessage(selections: readonly Selection[], editId: string) { MessageController.get(this._editor)?.showMessage(localize('pasteAsError', "No paste edits for '{0}' found", editId), selections[0].getStartPosition()); } private doPasteInline(allProviders: readonly DocumentPasteEditProvider[], selections: readonly Selection[], dataTransfer: VSDataTransfer, metadata: CopyMetadata | undefined, context: DocumentPasteContext): void { const p = createCancelablePromise(async (token) => { const editor = this._editor; if (!editor.hasModel()) { return; } const model = editor.getModel(); const tokenSource = new EditorStateCancellationTokenSource(editor, CodeEditorStateFlag.Value | CodeEditorStateFlag.Selection, undefined, token); try { await this.mergeInDataFromCopy(dataTransfer, metadata, tokenSource.token); if (tokenSource.token.isCancellationRequested) { return; } // Filter out any providers the don't match the full data transfer we will send them. const supportedProviders = allProviders.filter(provider => isSupportedPasteProvider(provider, dataTransfer)); if (!supportedProviders.length || (supportedProviders.length === 1 && supportedProviders[0].id === 'text') // Only our default text provider is active ) { await this.applyDefaultPasteHandler(dataTransfer, metadata, tokenSource.token); return; } const providerEdits = await this.getPasteEdits(supportedProviders, dataTransfer, model, selections, context, tokenSource.token); if (tokenSource.token.isCancellationRequested) { return; } // If the only edit returned is a text edit, use the default paste handler if (providerEdits.length === 1 && providerEdits[0].providerId === 'text') { await this.applyDefaultPasteHandler(dataTransfer, metadata, tokenSource.token); return; } if (providerEdits.length) { const canShowWidget = editor.getOption(EditorOption.pasteAs).showPasteSelector === 'afterPaste'; return this._postPasteWidgetManager.applyEditAndShowIfNeeded(selections, { activeEditIndex: 0, allEdits: providerEdits }, canShowWidget, tokenSource.token); } await this.applyDefaultPasteHandler(dataTransfer, metadata, tokenSource.token); } finally { tokenSource.dispose(); if (this._currentPasteOperation === p) { this._currentPasteOperation = undefined; } } }); this._pasteProgressManager.showWhile(selections[0].getEndPosition(), localize('pasteIntoEditorProgress', "Running paste handlers. Click to cancel"), p); this._currentPasteOperation = p; } private showPasteAsPick(preferredId: string | undefined, allProviders: readonly DocumentPasteEditProvider[], selections: readonly Selection[], dataTransfer: VSDataTransfer, metadata: CopyMetadata | undefined, context: DocumentPasteContext): void { const p = createCancelablePromise(async (token) => { const editor = this._editor; if (!editor.hasModel()) { return; } const model = editor.getModel(); const tokenSource = new EditorStateCancellationTokenSource(editor, CodeEditorStateFlag.Value | CodeEditorStateFlag.Selection, undefined, token); try { await this.mergeInDataFromCopy(dataTransfer, metadata, tokenSource.token); if (tokenSource.token.isCancellationRequested) { return; } // Filter out any providers the don't match the full data transfer we will send them. let supportedProviders = allProviders.filter(provider => isSupportedPasteProvider(provider, dataTransfer)); if (preferredId) { // We are looking for a specific edit supportedProviders = supportedProviders.filter(edit => edit.id === preferredId); } const providerEdits = await this.getPasteEdits(supportedProviders, dataTransfer, model, selections, context, tokenSource.token); if (tokenSource.token.isCancellationRequested) { return; } if (!providerEdits.length) { if (context.only) { this.showPasteAsNoEditMessage(selections, context.only); } return; } let pickedEdit: DocumentPasteEdit | undefined; if (preferredId) { pickedEdit = providerEdits.at(0); } else { const selected = await this._quickInputService.pick( providerEdits.map((edit): IQuickPickItem & { edit: DocumentPasteEdit } => ({ label: edit.label, description: edit.providerId, detail: edit.detail, edit, })), { placeHolder: localize('pasteAsPickerPlaceholder', "Select Paste Action"), }); pickedEdit = selected?.edit; } if (!pickedEdit) { return; } const combinedWorkspaceEdit = createCombinedWorkspaceEdit(model.uri, selections, pickedEdit); await this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor }); } finally { tokenSource.dispose(); if (this._currentPasteOperation === p) { this._currentPasteOperation = undefined; } } }); this._progressService.withProgress({ location: ProgressLocation.Window, title: localize('pasteAsProgress', "Running paste handlers"), }, () => p); } private setCopyMetadata(dataTransfer: DataTransfer, metadata: CopyMetadata) { dataTransfer.setData(vscodeClipboardMime, JSON.stringify(metadata)); } private fetchCopyMetadata(e: ClipboardEvent): CopyMetadata | undefined { if (!e.clipboardData) { return; } // Prefer using the clipboard data we saved off const rawMetadata = e.clipboardData.getData(vscodeClipboardMime); if (rawMetadata) { try { return JSON.parse(rawMetadata); } catch { return undefined; } } // Otherwise try to extract the generic text editor metadata const [_, metadata] = ClipboardEventUtils.getTextData(e.clipboardData); if (metadata) { return { defaultPastePayload: { mode: metadata.mode, multicursorText: metadata.multicursorText ?? null, pasteOnNewLine: !!metadata.isFromEmptySelection, }, }; } return undefined; } private async mergeInDataFromCopy(dataTransfer: VSDataTransfer, metadata: CopyMetadata | undefined, token: CancellationToken): Promise<void> { if (metadata?.id && this._currentCopyOperation?.handle === metadata.id) { const toMergeDataTransfer = await this._currentCopyOperation.dataTransferPromise; if (token.isCancellationRequested) { return; } for (const [key, value] of toMergeDataTransfer) { dataTransfer.replace(key, value); } } if (!dataTransfer.has(Mimes.uriList)) { const resources = await this._clipboardService.readResources(); if (token.isCancellationRequested) { return; } if (resources.length) { dataTransfer.append(Mimes.uriList, createStringDataTransferItem(UriList.create(resources))); } } } private async getPasteEdits(providers: readonly DocumentPasteEditProvider[], dataTransfer: VSDataTransfer, model: ITextModel, selections: readonly Selection[], context: DocumentPasteContext, token: CancellationToken): Promise<Array<DocumentPasteEdit & { providerId: string }>> { const results = await raceCancellation( Promise.all(providers.map(async provider => { try { const edit = await provider.provideDocumentPasteEdits?.(model, selections, dataTransfer, context, token); if (edit) { return { ...edit, providerId: provider.id }; } } catch (err) { console.error(err); } return undefined; })), token); const edits = coalesce(results ?? []); return sortEditsByYieldTo(edits); } private async applyDefaultPasteHandler(dataTransfer: VSDataTransfer, metadata: CopyMetadata | undefined, token: CancellationToken) { const textDataTransfer = dataTransfer.get(Mimes.text) ?? dataTransfer.get('text'); if (!textDataTransfer) { return; } const text = await textDataTransfer.asString(); if (token.isCancellationRequested) { return; } const payload: PastePayload = { text, pasteOnNewLine: metadata?.defaultPastePayload.pasteOnNewLine ?? false, multicursorText: metadata?.defaultPastePayload.multicursorText ?? null, mode: null, }; this._editor.trigger('keyboard', Handler.Paste, payload); } } function isSupportedPasteProvider(provider: DocumentPasteEditProvider, dataTransfer: VSDataTransfer): boolean { return Boolean(provider.pasteMimeTypes?.some(type => dataTransfer.matches(type))); }
src/vs/editor/contrib/dropOrPasteInto/browser/copyPasteController.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.00017596589168533683, 0.00017196591943502426, 0.0001671322388574481, 0.00017229253717232496, 0.000001980365595954936 ]
{ "id": 2, "code_window": [ "\t\t\t\t\tif (/\\.d\\.ts$/.test(fileName)) {\n", "\t\t\t\t\t\t// if it's already a d.ts file just emit it signature\n", "\t\t\t\t\t\tconst snapshot = host.getScriptSnapshot(fileName);\n", "\t\t\t\t\t\tconst signature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t.update(snapshot.getText(0, snapshot.getLength()))\n", "\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\treturn resolve({\n", "\t\t\t\t\t\t\tfileName,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\tconst signature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { // https://github.com/microsoft/vscode/issues/135591 @alexr00 // export interface FileDecorationProvider { // provideFileDecoration(uri: Uri, token: CancellationToken): ProviderResult<FileDecoration | FileDecoration1>; // } /** * A file decoration represents metadata that can be rendered with a file. */ export class FileDecoration2 { /** * A very short string that represents this decoration. */ badge?: string | ThemeIcon; /** * A human-readable tooltip for this decoration. */ tooltip?: string; /** * The color of this decoration. */ color?: ThemeColor; /** * A flag expressing that this decoration should be * propagated to its parents. */ propagate?: boolean; /** * Creates a new decoration. * * @param badge A letter that represents the decoration. * @param tooltip The tooltip of the decoration. * @param color The color of the decoration. */ constructor(badge?: string | ThemeIcon, tooltip?: string, color?: ThemeColor); } }
src/vscode-dts/vscode.proposed.codiconDecoration.d.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.00017429653962608427, 0.00016988103743642569, 0.00016305979806929827, 0.00017270373064093292, 0.000004320251719036605 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\tif (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n", "\t\t\t\t\t\t\tcontinue;\n", "\t\t\t\t\t\t}\n", "\n", "\t\t\t\t\t\tif (/\\.d\\.ts$/.test(file.name)) {\n", "\t\t\t\t\t\t\tsignature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t\t.update(file.text)\n", "\t\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\t\tif (!userWantsDeclarations) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tsignature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 136 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.createTypeScriptBuilder = exports.CancellationToken = void 0; const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); const utils = require("./utils"); const colors = require("ansi-colors"); const ts = require("typescript"); const Vinyl = require("vinyl"); const source_map_1 = require("source-map"); var CancellationToken; (function (CancellationToken) { CancellationToken.None = { isCancellationRequested() { return false; } }; })(CancellationToken || (exports.CancellationToken = CancellationToken = {})); function normalize(path) { return path.replace(/\\/g, '/'); } function createTypeScriptBuilder(config, projectFile, cmd) { const _log = config.logFn; const host = new LanguageServiceHost(cmd, projectFile, _log); const service = ts.createLanguageService(host, ts.createDocumentRegistry()); const lastBuildVersion = Object.create(null); const lastDtsHash = Object.create(null); const userWantsDeclarations = cmd.options.declaration; let oldErrors = Object.create(null); let headUsed = process.memoryUsage().heapUsed; let emitSourceMapsInStream = true; // always emit declaraction files host.getCompilationSettings().declaration = true; function file(file) { // support gulp-sourcemaps if (file.sourceMap) { emitSourceMapsInStream = false; } if (!file.contents) { host.removeScriptSnapshot(file.path); } else { host.addScriptSnapshot(file.path, new VinylScriptSnapshot(file)); } } function baseFor(snapshot) { if (snapshot instanceof VinylScriptSnapshot) { return cmd.options.outDir || snapshot.getBase(); } else { return ''; } } function isExternalModule(sourceFile) { return sourceFile.externalModuleIndicator || /declare\s+module\s+('|")(.+)\1/.test(sourceFile.getText()); } function build(out, onError, token = CancellationToken.None) { function checkSyntaxSoon(fileName) { return new Promise(resolve => { process.nextTick(function () { if (!host.getScriptSnapshot(fileName, false)) { resolve([]); // no script, no problems } else { resolve(service.getSyntacticDiagnostics(fileName)); } }); }); } function checkSemanticsSoon(fileName) { return new Promise(resolve => { process.nextTick(function () { if (!host.getScriptSnapshot(fileName, false)) { resolve([]); // no script, no problems } else { resolve(service.getSemanticDiagnostics(fileName)); } }); }); } function emitSoon(fileName) { return new Promise(resolve => { process.nextTick(function () { if (/\.d\.ts$/.test(fileName)) { // if it's already a d.ts file just emit it signature const snapshot = host.getScriptSnapshot(fileName); const signature = crypto.createHash('md5') .update(snapshot.getText(0, snapshot.getLength())) .digest('base64'); return resolve({ fileName, signature, files: [] }); } const output = service.getEmitOutput(fileName); const files = []; let signature; for (const file of output.outputFiles) { if (!emitSourceMapsInStream && /\.js\.map$/.test(file.name)) { continue; } if (/\.d\.ts$/.test(file.name)) { signature = crypto.createHash('md5') .update(file.text) .digest('base64'); if (!userWantsDeclarations) { // don't leak .d.ts files if users don't want them continue; } } const vinyl = new Vinyl({ path: file.name, contents: Buffer.from(file.text), base: !config._emitWithoutBasePath && baseFor(host.getScriptSnapshot(fileName)) || undefined }); if (!emitSourceMapsInStream && /\.js$/.test(file.name)) { const sourcemapFile = output.outputFiles.filter(f => /\.js\.map$/.test(f.name))[0]; if (sourcemapFile) { const extname = path.extname(vinyl.relative); const basename = path.basename(vinyl.relative, extname); const dirname = path.dirname(vinyl.relative); const tsname = (dirname === '.' ? '' : dirname + '/') + basename + '.ts'; let sourceMap = JSON.parse(sourcemapFile.text); sourceMap.sources[0] = tsname.replace(/\\/g, '/'); // check for an "input source" map and combine them // in step 1 we extract all line edit from the input source map, and // in step 2 we apply the line edits to the typescript source map const snapshot = host.getScriptSnapshot(fileName); if (snapshot instanceof VinylScriptSnapshot && snapshot.sourceMap) { const inputSMC = new source_map_1.SourceMapConsumer(snapshot.sourceMap); const tsSMC = new source_map_1.SourceMapConsumer(sourceMap); let didChange = false; const smg = new source_map_1.SourceMapGenerator({ file: sourceMap.file, sourceRoot: sourceMap.sourceRoot }); // step 1 const lineEdits = new Map(); inputSMC.eachMapping(m => { if (m.originalLine === m.generatedLine) { // same line mapping let array = lineEdits.get(m.originalLine); if (!array) { array = []; lineEdits.set(m.originalLine, array); } array.push([m.originalColumn, m.generatedColumn]); } else { // NOT SUPPORTED } }); // step 2 tsSMC.eachMapping(m => { didChange = true; const edits = lineEdits.get(m.originalLine); let originalColumnDelta = 0; if (edits) { for (const [from, to] of edits) { if (to >= m.originalColumn) { break; } originalColumnDelta = from - to; } } smg.addMapping({ source: m.source, name: m.name, generated: { line: m.generatedLine, column: m.generatedColumn }, original: { line: m.originalLine, column: m.originalColumn + originalColumnDelta } }); }); if (didChange) { [tsSMC, inputSMC].forEach((consumer) => { consumer.sources.forEach((sourceFile) => { smg._sources.add(sourceFile); const sourceContent = consumer.sourceContentFor(sourceFile); if (sourceContent !== null) { smg.setSourceContent(sourceFile, sourceContent); } }); }); sourceMap = JSON.parse(smg.toString()); // const filename = '/Users/jrieken/Code/vscode/src2/' + vinyl.relative + '.map'; // fs.promises.mkdir(path.dirname(filename), { recursive: true }).then(async () => { // await fs.promises.writeFile(filename, smg.toString()); // await fs.promises.writeFile('/Users/jrieken/Code/vscode/src2/' + vinyl.relative, vinyl.contents); // }); } } vinyl.sourceMap = sourceMap; } } files.push(vinyl); } resolve({ fileName, signature, files }); }); }); } const newErrors = Object.create(null); const t1 = Date.now(); const toBeEmitted = []; const toBeCheckedSyntactically = []; const toBeCheckedSemantically = []; const filesWithChangedSignature = []; const dependentFiles = []; const newLastBuildVersion = new Map(); for (const fileName of host.getScriptFileNames()) { if (lastBuildVersion[fileName] !== host.getScriptVersion(fileName)) { toBeEmitted.push(fileName); toBeCheckedSyntactically.push(fileName); toBeCheckedSemantically.push(fileName); } } return new Promise(resolve => { const semanticCheckInfo = new Map(); const seenAsDependentFile = new Set(); function workOnNext() { let promise; // let fileName: string; // someone told us to stop this if (token.isCancellationRequested()) { _log('[CANCEL]', '>>This compile run was cancelled<<'); newLastBuildVersion.clear(); resolve(); return; } // (1st) emit code else if (toBeEmitted.length) { const fileName = toBeEmitted.pop(); promise = emitSoon(fileName).then(value => { for (const file of value.files) { _log('[emit code]', file.path); out(file); } // remember when this was build newLastBuildVersion.set(fileName, host.getScriptVersion(fileName)); // remeber the signature if (value.signature && lastDtsHash[fileName] !== value.signature) { lastDtsHash[fileName] = value.signature; filesWithChangedSignature.push(fileName); } }).catch(e => { // can't just skip this or make a result up.. host.error(`ERROR emitting ${fileName}`); host.error(e); }); } // (2nd) check syntax else if (toBeCheckedSyntactically.length) { const fileName = toBeCheckedSyntactically.pop(); _log('[check syntax]', fileName); promise = checkSyntaxSoon(fileName).then(diagnostics => { delete oldErrors[fileName]; if (diagnostics.length > 0) { diagnostics.forEach(d => onError(d)); newErrors[fileName] = diagnostics; // stop the world when there are syntax errors toBeCheckedSyntactically.length = 0; toBeCheckedSemantically.length = 0; filesWithChangedSignature.length = 0; } }); } // (3rd) check semantics else if (toBeCheckedSemantically.length) { let fileName = toBeCheckedSemantically.pop(); while (fileName && semanticCheckInfo.has(fileName)) { fileName = toBeCheckedSemantically.pop(); } if (fileName) { _log('[check semantics]', fileName); promise = checkSemanticsSoon(fileName).then(diagnostics => { delete oldErrors[fileName]; semanticCheckInfo.set(fileName, diagnostics.length); if (diagnostics.length > 0) { diagnostics.forEach(d => onError(d)); newErrors[fileName] = diagnostics; } }); } } // (4th) check dependents else if (filesWithChangedSignature.length) { while (filesWithChangedSignature.length) { const fileName = filesWithChangedSignature.pop(); if (!isExternalModule(service.getProgram().getSourceFile(fileName))) { _log('[check semantics*]', fileName + ' is an internal module and it has changed shape -> check whatever hasn\'t been checked yet'); toBeCheckedSemantically.push(...host.getScriptFileNames()); filesWithChangedSignature.length = 0; dependentFiles.length = 0; break; } host.collectDependents(fileName, dependentFiles); } } // (5th) dependents contd else if (dependentFiles.length) { let fileName = dependentFiles.pop(); while (fileName && seenAsDependentFile.has(fileName)) { fileName = dependentFiles.pop(); } if (fileName) { seenAsDependentFile.add(fileName); const value = semanticCheckInfo.get(fileName); if (value === 0) { // already validated successfully -> look at dependents next host.collectDependents(fileName, dependentFiles); } else if (typeof value === 'undefined') { // first validate -> look at dependents next dependentFiles.push(fileName); toBeCheckedSemantically.push(fileName); } } } // (last) done else { resolve(); return; } if (!promise) { promise = Promise.resolve(); } promise.then(function () { // change to change process.nextTick(workOnNext); }).catch(err => { console.error(err); }); } workOnNext(); }).then(() => { // store the build versions to not rebuilt the next time newLastBuildVersion.forEach((value, key) => { lastBuildVersion[key] = value; }); // print old errors and keep them utils.collections.forEach(oldErrors, entry => { entry.value.forEach(diag => onError(diag)); newErrors[entry.key] = entry.value; }); oldErrors = newErrors; // print stats const headNow = process.memoryUsage().heapUsed; const MB = 1024 * 1024; _log('[tsb]', `time: ${colors.yellow((Date.now() - t1) + 'ms')} + \nmem: ${colors.cyan(Math.ceil(headNow / MB) + 'MB')} ${colors.bgCyan('delta: ' + Math.ceil((headNow - headUsed) / MB))}`); headUsed = headNow; }); } return { file, build, languageService: service }; } exports.createTypeScriptBuilder = createTypeScriptBuilder; class ScriptSnapshot { _text; _mtime; constructor(text, mtime) { this._text = text; this._mtime = mtime; } getVersion() { return this._mtime.toUTCString(); } getText(start, end) { return this._text.substring(start, end); } getLength() { return this._text.length; } getChangeRange(_oldSnapshot) { return undefined; } } class VinylScriptSnapshot extends ScriptSnapshot { _base; sourceMap; constructor(file) { super(file.contents.toString(), file.stat.mtime); this._base = file.base; this.sourceMap = file.sourceMap; } getBase() { return this._base; } } class LanguageServiceHost { _cmdLine; _projectPath; _log; _snapshots; _filesInProject; _filesAdded; _dependencies; _dependenciesRecomputeList; _fileNameToDeclaredModule; _projectVersion; constructor(_cmdLine, _projectPath, _log) { this._cmdLine = _cmdLine; this._projectPath = _projectPath; this._log = _log; this._snapshots = Object.create(null); this._filesInProject = new Set(_cmdLine.fileNames); this._filesAdded = new Set(); this._dependencies = new utils.graph.Graph(s => s); this._dependenciesRecomputeList = []; this._fileNameToDeclaredModule = Object.create(null); this._projectVersion = 1; } log(_s) { // console.log(s); } trace(_s) { // console.log(s); } error(s) { console.error(s); } getCompilationSettings() { return this._cmdLine.options; } getProjectVersion() { return String(this._projectVersion); } getScriptFileNames() { const res = Object.keys(this._snapshots).filter(path => this._filesInProject.has(path) || this._filesAdded.has(path)); return res; } getScriptVersion(filename) { filename = normalize(filename); const result = this._snapshots[filename]; if (result) { return result.getVersion(); } return 'UNKNWON_FILE_' + Math.random().toString(16).slice(2); } getScriptSnapshot(filename, resolve = true) { filename = normalize(filename); let result = this._snapshots[filename]; if (!result && resolve) { try { result = new VinylScriptSnapshot(new Vinyl({ path: filename, contents: fs.readFileSync(filename), base: this.getCompilationSettings().outDir, stat: fs.statSync(filename) })); this.addScriptSnapshot(filename, result); } catch (e) { // ignore } } return result; } static _declareModule = /declare\s+module\s+('|")(.+)\1/g; addScriptSnapshot(filename, snapshot) { this._projectVersion++; filename = normalize(filename); const old = this._snapshots[filename]; if (!old && !this._filesInProject.has(filename) && !filename.endsWith('.d.ts')) { // ^^^^^^^^^^^^^^^^^^^^^^^^^^ // not very proper! this._filesAdded.add(filename); } if (!old || old.getVersion() !== snapshot.getVersion()) { this._dependenciesRecomputeList.push(filename); const node = this._dependencies.lookup(filename); if (node) { node.outgoing = Object.create(null); } // (cheap) check for declare module LanguageServiceHost._declareModule.lastIndex = 0; let match; while ((match = LanguageServiceHost._declareModule.exec(snapshot.getText(0, snapshot.getLength())))) { let declaredModules = this._fileNameToDeclaredModule[filename]; if (!declaredModules) { this._fileNameToDeclaredModule[filename] = declaredModules = []; } declaredModules.push(match[2]); } } this._snapshots[filename] = snapshot; return old; } removeScriptSnapshot(filename) { this._filesInProject.delete(filename); this._filesAdded.delete(filename); this._projectVersion++; filename = normalize(filename); delete this._fileNameToDeclaredModule[filename]; return delete this._snapshots[filename]; } getCurrentDirectory() { return path.dirname(this._projectPath); } getDefaultLibFileName(options) { return ts.getDefaultLibFilePath(options); } directoryExists = ts.sys.directoryExists; getDirectories = ts.sys.getDirectories; fileExists = ts.sys.fileExists; readFile = ts.sys.readFile; readDirectory = ts.sys.readDirectory; // ---- dependency management collectDependents(filename, target) { while (this._dependenciesRecomputeList.length) { this._processFile(this._dependenciesRecomputeList.pop()); } filename = normalize(filename); const node = this._dependencies.lookup(filename); if (node) { utils.collections.forEach(node.incoming, entry => target.push(entry.key)); } } _processFile(filename) { if (filename.match(/.*\.d\.ts$/)) { return; } filename = normalize(filename); const snapshot = this.getScriptSnapshot(filename); if (!snapshot) { this._log('processFile', `Missing snapshot for: ${filename}`); return; } const info = ts.preProcessFile(snapshot.getText(0, snapshot.getLength()), true); // (1) ///-references info.referencedFiles.forEach(ref => { const resolvedPath = path.resolve(path.dirname(filename), ref.fileName); const normalizedPath = normalize(resolvedPath); this._dependencies.inertEdge(filename, normalizedPath); }); // (2) import-require statements info.importedFiles.forEach(ref => { const stopDirname = normalize(this.getCurrentDirectory()); let dirname = filename; let found = false; while (!found && dirname.indexOf(stopDirname) === 0) { dirname = path.dirname(dirname); const resolvedPath = path.resolve(dirname, ref.fileName); const normalizedPath = normalize(resolvedPath); if (this.getScriptSnapshot(normalizedPath + '.ts')) { this._dependencies.inertEdge(filename, normalizedPath + '.ts'); found = true; } else if (this.getScriptSnapshot(normalizedPath + '.d.ts')) { this._dependencies.inertEdge(filename, normalizedPath + '.d.ts'); found = true; } } if (!found) { for (const key in this._fileNameToDeclaredModule) { if (this._fileNameToDeclaredModule[key] && ~this._fileNameToDeclaredModule[key].indexOf(ref.fileName)) { this._dependencies.inertEdge(filename, key); } } } }); } } //# sourceMappingURL=builder.js.map
build/lib/tsb/builder.js
1
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.9907201528549194, 0.08775804191827774, 0.0001586632861290127, 0.000171264837263152, 0.27375712990760803 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\tif (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n", "\t\t\t\t\t\t\tcontinue;\n", "\t\t\t\t\t\t}\n", "\n", "\t\t\t\t\t\tif (/\\.d\\.ts$/.test(file.name)) {\n", "\t\t\t\t\t\t\tsignature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t\t.update(file.text)\n", "\t\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\t\tif (!userWantsDeclarations) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tsignature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { coalesce } from '../../util/arrays'; import { getParentDocumentUri } from '../../util/document'; import { Mime, mediaMimes } from '../../util/mimes'; import { Schemes } from '../../util/schemes'; import { NewFilePathGenerator } from './newFilePathGenerator'; import { createInsertUriListEdit, createUriListSnippet, getSnippetLabel } from './shared'; /** * Provides support for pasting or dropping resources into markdown documents. * * This includes: * * - `text/uri-list` data in the data transfer. * - File object in the data transfer. * - Media data in the data transfer, such as `image/png`. */ class ResourcePasteOrDropProvider implements vscode.DocumentPasteEditProvider, vscode.DocumentDropEditProvider { public static readonly id = 'insertResource'; public static readonly mimeTypes = [ Mime.textUriList, 'files', ...mediaMimes, ]; private readonly _yieldTo = [ { mimeType: 'text/plain' }, { extensionId: 'vscode.ipynb', providerId: 'insertAttachment' }, ]; public async provideDocumentDropEdits( document: vscode.TextDocument, position: vscode.Position, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<vscode.DocumentDropEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('editor.drop.enabled', true); if (!enabled) { return; } const filesEdit = await this._getMediaFilesDropEdit(document, dataTransfer, token); if (filesEdit) { return filesEdit; } if (token.isCancellationRequested) { return; } return this._createEditFromUriListData(document, [new vscode.Range(position, position)], dataTransfer, token); } public async provideDocumentPasteEdits( document: vscode.TextDocument, ranges: readonly vscode.Range[], dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<vscode.DocumentPasteEdit | undefined> { const enabled = vscode.workspace.getConfiguration('markdown', document).get('editor.filePaste.enabled', true); if (!enabled) { return; } const createEdit = await this._getMediaFilesPasteEdit(document, dataTransfer, token); if (createEdit) { return createEdit; } if (token.isCancellationRequested) { return; } return this._createEditFromUriListData(document, ranges, dataTransfer, token); } private async _createEditFromUriListData( document: vscode.TextDocument, ranges: readonly vscode.Range[], dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<vscode.DocumentPasteEdit | undefined> { const uriList = await dataTransfer.get(Mime.textUriList)?.asString(); if (!uriList || token.isCancellationRequested) { return; } const pasteEdit = createInsertUriListEdit(document, ranges, uriList); if (!pasteEdit) { return; } const uriEdit = new vscode.DocumentPasteEdit('', pasteEdit.label); const edit = new vscode.WorkspaceEdit(); edit.set(document.uri, pasteEdit.edits); uriEdit.additionalEdit = edit; uriEdit.yieldTo = this._yieldTo; return uriEdit; } private async _getMediaFilesPasteEdit( document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<vscode.DocumentPasteEdit | undefined> { if (getParentDocumentUri(document.uri).scheme === Schemes.untitled) { return; } const copyFilesIntoWorkspace = vscode.workspace.getConfiguration('markdown', document).get<'mediaFiles' | 'never'>('editor.filePaste.copyIntoWorkspace', 'mediaFiles'); if (copyFilesIntoWorkspace !== 'mediaFiles') { return; } const edit = await this._createEditForMediaFiles(document, dataTransfer, token); if (!edit) { return; } const pasteEdit = new vscode.DocumentPasteEdit(edit.snippet, edit.label); pasteEdit.additionalEdit = edit.additionalEdits; pasteEdit.yieldTo = this._yieldTo; return pasteEdit; } private async _getMediaFilesDropEdit( document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<vscode.DocumentDropEdit | undefined> { if (getParentDocumentUri(document.uri).scheme === Schemes.untitled) { return; } const copyIntoWorkspace = vscode.workspace.getConfiguration('markdown', document).get<'mediaFiles' | 'never'>('editor.drop.copyIntoWorkspace', 'mediaFiles'); if (copyIntoWorkspace !== 'mediaFiles') { return; } const edit = await this._createEditForMediaFiles(document, dataTransfer, token); if (!edit) { return; } const dropEdit = new vscode.DocumentDropEdit(edit.snippet); dropEdit.label = edit.label; dropEdit.additionalEdit = edit.additionalEdits; dropEdit.yieldTo = this._yieldTo; return dropEdit; } /** * Create a new edit for media files in a data transfer. * * This tries copying files outside of the workspace into the workspace. */ private async _createEditForMediaFiles( document: vscode.TextDocument, dataTransfer: vscode.DataTransfer, token: vscode.CancellationToken, ): Promise<{ snippet: vscode.SnippetString; label: string; additionalEdits: vscode.WorkspaceEdit } | undefined> { interface FileEntry { readonly uri: vscode.Uri; readonly newFile?: { readonly contents: vscode.DataTransferFile; readonly overwrite: boolean }; } const pathGenerator = new NewFilePathGenerator(); const fileEntries = coalesce(await Promise.all(Array.from(dataTransfer, async ([mime, item]): Promise<FileEntry | undefined> => { if (!mediaMimes.has(mime)) { return; } const file = item?.asFile(); if (!file) { return; } if (file.uri) { // If the file is already in a workspace, we don't want to create a copy of it const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri); if (workspaceFolder) { return { uri: file.uri }; } } const newFile = await pathGenerator.getNewFilePath(document, file, token); if (!newFile) { return; } return { uri: newFile.uri, newFile: { contents: file, overwrite: newFile.overwrite } }; }))); if (!fileEntries.length) { return; } const workspaceEdit = new vscode.WorkspaceEdit(); for (const entry of fileEntries) { if (entry.newFile) { workspaceEdit.createFile(entry.uri, { contents: entry.newFile.contents, overwrite: entry.newFile.overwrite, }); } } const snippet = createUriListSnippet(document.uri, fileEntries); if (!snippet) { return; } return { snippet: snippet.snippet, label: getSnippetLabel(snippet), additionalEdits: workspaceEdit, }; } } export function registerResourceDropOrPasteSupport(selector: vscode.DocumentSelector): vscode.Disposable { return vscode.Disposable.from( vscode.languages.registerDocumentPasteEditProvider(selector, new ResourcePasteOrDropProvider(), { id: ResourcePasteOrDropProvider.id, pasteMimeTypes: ResourcePasteOrDropProvider.mimeTypes, }), vscode.languages.registerDocumentDropEditProvider(selector, new ResourcePasteOrDropProvider(), { id: ResourcePasteOrDropProvider.id, dropMimeTypes: ResourcePasteOrDropProvider.mimeTypes, }), ); }
extensions/markdown-language-features/src/languageFeatures/copyFiles/dropOrPasteResource.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.0008013334008865058, 0.00021069640934001654, 0.00016131797747220844, 0.0001741446030791849, 0.00013539110659621656 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\tif (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n", "\t\t\t\t\t\t\tcontinue;\n", "\t\t\t\t\t\t}\n", "\n", "\t\t\t\t\t\tif (/\\.d\\.ts$/.test(file.name)) {\n", "\t\t\t\t\t\t\tsignature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t\t.update(file.text)\n", "\t\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\t\tif (!userWantsDeclarations) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tsignature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/panel'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { basename } from 'vs/base/common/resources'; import { isCodeEditor, isDiffEditor } from 'vs/editor/browser/editorBrowser'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { CommentNode, ResourceWithCommentThreads, ICommentThreadChangedEvent } from 'vs/workbench/contrib/comments/common/commentModel'; import { IWorkspaceCommentThreadsEvent, ICommentService } from 'vs/workbench/contrib/comments/browser/commentService'; import { IEditorService, ACTIVE_GROUP, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { textLinkForeground, textLinkActiveForeground, focusBorder, textPreformatForeground } from 'vs/platform/theme/common/colorRegistry'; import { ResourceLabels } from 'vs/workbench/browser/labels'; import { CommentsList, COMMENTS_VIEW_TITLE, Filter } from 'vs/workbench/contrib/comments/browser/commentsTreeViewer'; import { IViewPaneOptions, FilterViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IEditor } from 'vs/editor/common/editorCommon'; import { TextModel } from 'vs/editor/common/model/textModel'; import { CommentsViewFilterFocusContextKey, ICommentsView } from 'vs/workbench/contrib/comments/browser/comments'; import { CommentsFilters, CommentsFiltersChangeEvent } from 'vs/workbench/contrib/comments/browser/commentsViewActions'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { FilterOptions } from 'vs/workbench/contrib/comments/browser/commentsFilterOptions'; import { CommentThreadState } from 'vs/editor/common/languages'; import { ITreeElement } from 'vs/base/browser/ui/tree/tree'; import { Iterable } from 'vs/base/common/iterator'; import { CommentController } from 'vs/workbench/contrib/comments/browser/commentsController'; import { Range } from 'vs/editor/common/core/range'; import { registerNavigableContainer } from 'vs/workbench/browser/actions/widgetNavigationCommands'; import { CommentsModel, ICommentsModel } from 'vs/workbench/contrib/comments/browser/commentsModel'; export const CONTEXT_KEY_HAS_COMMENTS = new RawContextKey<boolean>('commentsView.hasComments', false); export const CONTEXT_KEY_SOME_COMMENTS_EXPANDED = new RawContextKey<boolean>('commentsView.someCommentsExpanded', false); const VIEW_STORAGE_ID = 'commentsViewState'; function createResourceCommentsIterator(model: ICommentsModel): Iterable<ITreeElement<ResourceWithCommentThreads | CommentNode>> { return Iterable.map(model.resourceCommentThreads, m => { const CommentNodeIt = Iterable.from(m.commentThreads); const children = Iterable.map(CommentNodeIt, r => ({ element: r })); return { element: m, children }; }); } export class CommentsPanel extends FilterViewPane implements ICommentsView { private treeLabels!: ResourceLabels; private tree: CommentsList | undefined; private treeContainer!: HTMLElement; private messageBoxContainer!: HTMLElement; private totalComments: number = 0; private readonly hasCommentsContextKey: IContextKey<boolean>; private readonly someCommentsExpandedContextKey: IContextKey<boolean>; private readonly filter: Filter; readonly filters: CommentsFilters; private currentHeight = 0; private currentWidth = 0; private readonly viewState: MementoObject; private readonly stateMemento: Memento; private cachedFilterStats: { total: number; filtered: number } | undefined = undefined; readonly onDidChangeVisibility = this.onDidChangeBodyVisibility; constructor( options: IViewPaneOptions, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ICommentService private readonly commentService: ICommentService, @ITelemetryService telemetryService: ITelemetryService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @IStorageService storageService: IStorageService ) { const stateMemento = new Memento(VIEW_STORAGE_ID, storageService); const viewState = stateMemento.getMemento(StorageScope.WORKSPACE, StorageTarget.MACHINE); super({ ...options, filterOptions: { placeholder: nls.localize('comments.filter.placeholder', "Filter (e.g. text, author)"), ariaLabel: nls.localize('comments.filter.ariaLabel', "Filter comments"), history: viewState['filterHistory'] || [], text: viewState['filter'] || '', focusContextKey: CommentsViewFilterFocusContextKey.key } }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.hasCommentsContextKey = CONTEXT_KEY_HAS_COMMENTS.bindTo(contextKeyService); this.someCommentsExpandedContextKey = CONTEXT_KEY_SOME_COMMENTS_EXPANDED.bindTo(contextKeyService); this.stateMemento = stateMemento; this.viewState = viewState; this.filters = this._register(new CommentsFilters({ showResolved: this.viewState['showResolved'] !== false, showUnresolved: this.viewState['showUnresolved'] !== false, }, this.contextKeyService)); this.filter = new Filter(new FilterOptions(this.filterWidget.getFilterText(), this.filters.showResolved, this.filters.showUnresolved)); this._register(this.filters.onDidChange((event: CommentsFiltersChangeEvent) => { if (event.showResolved || event.showUnresolved) { this.updateFilter(); } })); this._register(this.filterWidget.onDidChangeFilterText(() => this.updateFilter())); } override saveState(): void { this.viewState['filter'] = this.filterWidget.getFilterText(); this.viewState['filterHistory'] = this.filterWidget.getHistory(); this.viewState['showResolved'] = this.filters.showResolved; this.viewState['showUnresolved'] = this.filters.showUnresolved; this.stateMemento.saveMemento(); super.saveState(); } override render(): void { super.render(); this._register(registerNavigableContainer({ focusNotifiers: [this, this.filterWidget], focusNextWidget: () => { if (this.filterWidget.hasFocus()) { this.focus(); } }, focusPreviousWidget: () => { if (!this.filterWidget.hasFocus()) { this.focusFilter(); } } })); } public focusFilter(): void { this.filterWidget.focus(); } public clearFilterText(): void { this.filterWidget.setFilterText(''); } public getFilterStats(): { total: number; filtered: number } { if (!this.cachedFilterStats) { this.cachedFilterStats = { total: this.totalComments, filtered: this.tree?.getVisibleItemCount() ?? 0 }; } return this.cachedFilterStats; } private updateFilter() { this.filter.options = new FilterOptions(this.filterWidget.getFilterText(), this.filters.showResolved, this.filters.showUnresolved); this.tree?.filterComments(); this.cachedFilterStats = undefined; const { total, filtered } = this.getFilterStats(); this.filterWidget.updateBadge(total === filtered || total === 0 ? undefined : nls.localize('showing filtered results', "Showing {0} of {1}", filtered, total)); this.filterWidget.checkMoreFilters(!this.filters.showResolved || !this.filters.showUnresolved); } protected override renderBody(container: HTMLElement): void { super.renderBody(container); container.classList.add('comments-panel'); const domContainer = dom.append(container, dom.$('.comments-panel-container')); this.treeContainer = dom.append(domContainer, dom.$('.tree-container')); this.treeContainer.classList.add('file-icon-themable-tree', 'show-file-icons'); this.cachedFilterStats = undefined; this.createTree(); this.createMessageBox(domContainer); this._register(this.commentService.onDidSetAllCommentThreads(this.onAllCommentsChanged, this)); this._register(this.commentService.onDidUpdateCommentThreads(this.onCommentsUpdated, this)); this._register(this.commentService.onDidDeleteDataProvider(this.onDataProviderDeleted, this)); const styleElement = dom.createStyleSheet(container); this.applyStyles(styleElement); this._register(this.themeService.onDidColorThemeChange(_ => this.applyStyles(styleElement))); this._register(this.onDidChangeBodyVisibility(visible => { if (visible) { this.refresh(); } })); this.renderComments(); } public override focus(): void { super.focus(); const element = this.tree?.getHTMLElement(); if (element && dom.isActiveElement(element)) { return; } if (!this.commentService.commentsModel.hasCommentThreads() && this.messageBoxContainer) { this.messageBoxContainer.focus(); } else if (this.tree) { this.tree.domFocus(); } } private applyStyles(styleElement: HTMLStyleElement) { const content: string[] = []; const theme = this.themeService.getColorTheme(); const linkColor = theme.getColor(textLinkForeground); if (linkColor) { content.push(`.comments-panel .comments-panel-container a { color: ${linkColor}; }`); } const linkActiveColor = theme.getColor(textLinkActiveForeground); if (linkActiveColor) { content.push(`.comments-panel .comments-panel-container a:hover, a:active { color: ${linkActiveColor}; }`); } const focusColor = theme.getColor(focusBorder); if (focusColor) { content.push(`.comments-panel .comments-panel-container a:focus { outline-color: ${focusColor}; }`); } const codeTextForegroundColor = theme.getColor(textPreformatForeground); if (codeTextForegroundColor) { content.push(`.comments-panel .comments-panel-container .text code { color: ${codeTextForegroundColor}; }`); } styleElement.textContent = content.join('\n'); } private async renderComments(): Promise<void> { this.treeContainer.classList.toggle('hidden', !this.commentService.commentsModel.hasCommentThreads()); this.renderMessage(); await this.tree?.setChildren(null, createResourceCommentsIterator(this.commentService.commentsModel)); } public collapseAll() { if (this.tree) { this.tree.collapseAll(); this.tree.setSelection([]); this.tree.setFocus([]); this.tree.domFocus(); this.tree.focusFirst(); } } public expandAll() { if (this.tree) { this.tree.expandAll(); this.tree.setSelection([]); this.tree.setFocus([]); this.tree.domFocus(); this.tree.focusFirst(); } } public get hasRendered(): boolean { return !!this.tree; } protected layoutBodyContent(height: number = this.currentHeight, width: number = this.currentWidth): void { if (this.messageBoxContainer) { this.messageBoxContainer.style.height = `${height}px`; } this.tree?.layout(height, width); this.currentHeight = height; this.currentWidth = width; } private createMessageBox(parent: HTMLElement): void { this.messageBoxContainer = dom.append(parent, dom.$('.message-box-container')); this.messageBoxContainer.setAttribute('tabIndex', '0'); } private renderMessage(): void { this.messageBoxContainer.textContent = this.commentService.commentsModel.getMessage(); this.messageBoxContainer.classList.toggle('hidden', this.commentService.commentsModel.hasCommentThreads()); } private createTree(): void { this.treeLabels = this._register(this.instantiationService.createInstance(ResourceLabels, this)); this.tree = this._register(this.instantiationService.createInstance(CommentsList, this.treeLabels, this.treeContainer, { overrideStyles: { listBackground: this.getBackgroundColor() }, selectionNavigation: true, filter: this.filter, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (item: CommentsModel | ResourceWithCommentThreads | CommentNode) => { return undefined; } }, accessibilityProvider: { getAriaLabel(element: any): string { if (element instanceof CommentsModel) { return nls.localize('rootCommentsLabel', "Comments for current workspace"); } if (element instanceof ResourceWithCommentThreads) { return nls.localize('resourceWithCommentThreadsLabel', "Comments in {0}, full path {1}", basename(element.resource), element.resource.fsPath); } if (element instanceof CommentNode) { if (element.range) { return nls.localize('resourceWithCommentLabel', "Comment from ${0} at line {1} column {2} in {3}, source: {4}", element.comment.userName, element.range.startLineNumber, element.range.startColumn, basename(element.resource), (typeof element.comment.body === 'string') ? element.comment.body : element.comment.body.value ); } else { return nls.localize('resourceWithCommentLabelFile', "Comment from ${0} in {1}, source: {2}", element.comment.userName, basename(element.resource), (typeof element.comment.body === 'string') ? element.comment.body : element.comment.body.value ); } } return ''; }, getWidgetAriaLabel(): string { return COMMENTS_VIEW_TITLE.value; } } })); this._register(this.tree.onDidOpen(e => { this.openFile(e.element, e.editorOptions.pinned, e.editorOptions.preserveFocus, e.sideBySide); })); this._register(this.tree.onDidChangeModel(() => { this.updateSomeCommentsExpanded(); })); this._register(this.tree.onDidChangeCollapseState(() => { this.updateSomeCommentsExpanded(); })); } private openFile(element: any, pinned?: boolean, preserveFocus?: boolean, sideBySide?: boolean): boolean { if (!element) { return false; } if (!(element instanceof ResourceWithCommentThreads || element instanceof CommentNode)) { return false; } if (!this.commentService.isCommentingEnabled) { this.commentService.enableCommenting(true); } const range = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].range : element.range; const activeEditor = this.editorService.activeTextEditorControl; // If the active editor is a diff editor where one of the sides has the comment, // then we try to reveal the comment in the diff editor. const currentActiveResources: IEditor[] = isDiffEditor(activeEditor) ? [activeEditor.getOriginalEditor(), activeEditor.getModifiedEditor()] : (activeEditor ? [activeEditor] : []); for (const editor of currentActiveResources) { const model = editor.getModel(); if ((model instanceof TextModel) && this.uriIdentityService.extUri.isEqual(element.resource, model.uri)) { const threadToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].threadId : element.threadId; const commentToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].comment.uniqueIdInThread : element.comment.uniqueIdInThread; if (threadToReveal && isCodeEditor(editor)) { const controller = CommentController.get(editor); controller?.revealCommentThread(threadToReveal, commentToReveal, true, !preserveFocus); } return true; } } const threadToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].threadId : element.threadId; const commentToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].comment : element.comment; this.editorService.openEditor({ resource: element.resource, options: { pinned: pinned, preserveFocus: preserveFocus, selection: range ?? new Range(1, 1, 1, 1) } }, sideBySide ? SIDE_GROUP : ACTIVE_GROUP).then(editor => { if (editor) { const control = editor.getControl(); if (threadToReveal && isCodeEditor(control)) { const controller = CommentController.get(control); controller?.revealCommentThread(threadToReveal, commentToReveal.uniqueIdInThread, true, !preserveFocus); } } }); return true; } private async refresh(): Promise<void> { if (!this.tree) { return; } if (this.isVisible()) { this.hasCommentsContextKey.set(this.commentService.commentsModel.hasCommentThreads()); this.treeContainer.classList.toggle('hidden', !this.commentService.commentsModel.hasCommentThreads()); this.cachedFilterStats = undefined; this.renderMessage(); this.tree?.setChildren(null, createResourceCommentsIterator(this.commentService.commentsModel)); if (this.tree.getSelection().length === 0 && this.commentService.commentsModel.hasCommentThreads()) { const firstComment = this.commentService.commentsModel.resourceCommentThreads[0].commentThreads[0]; if (firstComment) { this.tree.setFocus([firstComment]); this.tree.setSelection([firstComment]); } } } } private onAllCommentsChanged(e: IWorkspaceCommentThreadsEvent): void { this.cachedFilterStats = undefined; this.totalComments += e.commentThreads.length; let unresolved = 0; for (const thread of e.commentThreads) { if (thread.state === CommentThreadState.Unresolved) { unresolved++; } } this.refresh(); } private onCommentsUpdated(e: ICommentThreadChangedEvent): void { this.cachedFilterStats = undefined; this.totalComments += e.added.length; this.totalComments -= e.removed.length; let unresolved = 0; for (const resource of this.commentService.commentsModel.resourceCommentThreads) { for (const thread of resource.commentThreads) { if (thread.threadState === CommentThreadState.Unresolved) { unresolved++; } } } this.refresh(); } private onDataProviderDeleted(owner: string | undefined): void { this.cachedFilterStats = undefined; this.totalComments = 0; this.refresh(); } private updateSomeCommentsExpanded() { this.someCommentsExpandedContextKey.set(this.isSomeCommentsExpanded()); } public areAllCommentsExpanded(): boolean { if (!this.tree) { return false; } const navigator = this.tree.navigate(); while (navigator.next()) { if (this.tree.isCollapsed(navigator.current())) { return false; } } return true; } public isSomeCommentsExpanded(): boolean { if (!this.tree) { return false; } const navigator = this.tree.navigate(); while (navigator.next()) { if (!this.tree.isCollapsed(navigator.current())) { return true; } } return false; } }
src/vs/workbench/contrib/comments/browser/commentsView.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.00017659453442320228, 0.00017240534361917526, 0.00016625392891000956, 0.00017278296581935138, 0.000002017412271015928 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\tif (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n", "\t\t\t\t\t\t\tcontinue;\n", "\t\t\t\t\t\t}\n", "\n", "\t\t\t\t\t\tif (/\\.d\\.ts$/.test(file.name)) {\n", "\t\t\t\t\t\t\tsignature = crypto.createHash('md5')\n", "\t\t\t\t\t\t\t\t.update(file.text)\n", "\t\t\t\t\t\t\t\t.digest('base64');\n", "\n", "\t\t\t\t\t\t\tif (!userWantsDeclarations) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tsignature = crypto.createHash('sha256')\n" ], "file_path": "build/lib/tsb/builder.ts", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { getErrorMessage, isCancellationError } from 'vs/base/common/errors'; import { Schemas } from 'vs/base/common/network'; import { basename } from 'vs/base/common/resources'; import { gt } from 'vs/base/common/semver/semver'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { EXTENSION_IDENTIFIER_REGEX, IExtensionGalleryService, IExtensionInfo, IExtensionManagementService, IGalleryExtension, ILocalExtension, InstallOptions, InstallExtensionInfo, InstallOperation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { areSameExtensions, getExtensionId, getGalleryExtensionId, getIdAndVersion } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { ExtensionType, EXTENSION_CATEGORIES, IExtensionManifest } from 'vs/platform/extensions/common/extensions'; import { ILogger } from 'vs/platform/log/common/log'; const notFound = (id: string) => localize('notFound', "Extension '{0}' not found.", id); const useId = localize('useId', "Make sure you use the full extension ID, including the publisher, e.g.: {0}", 'ms-dotnettools.csharp'); type InstallVSIXInfo = { vsix: URI; installOptions: InstallOptions }; type CLIInstallExtensionInfo = { id: string; version?: string; installOptions: InstallOptions }; export class ExtensionManagementCLI { constructor( protected readonly logger: ILogger, @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService, @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService, ) { } protected get location(): string | undefined { return undefined; } public async listExtensions(showVersions: boolean, category?: string, profileLocation?: URI): Promise<void> { let extensions = await this.extensionManagementService.getInstalled(ExtensionType.User, profileLocation); const categories = EXTENSION_CATEGORIES.map(c => c.toLowerCase()); if (category && category !== '') { if (categories.indexOf(category.toLowerCase()) < 0) { this.logger.info('Invalid category please enter a valid category. To list valid categories run --category without a category specified'); return; } extensions = extensions.filter(e => { if (e.manifest.categories) { const lowerCaseCategories: string[] = e.manifest.categories.map(c => c.toLowerCase()); return lowerCaseCategories.indexOf(category.toLowerCase()) > -1; } return false; }); } else if (category === '') { this.logger.info('Possible Categories: '); categories.forEach(category => { this.logger.info(category); }); return; } if (this.location) { this.logger.info(localize('listFromLocation', "Extensions installed on {0}:", this.location)); } extensions = extensions.sort((e1, e2) => e1.identifier.id.localeCompare(e2.identifier.id)); let lastId: string | undefined = undefined; for (const extension of extensions) { if (lastId !== extension.identifier.id) { lastId = extension.identifier.id; this.logger.info(showVersions ? `${lastId}@${extension.manifest.version}` : lastId); } } } public async installExtensions(extensions: (string | URI)[], builtinExtensions: (string | URI)[], installOptions: InstallOptions, force: boolean): Promise<void> { const failed: string[] = []; try { const installedExtensionsManifests: IExtensionManifest[] = []; if (extensions.length) { this.logger.info(this.location ? localize('installingExtensionsOnLocation', "Installing extensions on {0}...", this.location) : localize('installingExtensions', "Installing extensions...")); } const installVSIXInfos: InstallVSIXInfo[] = []; let installExtensionInfos: CLIInstallExtensionInfo[] = []; const addInstallExtensionInfo = (id: string, version: string | undefined, isBuiltin: boolean) => { installExtensionInfos.push({ id, version: version !== 'prerelease' ? version : undefined, installOptions: { ...installOptions, isBuiltin, installPreReleaseVersion: version === 'prerelease' || installOptions.installPreReleaseVersion } }); }; for (const extension of extensions) { if (extension instanceof URI) { installVSIXInfos.push({ vsix: extension, installOptions }); } else { const [id, version] = getIdAndVersion(extension); addInstallExtensionInfo(id, version, false); } } for (const extension of builtinExtensions) { if (extension instanceof URI) { installVSIXInfos.push({ vsix: extension, installOptions: { ...installOptions, isBuiltin: true, donotIncludePackAndDependencies: true } }); } else { const [id, version] = getIdAndVersion(extension); addInstallExtensionInfo(id, version, true); } } const installed = await this.extensionManagementService.getInstalled(ExtensionType.User, installOptions.profileLocation); if (installVSIXInfos.length) { await Promise.all(installVSIXInfos.map(async ({ vsix, installOptions }) => { try { const manifest = await this.installVSIX(vsix, installOptions, force, installed); if (manifest) { installedExtensionsManifests.push(manifest); } } catch (err) { this.logger.error(err); failed.push(vsix.toString()); } })); } if (installExtensionInfos.length) { installExtensionInfos = installExtensionInfos.filter(({ id, version }) => { const installedExtension = installed.find(i => areSameExtensions(i.identifier, { id })); if (installedExtension) { if (!force && (!version || (version === 'prerelease' && installedExtension.preRelease))) { this.logger.info(localize('alreadyInstalled-checkAndUpdate', "Extension '{0}' v{1} is already installed. Use '--force' option to update to latest version or provide '@<version>' to install a specific version, for example: '{2}@1.2.3'.", id, installedExtension.manifest.version, id)); return false; } if (version && installedExtension.manifest.version === version) { this.logger.info(localize('alreadyInstalled', "Extension '{0}' is already installed.", `${id}@${version}`)); return false; } } return true; }); if (installExtensionInfos.length) { const galleryExtensions = await this.getGalleryExtensions(installExtensionInfos); await Promise.all(installExtensionInfos.map(async extensionInfo => { const gallery = galleryExtensions.get(extensionInfo.id.toLowerCase()); if (gallery) { try { const manifest = await this.installFromGallery(extensionInfo, gallery, installed); if (manifest) { installedExtensionsManifests.push(manifest); } } catch (err) { this.logger.error(err.message || err.stack || err); failed.push(extensionInfo.id); } } else { this.logger.error(`${notFound(extensionInfo.version ? `${extensionInfo.id}@${extensionInfo.version}` : extensionInfo.id)}\n${useId}`); failed.push(extensionInfo.id); } })); } } } catch (error) { this.logger.error(localize('error while installing extensions', "Error while installing extensions: {0}", getErrorMessage(error))); throw error; } if (failed.length) { throw new Error(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', '))); } } public async updateExtensions(profileLocation?: URI): Promise<void> { const installedExtensions = await this.extensionManagementService.getInstalled(ExtensionType.User, profileLocation); const installedExtensionsQuery: IExtensionInfo[] = []; for (const extension of installedExtensions) { if (!!extension.identifier.uuid) { // No need to check new version for an unpublished extension installedExtensionsQuery.push({ ...extension.identifier, preRelease: extension.preRelease }); } } this.logger.trace(localize('updateExtensionsQuery', "Fetching latest versions for {0} extensions", installedExtensionsQuery.length)); const availableVersions = await this.extensionGalleryService.getExtensions(installedExtensionsQuery, { compatible: true }, CancellationToken.None); const extensionsToUpdate: InstallExtensionInfo[] = []; for (const newVersion of availableVersions) { for (const oldVersion of installedExtensions) { if (areSameExtensions(oldVersion.identifier, newVersion.identifier) && gt(newVersion.version, oldVersion.manifest.version)) { extensionsToUpdate.push({ extension: newVersion, options: { operation: InstallOperation.Update, installPreReleaseVersion: oldVersion.isPreReleaseVersion } }); } } } if (!extensionsToUpdate.length) { this.logger.info(localize('updateExtensionsNoExtensions', "No extension to update")); return; } this.logger.info(localize('updateExtensionsNewVersionsAvailable', "Updating extensions: {0}", extensionsToUpdate.map(ext => ext.extension.identifier.id).join(', '))); const installationResult = await this.extensionManagementService.installGalleryExtensions(extensionsToUpdate); for (const extensionResult of installationResult) { if (extensionResult.error) { this.logger.error(localize('errorUpdatingExtension', "Error while updating extension {0}: {1}", extensionResult.identifier.id, getErrorMessage(extensionResult.error))); } else { this.logger.info(localize('successUpdate', "Extension '{0}' v{1} was successfully updated.", extensionResult.identifier.id, extensionResult.local?.manifest.version)); } } } private async installVSIX(vsix: URI, installOptions: InstallOptions, force: boolean, installedExtensions: ILocalExtension[]): Promise<IExtensionManifest | null> { const manifest = await this.extensionManagementService.getManifest(vsix); if (!manifest) { throw new Error('Invalid vsix'); } const valid = await this.validateVSIX(manifest, force, installOptions.profileLocation, installedExtensions); if (valid) { try { await this.extensionManagementService.install(vsix, installOptions); this.logger.info(localize('successVsixInstall', "Extension '{0}' was successfully installed.", basename(vsix))); return manifest; } catch (error) { if (isCancellationError(error)) { this.logger.info(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", basename(vsix))); return null; } else { throw error; } } } return null; } private async getGalleryExtensions(extensions: CLIInstallExtensionInfo[]): Promise<Map<string, IGalleryExtension>> { const galleryExtensions = new Map<string, IGalleryExtension>(); const preRelease = extensions.some(e => e.installOptions.installPreReleaseVersion); const targetPlatform = await this.extensionManagementService.getTargetPlatform(); const extensionInfos: IExtensionInfo[] = []; for (const extension of extensions) { if (EXTENSION_IDENTIFIER_REGEX.test(extension.id)) { extensionInfos.push({ ...extension, preRelease }); } } if (extensionInfos.length) { const result = await this.extensionGalleryService.getExtensions(extensionInfos, { targetPlatform }, CancellationToken.None); for (const extension of result) { galleryExtensions.set(extension.identifier.id.toLowerCase(), extension); } } return galleryExtensions; } private async installFromGallery({ id, version, installOptions }: CLIInstallExtensionInfo, galleryExtension: IGalleryExtension, installed: ILocalExtension[]): Promise<IExtensionManifest | null> { const manifest = await this.extensionGalleryService.getManifest(galleryExtension, CancellationToken.None); if (manifest && !this.validateExtensionKind(manifest)) { return null; } const installedExtension = installed.find(e => areSameExtensions(e.identifier, galleryExtension.identifier)); if (installedExtension) { if (galleryExtension.version === installedExtension.manifest.version) { this.logger.info(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id)); return null; } this.logger.info(localize('updateMessage', "Updating the extension '{0}' to the version {1}", id, galleryExtension.version)); } try { if (installOptions.isBuiltin) { this.logger.info(version ? localize('installing builtin with version', "Installing builtin extension '{0}' v{1}...", id, version) : localize('installing builtin ', "Installing builtin extension '{0}'...", id)); } else { this.logger.info(version ? localize('installing with version', "Installing extension '{0}' v{1}...", id, version) : localize('installing', "Installing extension '{0}'...", id)); } const local = await this.extensionManagementService.installFromGallery(galleryExtension, { ...installOptions, installGivenVersion: !!version }); this.logger.info(localize('successInstall', "Extension '{0}' v{1} was successfully installed.", id, local.manifest.version)); return manifest; } catch (error) { if (isCancellationError(error)) { this.logger.info(localize('cancelInstall', "Cancelled installing extension '{0}'.", id)); return null; } else { throw error; } } } protected validateExtensionKind(_manifest: IExtensionManifest): boolean { return true; } private async validateVSIX(manifest: IExtensionManifest, force: boolean, profileLocation: URI | undefined, installedExtensions: ILocalExtension[]): Promise<boolean> { if (!force) { const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) }; const newer = installedExtensions.find(local => areSameExtensions(extensionIdentifier, local.identifier) && gt(local.manifest.version, manifest.version)); if (newer) { this.logger.info(localize('forceDowngrade', "A newer version of extension '{0}' v{1} is already installed. Use '--force' option to downgrade to older version.", newer.identifier.id, newer.manifest.version, manifest.version)); return false; } } return this.validateExtensionKind(manifest); } public async uninstallExtensions(extensions: (string | URI)[], force: boolean, profileLocation?: URI): Promise<void> { const getId = async (extensionDescription: string | URI): Promise<string> => { if (extensionDescription instanceof URI) { const manifest = await this.extensionManagementService.getManifest(extensionDescription); return getExtensionId(manifest.publisher, manifest.name); } return extensionDescription; }; const uninstalledExtensions: ILocalExtension[] = []; for (const extension of extensions) { const id = await getId(extension); const installed = await this.extensionManagementService.getInstalled(undefined, profileLocation); const extensionsToUninstall = installed.filter(e => areSameExtensions(e.identifier, { id })); if (!extensionsToUninstall.length) { throw new Error(`${this.notInstalled(id)}\n${useId}`); } if (extensionsToUninstall.some(e => e.type === ExtensionType.System)) { this.logger.info(localize('builtin', "Extension '{0}' is a Built-in extension and cannot be uninstalled", id)); return; } if (!force && extensionsToUninstall.some(e => e.isBuiltin)) { this.logger.info(localize('forceUninstall', "Extension '{0}' is marked as a Built-in extension by user. Please use '--force' option to uninstall it.", id)); return; } this.logger.info(localize('uninstalling', "Uninstalling {0}...", id)); for (const extensionToUninstall of extensionsToUninstall) { await this.extensionManagementService.uninstall(extensionToUninstall, { profileLocation }); uninstalledExtensions.push(extensionToUninstall); } if (this.location) { this.logger.info(localize('successUninstallFromLocation', "Extension '{0}' was successfully uninstalled from {1}!", id, this.location)); } else { this.logger.info(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)); } } } public async locateExtension(extensions: string[]): Promise<void> { const installed = await this.extensionManagementService.getInstalled(); extensions.forEach(e => { installed.forEach(i => { if (i.identifier.id === e) { if (i.location.scheme === Schemas.file) { this.logger.info(i.location.fsPath); return; } } }); }); } private notInstalled(id: string) { return this.location ? localize('notInstalleddOnLocation', "Extension '{0}' is not installed on {1}.", id, this.location) : localize('notInstalled', "Extension '{0}' is not installed.", id); } }
src/vs/platform/extensionManagement/common/extensionManagementCLI.ts
0
https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467
[ 0.00017561725690029562, 0.00017165052122436464, 0.0001620777911739424, 0.0001723679743008688, 0.0000027195435450266814 ]
{ "id": 0, "code_window": [ "\t\tloop: true\n", "\t}\n", "];\n", "\n", "export function defaultPattern(name: 'msCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'tsc'): ProblemPattern;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "_defaultPatterns['go'] = {\n", "\tregexp: /^([^:]*: )?((.:)?[^:]*):(\\d+)(:(\\d+))?: (.*)$/,\n", "\tfile: 2,\n", "\tline: 4,\n", "\tcolumn: 6,\n", "\tmessage: 7\n", "};\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 496 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as NLS from 'vs/nls'; import * as Objects from 'vs/base/common/objects'; import * as Strings from 'vs/base/common/strings'; import * as Assert from 'vs/base/common/assert'; import * as Paths from 'vs/base/common/paths'; import * as Types from 'vs/base/common/types'; import Severity from 'vs/base/common/severity'; import URI from 'vs/base/common/uri'; import { ValidationStatus, ValidationState, ILogger, Parser } from 'vs/base/common/parsers'; import { IStringDictionary } from 'vs/base/common/collections'; import { IMarkerData } from 'vs/platform/markers/common/markers'; export enum FileLocationKind { Auto, Relative, Absolute } export module FileLocationKind { export function fromString(value: string): FileLocationKind { value = value.toLowerCase(); if (value === 'absolute') { return FileLocationKind.Absolute; } else if (value === 'relative') { return FileLocationKind.Relative; } else { return undefined; } } } export interface ProblemPattern { regexp: RegExp; file?: number; message?: number; location?: number; line?: number; column?: number; endLine?: number; endColumn?: number; code?: number; severity?: number; loop?: boolean; mostSignifikant?: boolean; [key: string]: any; } export let problemPatternProperties = ['file', 'message', 'location', 'line', 'column', 'endLine', 'endColumn', 'code', 'severity', 'loop', 'mostSignifikant']; export interface WatchingPattern { regexp: RegExp; file?: number; } export interface WatchingMatcher { activeOnStart: boolean; beginsPattern: WatchingPattern; endsPattern: WatchingPattern; } export enum ApplyToKind { allDocuments, openDocuments, closedDocuments } export module ApplyToKind { export function fromString(value: string): ApplyToKind { value = value.toLowerCase(); if (value === 'alldocuments') { return ApplyToKind.allDocuments; } else if (value === 'opendocuments') { return ApplyToKind.openDocuments; } else if (value === 'closeddocuments') { return ApplyToKind.closedDocuments; } else { return undefined; } } } export interface ProblemMatcher { owner: string; applyTo: ApplyToKind; fileLocation: FileLocationKind; filePrefix?: string; pattern: ProblemPattern | ProblemPattern[]; severity?: Severity; watching?: WatchingMatcher; } export interface NamedProblemMatcher extends ProblemMatcher { name: string; } export function isNamedProblemMatcher(value: ProblemMatcher): value is NamedProblemMatcher { return Types.isString((<NamedProblemMatcher>value).name) ? true : false; } let valueMap: { [key: string]: string; } = { E: 'error', W: 'warning', I: 'info', }; interface Location { startLineNumber: number; startColumn: number; endLineNumber: number; endColumn: number; } interface ProblemData { file?: string; location?: string; line?: string; column?: string; endLine?: string; endColumn?: string; message?: string; severity?: string; code?: string; [key: string]: string; } export interface ProblemMatch { resource: URI; marker: IMarkerData; description: ProblemMatcher; } export interface HandleResult { match: ProblemMatch; continue: boolean; } export function getResource(filename: string, matcher: ProblemMatcher): URI { let kind = matcher.fileLocation; let fullPath: string; if (kind === FileLocationKind.Absolute) { fullPath = filename; } else if (kind === FileLocationKind.Relative) { fullPath = Paths.join(matcher.filePrefix, filename); } fullPath = fullPath.replace(/\\/g, '/'); if (fullPath[0] !== '/') { fullPath = '/' + fullPath; } return URI.parse('file://' + fullPath); } export interface ILineMatcher { matchLength: number; next(line: string): ProblemMatch; handle(lines: string[], start?: number): HandleResult; } export function createLineMatcher(matcher: ProblemMatcher): ILineMatcher { let pattern = matcher.pattern; if (Types.isArray(pattern)) { return new MultiLineMatcher(matcher); } else { return new SingleLineMatcher(matcher); } } class AbstractLineMatcher implements ILineMatcher { private matcher: ProblemMatcher; constructor(matcher: ProblemMatcher) { this.matcher = matcher; } public handle(lines: string[], start: number = 0): HandleResult { return { match: null, continue: false }; } public next(line: string): ProblemMatch { return null; } public get matchLength(): number { throw new Error('Subclass reponsibility'); } protected fillProblemData(data: ProblemData, pattern: ProblemPattern, matches: RegExpExecArray): void { this.fillProperty(data, 'file', pattern, matches, true); this.fillProperty(data, 'message', pattern, matches, true); this.fillProperty(data, 'code', pattern, matches, true); this.fillProperty(data, 'severity', pattern, matches, true); this.fillProperty(data, 'location', pattern, matches, true); this.fillProperty(data, 'line', pattern, matches); this.fillProperty(data, 'column', pattern, matches); this.fillProperty(data, 'endLine', pattern, matches); this.fillProperty(data, 'endColumn', pattern, matches); } private fillProperty(data: ProblemData, property: string, pattern: ProblemPattern, matches: RegExpExecArray, trim: boolean = false): void { if (Types.isUndefined(data[property]) && !Types.isUndefined(pattern[property]) && pattern[property] < matches.length) { let value = matches[pattern[property]]; if (trim) { value = Strings.trim(value); } data[property] = value; } } protected getMarkerMatch(data: ProblemData): ProblemMatch { let location = this.getLocation(data); if (data.file && location && data.message) { let marker: IMarkerData = { severity: this.getSeverity(data), startLineNumber: location.startLineNumber, startColumn: location.startColumn, endLineNumber: location.startLineNumber, endColumn: location.endColumn, message: data.message }; if (!Types.isUndefined(data.code)) { marker.code = data.code; } return { description: this.matcher, resource: this.getResource(data.file), marker: marker }; } } protected getResource(filename: string): URI { return getResource(filename, this.matcher); } private getLocation(data: ProblemData): Location { if (data.location) { return this.parseLocationInfo(data.location); } if (!data.line) { return null; } let startLine = parseInt(data.line); let startColumn = data.column ? parseInt(data.column) : undefined; let endLine = data.endLine ? parseInt(data.endLine) : undefined; let endColumn = data.endColumn ? parseInt(data.endColumn) : undefined; return this.createLocation(startLine, startColumn, endLine, endColumn); } private parseLocationInfo(value: string): Location { if (!value || !value.match(/(\d+|\d+,\d+|\d+,\d+,\d+,\d+)/)) { return null; } let parts = value.split(','); let startLine = parseInt(parts[0]); let startColumn = parts.length > 1 ? parseInt(parts[1]) : undefined; if (parts.length > 3) { return this.createLocation(startLine, startColumn, parseInt(parts[2]), parseInt(parts[3])); } else { return this.createLocation(startLine, startColumn, undefined, undefined); } } private createLocation(startLine: number, startColumn: number, endLine: number, endColumn: number): Location { if (startLine && startColumn && endLine && endColumn) { return { startLineNumber: startLine, startColumn: startColumn, endLineNumber: endLine, endColumn: endColumn }; } if (startLine && startColumn) { return { startLineNumber: startLine, startColumn: startColumn, endLineNumber: startLine, endColumn: startColumn }; } return { startLineNumber: startLine, startColumn: 1, endLineNumber: startLine, endColumn: Number.MAX_VALUE }; } private getSeverity(data: ProblemData): Severity { let result: Severity = null; if (data.severity) { let value = data.severity; if (value && value.length > 0) { if (value.length === 1 && valueMap[value[0]]) { value = valueMap[value[0]]; } result = Severity.fromValue(value); } } if (result === null || result === Severity.Ignore) { result = this.matcher.severity || Severity.Error; } return result; } } class SingleLineMatcher extends AbstractLineMatcher { private pattern: ProblemPattern; constructor(matcher: ProblemMatcher) { super(matcher); this.pattern = <ProblemPattern>matcher.pattern; } public get matchLength(): number { return 1; } public handle(lines: string[], start: number = 0): HandleResult { Assert.ok(lines.length - start === 1); let data: ProblemData = Object.create(null); let matches = this.pattern.regexp.exec(lines[start]); if (matches) { this.fillProblemData(data, this.pattern, matches); let match = this.getMarkerMatch(data); if (match) { return { match: match, continue: false }; } } return { match: null, continue: false }; } public next(line: string): ProblemMatch { return null; } } class MultiLineMatcher extends AbstractLineMatcher { private patterns: ProblemPattern[]; private data: ProblemData; constructor(matcher: ProblemMatcher) { super(matcher); this.patterns = <ProblemPattern[]>matcher.pattern; } public get matchLength(): number { return this.patterns.length; } public handle(lines: string[], start: number = 0): HandleResult { Assert.ok(lines.length - start === this.patterns.length); this.data = Object.create(null); let data = this.data; for (let i = 0; i < this.patterns.length; i++) { let pattern = this.patterns[i]; let matches = pattern.regexp.exec(lines[i + start]); if (!matches) { return { match: null, continue: false }; } else { // Only the last pattern can loop if (pattern.loop && i === this.patterns.length - 1) { data = Objects.clone(data); } this.fillProblemData(data, pattern, matches); } } let loop = this.patterns[this.patterns.length - 1].loop; if (!loop) { this.data = null; } return { match: this.getMarkerMatch(data), continue: loop }; } public next(line: string): ProblemMatch { let pattern = this.patterns[this.patterns.length - 1]; Assert.ok(pattern.loop === true && this.data !== null); let matches = pattern.regexp.exec(line); if (!matches) { this.data = null; return null; } let data = Objects.clone(this.data); this.fillProblemData(data, pattern, matches); return this.getMarkerMatch(data); } } let _defaultPatterns: { [name: string]: ProblemPattern | ProblemPattern[]; } = Object.create(null); _defaultPatterns['msCompile'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(\w{1,2}\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['gulp-tsc'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(\d+)\s+(.*)$/, file: 1, location: 2, code: 3, message: 4 }; _defaultPatterns['tsc'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(TS\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['cpp'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(C\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['csc'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(CS\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['vb'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(BC\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['lessCompile'] = { regexp: /^\s*(.*) in file (.*) line no. (\d+)$/, message: 1, file: 2, line: 3 }; _defaultPatterns['jshint'] = { regexp: /^(.*):\s+line\s+(\d+),\s+col\s+(\d+),\s(.+?)(?:\s+\((\w)(\d+)\))?$/, file: 1, line: 2, column: 3, message: 4, severity: 5, code: 6 }; _defaultPatterns['jshint-stylish'] = [ { regexp: /^(.+)$/, file: 1 }, { regexp: /^\s+line\s+(\d+)\s+col\s+(\d+)\s+(.+?)(?:\s+\((\w)(\d+)\))?$/, line: 1, column: 2, message: 3, severity: 4, code: 5, loop: true } ]; _defaultPatterns['eslint-compact'] = { regexp: /^(.+):\sline\s(\d+),\scol\s(\d+),\s(Error|Warning|Info)\s-\s(.+)\s\((.+)\)$/, file: 1, line: 2, column: 3, severity: 4, message: 5, code: 6 }; _defaultPatterns['eslint-stylish'] = [ { regexp: /^([^\s].*)$/, file: 1 }, { regexp: /^\s+(\d+):(\d+)\s+(error|warning|info)\s+(.+?)\s\s+(.*)$/, line: 1, column: 2, severity: 3, message: 4, code: 5, loop: true } ]; export function defaultPattern(name: 'msCompile'): ProblemPattern; export function defaultPattern(name: 'tsc'): ProblemPattern; export function defaultPattern(name: 'cpp'): ProblemPattern; export function defaultPattern(name: 'csc'): ProblemPattern; export function defaultPattern(name: 'vb'): ProblemPattern; export function defaultPattern(name: 'lessCompile'): ProblemPattern; export function defaultPattern(name: 'jshint'): ProblemPattern; export function defaultPattern(name: 'gulp-tsc'): ProblemPattern; export function defaultPattern(name: 'jshint-stylish'): ProblemPattern[]; export function defaultPattern(name: string): ProblemPattern | ProblemPattern[]; export function defaultPattern(name: string): ProblemPattern | ProblemPattern[] { return _defaultPatterns[name]; } export namespace Config { /** * Defines possible problem severity values */ export namespace ProblemSeverity { export const Error: string = 'error'; export const Warning: string = 'warning'; export const Info: string = 'info'; } export interface ProblemPattern { /** * The regular expression to find a problem in the console output of an * executed task. */ regexp?: string; /** * The match group index of the filename. * If omitted 1 is used. */ file?: number; /** * The match group index of the problems's location. Valid location * patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). * If omitted the line and colum properties are used. */ location?: number; /** * The match group index of the problem's line in the source file. * * Defaults to 2. */ line?: number; /** * The match group index of the problem's column in the source file. * * Defaults to 3. */ column?: number; /** * The match group index of the problem's end line in the source file. * * Defaults to undefined. No end line is captured. */ endLine?: number; /** * The match group index of the problem's end column in the source file. * * Defaults to undefined. No end column is captured. */ endColumn?: number; /** * The match group index of the problem's severity. * * Defaults to undefined. In this case the problem matcher's severity * is used. */ severity?: number; /** * The match group index of the problems's code. * * Defaults to undefined. No code is captured. */ code?: number; /** * The match group index of the message. If omitted it defaults * to 4 if location is specified. Otherwise it defaults to 5. */ message?: number; /** * Specifies if the last pattern in a multi line problem matcher should * loop as long as it does match a line consequently. Only valid on the * last problem pattern in a multi line problem matcher. */ loop?: boolean; [key: string]: any; } /** * A watching pattern */ export interface WatchingPattern { /** * The actual regular expression */ regexp?: string; /** * The match group index of the filename. If provided the expression * is matched for that file only. */ file?: number; } /** * A description to track the start and end of a watching task. */ export interface WatchingMatcher { /** * If set to true the watcher is in active mode when the task * starts. This is equals of issuing a line that matches the * beginPattern. */ activeOnStart?: boolean; /** * If matched in the output the start of a watching task is signaled. */ beginsPattern?: string | WatchingPattern; /** * If matched in the output the end of a watching task is signaled. */ endsPattern?: string | WatchingPattern; } /** * A description of a problem matcher that detects problems * in build output. */ export interface ProblemMatcher { /** * The name of a base problem matcher to use. If specified the * base problem matcher will be used as a template and properties * specified here will replace properties of the base problem * matcher */ base?: string; /** * The owner of the produced VSCode problem. This is typically * the identifier of a VSCode language service if the problems are * to be merged with the one produced by the language service * or 'external'. Defaults to 'external' if omitted. */ owner?: string; /** * Specifies to which kind of documents the problems found by this * matcher are applied. Valid values are: * * "allDocuments": problems found in all documents are applied. * "openDocuments": problems found in documents that are open * are applied. * "closedDocuments": problems found in closed documents are * applied. */ applyTo?: string; /** * The severity of the VSCode problem produced by this problem matcher. * * Valid values are: * "error": to produce errors. * "warning": to produce warnings. * "info": to produce infos. * * The value is used if a pattern doesn't specify a severity match group. * Defaults to "error" if omitted. */ severity?: string; /** * Defines how filename reported in a problem pattern * should be read. Valid values are: * - "absolute": the filename is always treated absolute. * - "relative": the filename is always treated relative to * the current working directory. This is the default. * - ["relative", "path value"]: the filename is always * treated relative to the given path value. */ fileLocation?: string | string[]; /** * The name of a predefined problem pattern, the inline definintion * of a problem pattern or an array of problem patterns to match * problems spread over multiple lines. */ pattern?: string | ProblemPattern | ProblemPattern[]; /** * A regular expression signaling that a watched tasks begins executing * triggered through file watching. */ watchedTaskBeginsRegExp?: string; /** * A regular expression signaling that a watched tasks ends executing. */ watchedTaskEndsRegExp?: string; watching?: WatchingMatcher; } export type ProblemMatcherType = string | ProblemMatcher | (string | ProblemMatcher)[]; export interface NamedProblemMatcher extends ProblemMatcher { /** * An optional name. This name can be used to refer to the * problem matchter from within a task. */ name?: string; } export function isNamedProblemMatcher(value: ProblemMatcher): value is NamedProblemMatcher { return Types.isString((<NamedProblemMatcher>value).name); } } export class ProblemMatcherParser extends Parser { private resolver: { get(name: string): ProblemMatcher; }; constructor(resolver: { get(name: string): ProblemMatcher; }, logger: ILogger, validationStatus: ValidationStatus = new ValidationStatus()) { super(logger, validationStatus); this.resolver = resolver; } public parse(json: Config.ProblemMatcher): ProblemMatcher { let result = this.createProblemMatcher(json); if (!this.checkProblemMatcherValid(json, result)) { return null; } this.addWatchingMatcher(json, result); return result; } private checkProblemMatcherValid(externalProblemMatcher: Config.ProblemMatcher, problemMatcher: ProblemMatcher): boolean { if (!problemMatcher || !problemMatcher.pattern || !problemMatcher.owner || Types.isUndefined(problemMatcher.fileLocation)) { this.status.state = ValidationState.Fatal; this.log(NLS.localize('ProblemMatcherParser.invalidMarkerDescription', 'Error: Invalid problemMatcher description. A matcher must at least define a pattern, owner and a file location. The problematic matcher is:\n{0}\n', JSON.stringify(externalProblemMatcher, null, 4))); return false; } return true; } private createProblemMatcher(description: Config.ProblemMatcher): ProblemMatcher { let result: ProblemMatcher = null; let owner = description.owner ? description.owner : 'external'; let applyTo = Types.isString(description.applyTo) ? ApplyToKind.fromString(description.applyTo) : ApplyToKind.allDocuments; if (!applyTo) { applyTo = ApplyToKind.allDocuments; } let fileLocation: FileLocationKind = undefined; let filePrefix: string = undefined; let kind: FileLocationKind; if (Types.isUndefined(description.fileLocation)) { fileLocation = FileLocationKind.Relative; filePrefix = '${cwd}'; } else if (Types.isString(description.fileLocation)) { kind = FileLocationKind.fromString(<string>description.fileLocation); if (kind) { fileLocation = kind; if (kind === FileLocationKind.Relative) { filePrefix = '${cwd}'; } } } else if (Types.isStringArray(description.fileLocation)) { let values = <string[]>description.fileLocation; if (values.length > 0) { kind = FileLocationKind.fromString(values[0]); if (values.length === 1 && kind === FileLocationKind.Absolute) { fileLocation = kind; } else if (values.length === 2 && kind === FileLocationKind.Relative && values[1]) { fileLocation = kind; filePrefix = values[1]; } } } let pattern = description.pattern ? this.createProblemPattern(description.pattern) : undefined; let severity = description.severity ? Severity.fromValue(description.severity) : undefined; if (severity === Severity.Ignore) { this.status.state = ValidationState.Info; this.log(NLS.localize('ProblemMatcherParser.unknownSeverity', 'Info: unknown severity {0}. Valid values are error, warning and info.\n', description.severity)); severity = Severity.Error; } if (Types.isString(description.base)) { let variableName = <string>description.base; if (variableName.length > 1 && variableName[0] === '$') { let base = this.resolver.get(variableName.substring(1)); if (base) { result = Objects.clone(base); if (description.owner) { result.owner = owner; } if (fileLocation) { result.fileLocation = fileLocation; } if (filePrefix) { result.filePrefix = filePrefix; } if (description.pattern) { result.pattern = pattern; } if (description.severity) { result.severity = severity; } } } } else if (fileLocation) { result = { owner: owner, applyTo: applyTo, fileLocation: fileLocation, pattern: pattern, }; if (filePrefix) { result.filePrefix = filePrefix; } if (severity) { result.severity = severity; } } if (Config.isNamedProblemMatcher(description)) { (<NamedProblemMatcher>result).name = description.name; } return result; } private createProblemPattern(value: string | Config.ProblemPattern | Config.ProblemPattern[]): ProblemPattern | ProblemPattern[] { let pattern: ProblemPattern; if (Types.isString(value)) { let variableName: string = <string>value; if (variableName.length > 1 && variableName[0] === '$') { return defaultPattern(variableName.substring(1)); } } else if (Types.isArray(value)) { let values = <Config.ProblemPattern[]>value; let result: ProblemPattern[] = []; for (let i = 0; i < values.length; i++) { pattern = this.createSingleProblemPattern(values[i], false); if (i < values.length - 1) { if (!Types.isUndefined(pattern.loop) && pattern.loop) { pattern.loop = false; this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.loopProperty.notLast', 'The loop property is only supported on the last line matcher.')); } } result.push(pattern); } this.validateProblemPattern(result); return result; } else { pattern = this.createSingleProblemPattern(<Config.ProblemPattern>value, true); if (!Types.isUndefined(pattern.loop) && pattern.loop) { pattern.loop = false; this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.loopProperty.notMultiLine', 'The loop property is only supported on multi line matchers.')); } this.validateProblemPattern([pattern]); return pattern; } return null; } private createSingleProblemPattern(value: Config.ProblemPattern, setDefaults: boolean): ProblemPattern { let result: ProblemPattern = { regexp: this.createRegularExpression(value.regexp) }; problemPatternProperties.forEach(property => { if (!Types.isUndefined(value[property])) { result[property] = value[property]; } }); if (setDefaults) { if (result.location) { result = Objects.mixin(result, { file: 1, message: 4 }, false); } else { result = Objects.mixin(result, { file: 1, line: 2, column: 3, message: 4 }, false); } } return result; } private validateProblemPattern(values: ProblemPattern[]): void { let file: boolean, message: boolean, location: boolean, line: boolean; let regexp: number = 0; values.forEach(pattern => { file = file || !!pattern.file; message = message || !!pattern.message; location = location || !!pattern.location; line = line || !!pattern.line; if (pattern.regexp) { regexp++; } }); if (regexp !== values.length) { this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.problemPattern.missingRegExp', 'The problem pattern is missing a regular expression.')); } if (!(file && message && (location || line))) { this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.problemPattern.missingProperty', 'The problem pattern is invalid. It must have at least a file, message and line or location match group.')); } } private addWatchingMatcher(external: Config.ProblemMatcher, internal: ProblemMatcher): void { let oldBegins = this.createRegularExpression(external.watchedTaskBeginsRegExp); let oldEnds = this.createRegularExpression(external.watchedTaskEndsRegExp); if (oldBegins && oldEnds) { internal.watching = { activeOnStart: false, beginsPattern: { regexp: oldBegins }, endsPattern: { regexp: oldEnds } }; return; } if (Types.isUndefinedOrNull(external.watching)) { return; } let watching = external.watching; let begins: WatchingPattern = this.createWatchingPattern(watching.beginsPattern); let ends: WatchingPattern = this.createWatchingPattern(watching.endsPattern); if (begins && ends) { internal.watching = { activeOnStart: Types.isBoolean(watching.activeOnStart) ? watching.activeOnStart : false, beginsPattern: begins, endsPattern: ends }; return; } if (begins || ends) { this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.problemPattern.watchingMatcher', 'A problem matcher must define both a begin pattern and an end pattern for watching.')); } } private createWatchingPattern(external: string | Config.WatchingPattern): WatchingPattern { if (Types.isUndefinedOrNull(external)) { return null; } let regexp: RegExp; let file: number; if (Types.isString(external)) { regexp = this.createRegularExpression(external); } else { regexp = this.createRegularExpression(external.regexp); if (Types.isNumber(external.file)) { file = external.file; } } if (!regexp) { return null; } return file ? { regexp, file } : { regexp }; } private createRegularExpression(value: string): RegExp { let result: RegExp = null; if (!value) { return result; } try { result = new RegExp(value); } catch (err) { this.status.state = ValidationState.Fatal; this.log(NLS.localize('ProblemMatcherParser.invalidRegexp', 'Error: The string {0} is not a valid regular expression.\n', value)); } return result; } } // let problemMatchersExtPoint = ExtensionsRegistry.registerExtensionPoint<Config.NamedProblemMatcher | Config.NamedProblemMatcher[]>('problemMatchers', { // TODO@Dirk: provide here JSON schema for extension point // }); export class ProblemMatcherRegistry { private matchers: IStringDictionary<ProblemMatcher>; constructor() { this.matchers = Object.create(null); /* problemMatchersExtPoint.setHandler((extensions, collector) => { // TODO@Dirk: validate extensions here and collect errors/warnings in `collector` extensions.forEach(extension => { let extensions = extension.value; if (Types.isArray(extensions)) { (<Config.NamedProblemMatcher[]>extensions).forEach(this.onProblemMatcher, this); } else { this.onProblemMatcher(extensions) } }); }); */ } // private onProblemMatcher(json: Config.NamedProblemMatcher): void { // let logger: ILogger = { // log: (message) => { console.warn(message); } // } // let parser = new ProblemMatcherParser(this, logger); // let result = parser.parse(json); // if (isNamedProblemMatcher(result) && parser.status.isOK()) { // this.add(result.name, result); // } // } public add(name: string, matcher: ProblemMatcher): void { this.matchers[name] = matcher; } public get(name: string): ProblemMatcher { return this.matchers[name]; } public exists(name: string): boolean { return !!this.matchers[name]; } public remove(name: string): void { delete this.matchers[name]; } } export const registry: ProblemMatcherRegistry = new ProblemMatcherRegistry(); registry.add('msCompile', { owner: 'msCompile', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('msCompile') }); registry.add('lessCompile', { owner: 'lessCompile', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('lessCompile'), severity: Severity.Error }); registry.add('tsc', { owner: 'typescript', applyTo: ApplyToKind.closedDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('tsc') }); let matcher = { owner: 'typescript', applyTo: ApplyToKind.closedDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('tsc'), watching: { activeOnStart: true, beginsPattern: { regexp: /^\s*(?:message TS6032:|\d{1,2}:\d{1,2}:\d{1,2}(?: AM| PM)? -) File change detected\. Starting incremental compilation\.\.\./ }, endsPattern: { regexp: /^\s*(?:message TS6042:|\d{1,2}:\d{1,2}:\d{1,2}(?: AM| PM)? -) Compilation complete\. Watching for file changes\./ } } }; (<any>matcher).tscWatch = true; registry.add('tsc-watch', matcher); registry.add('gulp-tsc', { owner: 'typescript', applyTo: ApplyToKind.closedDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('gulp-tsc') }); registry.add('jshint', { owner: 'jshint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('jshint') }); registry.add('jshint-stylish', { owner: 'jshint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('jshint-stylish') }); registry.add('eslint-compact', { owner: 'eslint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('eslint-compact') }); registry.add('eslint-stylish', { owner: 'eslint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('eslint-stylish') });
src/vs/platform/markers/common/problemMatcher.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.9992614388465881, 0.09820624440908432, 0.00016346252232324332, 0.00020961195696145296, 0.2886585593223572 ]
{ "id": 0, "code_window": [ "\t\tloop: true\n", "\t}\n", "];\n", "\n", "export function defaultPattern(name: 'msCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'tsc'): ProblemPattern;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "_defaultPatterns['go'] = {\n", "\tregexp: /^([^:]*: )?((.:)?[^:]*):(\\d+)(:(\\d+))?: (.*)$/,\n", "\tfile: 2,\n", "\tline: 4,\n", "\tcolumn: 6,\n", "\tmessage: 7\n", "};\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 496 }
microsoft-vscode THIRD-PARTY SOFTWARE NOTICES AND INFORMATION Do Not Translate or Localize This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Microsoft received such components are set forth below. Microsoft reserves all rights not expressly granted herein, whether by implication, estoppel or otherwise. 1. Benvie/JavaScriptNext.tmLanguage (https://github.com/Benvie/JavaScriptNext.tmLanguage) 2. chjj-marked version 0.3.2 (https://github.com/npmcomponent/chjj-marked) 3. Colorsublime-Themes version 0.1.0 (https://github.com/Colorsublime/Colorsublime-Themes) 4. davidrios/jade-tmbundle (https://github.com/davidrios/jade-tmbundle) 5. definitelytyped (https://github.com/DefinitelyTyped/DefinitelyTyped) 6. freebroccolo/atom-language-swift (https://github.com/freebroccolo/atom-language-swift) 7. HTML 5.1 W3C Working Draft version 08 October 2015 (http://www.w3.org/TR/2015/WD-html51-20151008/) 8. Ionic documentation version 1.2.4 (https://github.com/driftyco/ionic-site) 9. ionide/ionide-fsharp (https://github.com/ionide/ionide-fsharp) 10. js-beautify version 1.6.2 (https://github.com/beautify-web/js-beautify) 11. Jxck/assert version 1.0.0 (https://github.com/Jxck/assert) 12. language-docker (https://github.com/docker/docker) 13. language-go version 0.39.0 (https://github.com/atom/language-go) 14. language-php version 0.29.0 (https://github.com/atom/language-php) 15. language-rust version 0.4.4 (https://github.com/zargony/atom-language-rust) 16. Microsoft/TypeScript-TmLanguage version 0.0.1 (https://github.com/Microsoft/TypeScript-TmLanguage) 17. mmcgrana/textmate-clojure (https://github.com/mmcgrana/textmate-clojure) 18. octicons-code version 3.1.0 (https://octicons.github.com) 19. octicons-font version 3.1.0 (https://octicons.github.com) 20. string_scorer version 0.1.20 (https://github.com/joshaven/string_score) 21. sublimehq/Packages (https://github.com/sublimehq/Packages) 22. SublimeText/PowerShell (https://github.com/SublimeText/PowerShell) 23. textmate/asp.vb.net.tmbundle (https://github.com/textmate/asp.vb.net.tmbundle) 24. textmate/c.tmbundle (https://github.com/textmate/c.tmbundle) 25. textmate/coffee-script.tmbundle (https://github.com/textmate/coffee-script.tmbundle) 26. textmate/css.tmbundle (https://github.com/textmate/css.tmbundle) 27. textmate/diff.tmbundle (https://github.com/textmate/diff.tmbundle) 28. textmate/git.tmbundle (https://github.com/textmate/git.tmbundle) 29. textmate/groovy.tmbundle (https://github.com/textmate/groovy.tmbundle) 30. textmate/html.tmbundle (https://github.com/textmate/html.tmbundle) 31. textmate/ini.tmbundle (https://github.com/textmate/ini.tmbundle) 32. textmate/java.tmbundle (https://github.com/textmate/java.tmbundle) 33. textmate/javascript.tmbundle (https://github.com/textmate/javascript.tmbundle) 34. textmate/less.tmbundle (https://github.com/textmate/less.tmbundle) 35. textmate/lua.tmbundle (https://github.com/textmate/lua.tmbundle) 36. textmate/make.tmbundle (https://github.com/textmate/make.tmbundle) 37. textmate/objective-c.tmbundle (https://github.com/textmate/objective-c.tmbundle) 38. textmate/perl.tmbundle (https://github.com/textmate/perl.tmbundle) 39. textmate/php.tmbundle (https://github.com/textmate/php.tmbundle) 40. textmate/python.tmbundle (https://github.com/textmate/python.tmbundle) 41. textmate/r.tmbundle (https://github.com/textmate/r.tmbundle) 42. textmate/ruby.tmbundle (https://github.com/textmate/ruby.tmbundle) 43. textmate/shellscript.tmbundle (https://github.com/textmate/shellscript.tmbundle) 44. textmate/sql.tmbundle (https://github.com/textmate/sql.tmbundle) 45. textmate/xml.tmbundle (https://github.com/textmate/xml.tmbundle) 46. textmate/yaml.tmbundle (https://github.com/textmate/yaml.tmbundle) 47. typescript version 1.5 (https://github.com/Microsoft/TypeScript) 48. typescript version 1.8.2 (https://github.com/Microsoft/TypeScript) 49. typescript-sublime-plugin version 0.1.8 (https://github.com/Microsoft/TypeScript-TmLanguage) 50. unity-shader-files version 0.1.0 (https://github.com/nashella/unity-shader-files) 51. vscode-swift version 0.0.1 (https://github.com/owensd/vscode-swift) %% Benvie/JavaScriptNext.tmLanguage NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2015 simonzack, zertosh, benvie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF Benvie/JavaScriptNext.tmLanguage NOTICES AND INFORMATION %% chjj-marked NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2011-2014, Christopher Jeffrey (https://github.com/chjj/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF chjj-marked NOTICES AND INFORMATION %% Colorsublime-Themes NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) 2015 Colorsublime.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF Colorsublime-Themes NOTICES AND INFORMATION %% davidrios/jade-tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2014 David Rios Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE ========================================= END OF davidrios/jade-tmbundle NOTICES AND INFORMATION %% definitelytyped NOTICES AND INFORMATION BEGIN HERE ========================================= This project is licensed under the MIT license. Copyrights are respective of each contributor listed at the beginning of each definition file. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF definitelytyped NOTICES AND INFORMATION %% freebroccolo/atom-language-swift NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2014 Darin Morrison Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF freebroccolo/atom-language-swift NOTICES AND INFORMATION %% HTML 5.1 W3C Working Draft NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). This software or document includes material copied from or derived from HTML 5.1 W3C Working Draft (http://www.w3.org/TR/2015/WD-html51-20151008/.) THIS DOCUMENT IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF. The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to this document or its contents without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders. ========================================= END OF HTML 5.1 W3C Working Draft NOTICES AND INFORMATION %% Ionic documentation NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright Drifty Co. http://drifty.com/. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ========================================= END OF Ionic documentation NOTICES AND INFORMATION %% ionide/ionide-fsharp NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2015 Krzysztof Cieslak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF ionide/ionide-fsharp NOTICES AND INFORMATION %% js-beautify NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2007-2013 Einar Lielmanis and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF js-beautify NOTICES AND INFORMATION %% Jxck/assert NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2011 Jxck Originally from node.js (http://nodejs.org) Copyright Joyent, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF Jxck/assert NOTICES AND INFORMATION %% language-docker NOTICES AND INFORMATION BEGIN HERE ========================================= Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2013-2016 Docker, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ========================================= END OF language-docker NOTICES AND INFORMATION %% language-go NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2014 GitHub Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This package was derived from a TextMate bundle located at https://github.com/rsms/Go.tmbundle and distributed under the following license, located in `LICENSE`: Copyright (c) 2009 Rasmus Andersson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The Go Template grammar was derived from GoSublime located at https://github.com/DisposaBoy/GoSublime and distributed under the following license, located in `LICENSE.md`: Copyright (c) 2012 The GoSublime Authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF language-go NOTICES AND INFORMATION %% language-php NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2014 GitHub Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This package was derived from a TextMate bundle located at https://github.com/textmate/php.tmbundle and distributed under the following license, located in `README.mdown`: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. ========================================= END OF language-php NOTICES AND INFORMATION %% language-rust NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright © `2013` `Andreas Neuhaus` `http://zargony.com/` Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF language-rust NOTICES AND INFORMATION %% Microsoft/TypeScript-TmLanguage NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) Microsoft Corporation. All rights reserved. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ========================================= END OF Microsoft/TypeScript-TmLanguage NOTICES AND INFORMATION %% mmcgrana/textmate-clojure NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2010- Mark McGranaghan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF mmcgrana/textmate-clojure NOTICES AND INFORMATION %% octicons-code NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) (c) 2012-2015 GitHub Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF octicons-code NOTICES AND INFORMATION %% octicons-font NOTICES AND INFORMATION BEGIN HERE ========================================= (c) 2012-2015 GitHub SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ========================================= END OF octicons-font NOTICES AND INFORMATION %% string_scorer NOTICES AND INFORMATION BEGIN HERE ========================================= This software is released under the MIT license: Copyright (c) Joshaven Potter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF string_scorer NOTICES AND INFORMATION %% sublimehq/Packages NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) Sublime Packages project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF sublimehq/Packages NOTICES AND INFORMATION %% SublimeText/PowerShell NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2011 Guillermo López-Anglada Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF SublimeText/PowerShell NOTICES AND INFORMATION %% textmate/asp.vb.net.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-asp.vb.net.tmbundle project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/asp.vb.net.tmbundle NOTICES AND INFORMATION %% textmate/c.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-c.tmbundle authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/c.tmbundle NOTICES AND INFORMATION %% textmate/coffee-script.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2009-2014 Jeremy Ashkenas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF textmate/coffee-script.tmbundle NOTICES AND INFORMATION %% textmate/css.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-css.tmbundle project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/css.tmbundle NOTICES AND INFORMATION %% textmate/diff.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-diff.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/diff.tmbundle NOTICES AND INFORMATION %% textmate/git.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2008 Tim Harper Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the" Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF textmate/git.tmbundle NOTICES AND INFORMATION %% textmate/groovy.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-groovy.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/groovy.tmbundle NOTICES AND INFORMATION %% textmate/html.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-html.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/html.tmbundle NOTICES AND INFORMATION %% textmate/ini.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-ini.tmbundle project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/ini.tmbundle NOTICES AND INFORMATION %% textmate/java.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-java.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/java.tmbundle NOTICES AND INFORMATION %% textmate/javascript.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-javascript.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/javascript.tmbundle NOTICES AND INFORMATION %% textmate/less.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2010 Scott Kyle and Rasmus Andersson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF textmate/less.tmbundle NOTICES AND INFORMATION %% textmate/lua.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-lua.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/lua.tmbundle NOTICES AND INFORMATION %% textmate/make.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-make.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/make.tmbundle NOTICES AND INFORMATION %% textmate/objective-c.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-objective-c.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/objective-c.tmbundle NOTICES AND INFORMATION %% textmate/perl.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-perl.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/perl.tmbundle NOTICES AND INFORMATION %% textmate/php.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-php.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/php.tmbundle NOTICES AND INFORMATION %% textmate/python.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-python.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/python.tmbundle NOTICES AND INFORMATION %% textmate/r.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-r.tmbundle project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. ========================================= END OF textmate/r.tmbundle NOTICES AND INFORMATION %% textmate/ruby.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-ruby.tmbundle project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/ruby.tmbundle NOTICES AND INFORMATION %% textmate/shellscript.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-shellscript.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/shellscript.tmbundle NOTICES AND INFORMATION %% textmate/sql.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-sql.tmbundle project authors If not otherwise specified (see below), files in this folder fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/sql.tmbundle NOTICES AND INFORMATION %% textmate/xml.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-xml.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/xml.tmbundle NOTICES AND INFORMATION %% textmate/yaml.tmbundle NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) textmate-yaml.tmbundle project authors If not otherwise specified (see below), files in this repository fall under the following license: Permission to copy, use, modify, sell and distribute this software is granted. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. An exception is made for files in readable text which contain their own license information, or files where an accompanying file exists (in the same directory) with a "-license" suffix added to the base-name name of the original file, and an extension of txt, html, or similar. For example "tidy" is accompanied by "tidy-license.txt". ========================================= END OF textmate/yaml.tmbundle NOTICES AND INFORMATION %% typescript NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) Microsoft Corporation. All rights reserved. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ========================================= END OF typescript NOTICES AND INFORMATION %% typescript NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) Microsoft Corporation. All rights reserved. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ========================================= END OF typescript NOTICES AND INFORMATION %% typescript-sublime-plugin NOTICES AND INFORMATION BEGIN HERE ========================================= Copyright (c) Microsoft Corporation. All rights reserved. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ========================================= END OF typescript-sublime-plugin NOTICES AND INFORMATION %% unity-shader-files NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2014 Teddy Bradford (for original ./Grammars/shaderlab.cson file) Copyright (c) 2015 Nadège Michel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF unity-shader-files NOTICES AND INFORMATION %% vscode-swift NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2015 David Owens II Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF vscode-swift NOTICES AND INFORMATION
ThirdPartyNotices.txt
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00020011933520436287, 0.0001722188462736085, 0.0001613829081179574, 0.00017246232891920954, 0.000004030399850307731 ]
{ "id": 0, "code_window": [ "\t\tloop: true\n", "\t}\n", "];\n", "\n", "export function defaultPattern(name: 'msCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'tsc'): ProblemPattern;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "_defaultPatterns['go'] = {\n", "\tregexp: /^([^:]*: )?((.:)?[^:]*):(\\d+)(:(\\d+))?: (.*)$/,\n", "\tfile: 2,\n", "\tline: 4,\n", "\tcolumn: 6,\n", "\tmessage: 7\n", "};\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 496 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import nls = require('vs/nls'); import {TPromise} from 'vs/base/common/winjs.base'; import paths = require('vs/base/common/paths'); import encoding = require('vs/base/node/encoding'); import errors = require('vs/base/common/errors'); import strings = require('vs/base/common/strings'); import uri from 'vs/base/common/uri'; import timer = require('vs/base/common/timer'); import {IFileService, IFilesConfiguration, IResolveFileOptions, IFileStat, IContent, IImportResult, IResolveContentOptions, IUpdateContentOptions} from 'vs/platform/files/common/files'; import {FileService as NodeFileService, IFileServiceOptions, IEncodingOverride} from 'vs/workbench/services/files/node/fileService'; import {IConfigurationService, IConfigurationServiceEvent, ConfigurationServiceEventTypes} from 'vs/platform/configuration/common/configuration'; import {IEventService} from 'vs/platform/event/common/event'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {shell} from 'electron'; export class FileService implements IFileService { public serviceId = IFileService; private raw: IFileService; private configurationChangeListenerUnbind: () => void; constructor( private configurationService: IConfigurationService, private eventService: IEventService, private contextService: IWorkspaceContextService ) { const configuration = this.configurationService.getConfiguration<IFilesConfiguration>(); // adjust encodings (TODO@Ben knowledge on settings location ('.vscode') is hardcoded) let encodingOverride: IEncodingOverride[] = []; encodingOverride.push({ resource: uri.file(this.contextService.getConfiguration().env.appSettingsHome), encoding: encoding.UTF8 }); if (this.contextService.getWorkspace()) { encodingOverride.push({ resource: uri.file(paths.join(this.contextService.getWorkspace().resource.fsPath, '.vscode')), encoding: encoding.UTF8 }); } let watcherIgnoredPatterns: string[] = []; if (configuration.files && configuration.files.watcherExclude) { watcherIgnoredPatterns = Object.keys(configuration.files.watcherExclude).filter(k => !!configuration.files.watcherExclude[k]); } // build config let fileServiceConfig: IFileServiceOptions = { errorLogger: (msg: string) => errors.onUnexpectedError(msg), encoding: configuration.files && configuration.files.encoding, encodingOverride: encodingOverride, watcherIgnoredPatterns: watcherIgnoredPatterns, verboseLogging: this.contextService.getConfiguration().env.verboseLogging }; // create service let workspace = this.contextService.getWorkspace(); this.raw = new NodeFileService(workspace ? workspace.resource.fsPath : void 0, this.eventService, fileServiceConfig); // Listeners this.registerListeners(); } private registerListeners(): void { // Config Changes this.configurationChangeListenerUnbind = this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, (e: IConfigurationServiceEvent) => this.onConfigurationChange(e.config)); } private onConfigurationChange(configuration: IFilesConfiguration): void { this.updateOptions(configuration.files); } public updateOptions(options: any): void { this.raw.updateOptions(options); } public resolveFile(resource: uri, options?: IResolveFileOptions): TPromise<IFileStat> { return this.raw.resolveFile(resource, options); } public resolveContent(resource: uri, options?: IResolveContentOptions): TPromise<IContent> { let contentId = resource.toString(); let timerEvent = timer.start(timer.Topic.WORKBENCH, strings.format('Load {0}', contentId)); return this.raw.resolveContent(resource, options).then((result) => { timerEvent.stop(); return result; }); } public resolveContents(resources: uri[]): TPromise<IContent[]> { return this.raw.resolveContents(resources); } public updateContent(resource: uri, value: string, options?: IUpdateContentOptions): TPromise<IFileStat> { let timerEvent = timer.start(timer.Topic.WORKBENCH, strings.format('Save {0}', resource.toString())); return this.raw.updateContent(resource, value, options).then((result) => { timerEvent.stop(); return result; }, (error) => { timerEvent.stop(); return TPromise.wrapError(error); }); } public moveFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> { return this.raw.moveFile(source, target, overwrite); } public copyFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> { return this.raw.copyFile(source, target, overwrite); } public createFile(resource: uri, content?: string): TPromise<IFileStat> { return this.raw.createFile(resource, content); } public createFolder(resource: uri): TPromise<IFileStat> { return this.raw.createFolder(resource); } public rename(resource: uri, newName: string): TPromise<IFileStat> { return this.raw.rename(resource, newName); } public del(resource: uri, useTrash?: boolean): TPromise<void> { if (useTrash) { return this.doMoveItemToTrash(resource); } return this.raw.del(resource); } private doMoveItemToTrash(resource: uri): TPromise<void> { let workspace = this.contextService.getWorkspace(); if (!workspace) { return TPromise.wrapError<void>('Need a workspace to use this'); } let absolutePath = resource.fsPath; let result = shell.moveItemToTrash(absolutePath); if (!result) { return TPromise.wrapError<void>(new Error(nls.localize('trashFailed', "Failed to move '{0}' to the trash", paths.basename(absolutePath)))); } return TPromise.as(null); } public importFile(source: uri, targetFolder: uri): TPromise<IImportResult> { return this.raw.importFile(source, targetFolder).then((result) => { return <IImportResult>{ isNew: result && result.isNew, stat: result && result.stat }; }); } public watchFileChanges(resource: uri): void { if (!resource) { return; } if (resource.scheme !== 'file') { return; // only support files } // return early if the resource is inside the workspace for which we have another watcher in place if (this.contextService.isInsideWorkspace(resource)) { return; } this.raw.watchFileChanges(resource); } public unwatchFileChanges(resource: uri): void; public unwatchFileChanges(path: string): void; public unwatchFileChanges(arg1: any): void { this.raw.unwatchFileChanges(arg1); } public dispose(): void { // Listeners if (this.configurationChangeListenerUnbind) { this.configurationChangeListenerUnbind(); this.configurationChangeListenerUnbind = null; } // Dispose service this.raw.dispose(); } }
src/vs/workbench/services/files/electron-browser/fileService.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.0001812543487176299, 0.00017380944336764514, 0.00016933403094299138, 0.00017336435848847032, 0.0000025961915071093244 ]
{ "id": 0, "code_window": [ "\t\tloop: true\n", "\t}\n", "];\n", "\n", "export function defaultPattern(name: 'msCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'tsc'): ProblemPattern;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "_defaultPatterns['go'] = {\n", "\tregexp: /^([^:]*: )?((.:)?[^:]*):(\\d+)(:(\\d+))?: (.*)$/,\n", "\tfile: 2,\n", "\tline: 4,\n", "\tcolumn: 6,\n", "\tmessage: 7\n", "};\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 496 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "activateBreakpoints": "Activar puntos de interrupción", "addConditionalBreakpoint": "Agregar punto de interrupción condicional", "addFunctionBreakpoint": "Agregar punto de interrupción de función", "addToWatchExpressions": "Agregar a inspección", "addWatchExpression": "Agregar expresión", "clearRepl": "Borrar consola", "continueDebug": "Continuar", "copyValue": "Copiar valor", "deactivateBreakpoints": "Desactivar puntos de interrupción", "debugActionLabelAndKeybinding": "{0} ({1})", "disableAllBreakpoints": "Deshabilitar todos los puntos de interrupción", "disconnectDebug": "Desconectar", "editConditionalBreakpoint": "Editar punto de interrupción", "enableAllBreakpoints": "Habilitar todos los puntos de interrupción", "openLaunchJson": "Abrir {0}", "pauseDebug": "Pausar", "reapplyAllBreakpoints": "Volver a aplicar todos los puntos de interrupción", "reconnectDebug": "Volver a conectar", "removeAllBreakpoints": "Quitar todos los puntos de interrupción", "removeAllWatchExpressions": "Quitar todas las expresiones", "removeBreakpoint": "Quitar punto de interrupción", "removeWatchExpression": "Quitar expresión", "renameFunctionBreakpoint": "Cambiar nombre de punto de interrupción de función", "renameWatchExpression": "Cambiar nombre de expresión", "restartDebug": "Reiniciar", "run": "Ejecutar", "selectConfig": "Seleccionar configuración", "startDebug": "Iniciar", "stepIntoDebug": "Depurar paso a paso por instrucciones", "stepOutDebug": "Salir de la depuración", "stepOverDebug": "Depurar paso a paso por procedimientos", "stopDebug": "Detener", "toggleEnablement": "Habilitar/Deshabilitar punto de interrupción", "toggleRepl": "Consola de depuración" }
i18n/esn/src/vs/workbench/parts/debug/electron-browser/debugActions.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00018125450878869742, 0.0001735011173877865, 0.0001696774852462113, 0.0001714191457722336, 0.000004297425221011508 ]
{ "id": 1, "code_window": [ "export function defaultPattern(name: 'csc'): ProblemPattern;\n", "export function defaultPattern(name: 'vb'): ProblemPattern;\n", "export function defaultPattern(name: 'lessCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint'): ProblemPattern;\n", "export function defaultPattern(name: 'gulp-tsc'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint-stylish'): ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[] {\n", "\treturn _defaultPatterns[name];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function defaultPattern(name: 'go'): ProblemPattern;\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 505 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/task.contribution'; import 'vs/workbench/parts/tasks/browser/taskQuickOpen'; import * as nls from 'vs/nls'; import * as Env from 'vs/base/common/flags'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import Severity from 'vs/base/common/severity'; import * as Objects from 'vs/base/common/objects'; import { IStringDictionary } from 'vs/base/common/collections'; import { Action } from 'vs/base/common/actions'; import * as Dom from 'vs/base/browser/dom'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { EventEmitter, ListenerUnbind } from 'vs/base/common/eventEmitter'; import * as Builder from 'vs/base/browser/builder'; import * as Types from 'vs/base/common/types'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { match } from 'vs/base/common/glob'; import { setTimeout } from 'vs/base/common/platform'; import { TerminateResponse } from 'vs/base/common/processes'; import { Registry } from 'vs/platform/platform'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IEventService } from 'vs/platform/event/common/event'; import { IEditor } from 'vs/platform/editor/common/editor'; import { IMessageService } from 'vs/platform/message/common/message'; import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration'; import { IFileService, FileChangesEvent, FileChangeType, EventType as FileEventType } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/platform/extensions/common/extensions'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry'); import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry'; import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService'; import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables'; import { ITextFileService, EventType } from 'vs/workbench/parts/files/common/files'; import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/parts/output/common/output'; import { ITaskSystem, ITaskSummary, ITaskRunResult, TaskError, TaskErrors, TaskConfiguration, TaskDescription, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem'; import { ITaskService, TaskServiceEvents } from 'vs/workbench/parts/tasks/common/taskService'; import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates'; import { LanguageServiceTaskSystem, LanguageServiceTaskConfiguration } from 'vs/workbench/parts/tasks/common/languageServiceTaskSystem'; import * as FileConfig from 'vs/workbench/parts/tasks/node/processRunnerConfiguration'; import { ProcessRunnerSystem } from 'vs/workbench/parts/tasks/node/processRunnerSystem'; import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector'; let $ = Builder.$; class AbstractTaskAction extends Action { protected taskService: ITaskService; protected telemetryService: ITelemetryService; constructor(id:string, label:string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label); this.taskService = taskService; this.telemetryService = telemetryService; } } class BuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.build'; public static TEXT = nls.localize('BuildAction.label','Run Build Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.build(); } } class TestAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.test'; public static TEXT = nls.localize('TestAction.label','Run Test Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.runTest(); } } class RebuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.rebuild'; public static TEXT = nls.localize('RebuildAction.label', 'Run Rebuild Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.rebuild(); } } class CleanAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.clean'; public static TEXT = nls.localize('CleanAction.label', 'Run Clean Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.clean(); } } class ConfigureTaskRunnerAction extends Action { public static ID = 'workbench.action.tasks.configureTaskRunner'; public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', 'Configure Task Runner'); private configurationService: IConfigurationService; private fileService: IFileService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private outputService: IOutputService; private messageService: IMessageService; private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(id, label); this.configurationService = configurationService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.outputService = outputService; this.messageService = messageService; this.quickOpenService = quickOpenService; } public run(event?:any): TPromise<IEditor> { if (!this.contextService.getWorkspace()) { this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.')); return TPromise.as(undefined); } let sideBySide = !!(event && (event.ctrlKey || event.metaKey)); return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => { return success; }, (err:any) => { ; return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner')}).then(selection => { if (!selection) { return undefined; } let contentPromise: TPromise<string>; if (selection.autoDetect) { this.outputService.showOutput(TaskService.OutputChannel); this.outputService.append(TaskService.OutputChannel, nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n'); let detector = new ProcessRunnerDetector(this.fileService, this.contextService, new SystemVariables(this.editorService, this.contextService)); contentPromise = detector.detect(false, selection.id).then((value) => { let config = value.config; if (value.stderr && value.stderr.length > 0) { value.stderr.forEach((line) => { this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.')); return selection.content; } else if (config) { if (value.stdout && value.stdout.length > 0) { value.stdout.forEach(line => this.outputService.append(TaskService.OutputChannel, line + '\n')); } let content = JSON.stringify(config, null, '\t'); content = [ '{', '\t// See http://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', ].join('\n') + content.substr(1); return content; } else { return selection.content; } }); } else { contentPromise = TPromise.as(selection.content); } return contentPromise.then(content => { return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content); }); }); }).then((stat) => { if (!stat) { return undefined; } // // (2) Open editor with configuration file return this.editorService.openEditor({ resource: stat.resource, options: { forceOpen: true } }, sideBySide); }, (error) => { throw new Error(nls.localize('ConfigureTaskRunnerAction.failed', "Unable to create the 'tasks.json' file inside the '.vscode' folder. Consult the task output for details.")); }); } } class CloseMessageAction extends Action { public static ID = 'workbench.action.build.closeMessage'; public static TEXT = nls.localize('CloseMessageAction.label', 'Close'); public closeFunction: () => void; constructor() { super(CloseMessageAction.ID, CloseMessageAction.TEXT); } public run(): Promise { if (this.closeFunction) { this.closeFunction(); } return TPromise.as(null); } } class TerminateAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.terminate'; public static TEXT = nls.localize('TerminateAction.label', 'Terminate Running Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.isActive().then((active) => { if (active) { return this.taskService.terminate().then((response) => { if (response.success) { return; } else { return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task')); } }); } }); } } class ShowLogAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.showLog'; public static TEXT = nls.localize('ShowLogAction.label', 'Show Task Log'); private outputService: IOutputService; constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService, @IOutputService outputService:IOutputService) { super(id, label, taskService, telemetryService); this.outputService = outputService; } public run(): Promise { return this.outputService.showOutput(TaskService.OutputChannel); } } class RunTaskAction extends Action { public static ID = 'workbench.action.tasks.runTask'; public static TEXT = nls.localize('RunTaskAction.label', "Run Task"); private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IQuickOpenService quickOpenService:IQuickOpenService) { super(id, label); this.quickOpenService = quickOpenService; } public run(event?:any): Promise { this.quickOpenService.show('task '); return TPromise.as(null); } } class StatusBarItem implements IStatusbarItem { private quickOpenService: IQuickOpenService; private markerService: IMarkerService; private taskService:ITaskService; private outputService: IOutputService; private intervalToken: any; private activeCount: number; private static progressChars:string = '|/-\\'; constructor(@IQuickOpenService quickOpenService:IQuickOpenService, @IMarkerService markerService:IMarkerService, @IOutputService outputService:IOutputService, @ITaskService taskService:ITaskService) { this.quickOpenService = quickOpenService; this.markerService = markerService; this.outputService = outputService; this.taskService = taskService; this.activeCount = 0; } public render(container: HTMLElement): IDisposable { let callOnDispose: IDisposable[] = [], element = document.createElement('div'), // icon = document.createElement('a'), progress = document.createElement('div'), label = document.createElement('a'), error = document.createElement('div'), warning = document.createElement('div'), info = document.createElement('div'); Dom.addClass(element, 'task-statusbar-item'); // dom.addClass(icon, 'task-statusbar-item-icon'); // element.appendChild(icon); Dom.addClass(progress, 'task-statusbar-item-progress'); element.appendChild(progress); progress.innerHTML = StatusBarItem.progressChars[0]; $(progress).hide(); Dom.addClass(label, 'task-statusbar-item-label'); element.appendChild(label); Dom.addClass(error, 'task-statusbar-item-label-error'); error.innerHTML = '0'; label.appendChild(error); Dom.addClass(warning, 'task-statusbar-item-label-warning'); warning.innerHTML = '0'; label.appendChild(warning); Dom.addClass(info, 'task-statusbar-item-label-info'); label.appendChild(info); $(info).hide(); // callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => { // this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true); // })); callOnDispose.push(Dom.addDisposableListener(label, 'click', (e:MouseEvent) => { this.quickOpenService.show('!'); })); let updateStatus = (element:HTMLDivElement, stats:number): boolean => { if (stats > 0) { element.innerHTML = stats.toString(); $(element).show(); return true; } else { $(element).hide(); return false; } }; let manyMarkers = nls.localize('manyMarkers', "99+"); let updateLabel = (stats: MarkerStatistics) => { error.innerHTML = stats.errors < 100 ? stats.errors.toString() : manyMarkers; warning.innerHTML = stats.warnings < 100 ? stats.warnings.toString() : manyMarkers; updateStatus(info, stats.infos); }; this.markerService.onMarkerChanged((changedResources) => { updateLabel(this.markerService.getStatistics()); }); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => { this.activeCount++; if (this.activeCount === 1) { let index = 1; let chars = StatusBarItem.progressChars; progress.innerHTML = chars[0]; this.intervalToken = setInterval(() => { progress.innerHTML = chars[index]; index++; if (index >= chars.length) { index = 0; } }, 50); $(progress).show(); } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data:TaskServiceEventData) => { this.activeCount--; if (this.activeCount === 0) { $(progress).hide(); clearInterval(this.intervalToken); this.intervalToken = null; } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => { if (this.activeCount !== 0) { $(progress).hide(); if (this.intervalToken) { clearInterval(this.intervalToken); this.intervalToken = null; } this.activeCount = 0; } })); container.appendChild(element); return { dispose: () => { callOnDispose = dispose(callOnDispose); } }; } } interface TaskServiceEventData { error?: any; } class TaskService extends EventEmitter implements ITaskService { public serviceId = ITaskService; public static SERVICE_ID: string = 'taskService'; public static OutputChannel:string = 'Tasks'; private modeService: IModeService; private configurationService: IConfigurationService; private markerService: IMarkerService; private outputService: IOutputService; private messageService: IMessageService; private fileService: IFileService; private telemetryService: ITelemetryService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private textFileService: ITextFileService; private eventService: IEventService; private modelService: IModelService; private extensionService: IExtensionService; private quickOpenService: IQuickOpenService; private _taskSystemPromise: TPromise<ITaskSystem>; private _taskSystem: ITaskSystem; private taskSystemListeners: ListenerUnbind[]; private clearTaskSystemPromise: boolean; private fileChangesListener: ListenerUnbind; constructor(@IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService, @IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService:IWorkbenchEditorService, @IFileService fileService:IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService:ITextFileService, @ILifecycleService lifecycleService: ILifecycleService, @IEventService eventService: IEventService, @IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(); this.modeService = modeService; this.configurationService = configurationService; this.markerService = markerService; this.outputService = outputService; this.messageService = messageService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.telemetryService = telemetryService; this.textFileService = textFileService; this.eventService = eventService; this.modelService = modelService; this.extensionService = extensionService; this.quickOpenService = quickOpenService; this.taskSystemListeners = []; this.clearTaskSystemPromise = false; this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, () => { this.emit(TaskServiceEvents.ConfigChanged); if (this._taskSystem && this._taskSystem.isActiveSync()) { this.clearTaskSystemPromise = true; } else { this._taskSystem = null; this._taskSystemPromise = null; } this.disposeTaskSystemListeners(); }); lifecycleService.addBeforeShutdownParticipant(this); } private disposeTaskSystemListeners(): void { this.taskSystemListeners.forEach(unbind => unbind()); this.taskSystemListeners = []; } private disposeFileChangesListener(): void { if (this.fileChangesListener) { this.fileChangesListener(); this.fileChangesListener = null; } } private get taskSystemPromise(): TPromise<ITaskSystem> { if (!this._taskSystemPromise) { let variables = new SystemVariables(this.editorService, this.contextService); let clearOutput = true; this._taskSystemPromise = TPromise.as(this.configurationService.getConfiguration<TaskConfiguration>('tasks')).then((config: TaskConfiguration) => { let parseErrors: string[] = config ? (<any>config).$parseErrors : null; if (parseErrors) { let isAffected = false; for (let i = 0; i < parseErrors.length; i++) { if (/tasks\.json$/.test(parseErrors[i])) { isAffected = true; break; } } if (isAffected) { this.outputService.append(TaskService.OutputChannel, nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n')); this.outputService.showOutput(TaskService.OutputChannel, true); return TPromise.wrapError({}); } } let configPromise: TPromise<TaskConfiguration>; if (config) { if (this.isRunnerConfig(config) && this.hasDetectorSupport(<FileConfig.ExternalTaskRunnerConfiguration>config)) { let fileConfig = <FileConfig.ExternalTaskRunnerConfiguration>config; configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables, fileConfig).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); let detectedConfig = value.config; if (!detectedConfig) { return config; } let result: FileConfig.ExternalTaskRunnerConfiguration = Objects.clone(fileConfig); let configuredTasks: IStringDictionary<FileConfig.TaskDescription> = Object.create(null); if (!result.tasks) { if (detectedConfig.tasks) { result.tasks = detectedConfig.tasks; } } else { result.tasks.forEach(task => configuredTasks[task.taskName] = task); detectedConfig.tasks.forEach((task) => { if (!configuredTasks[task.taskName]) { result.tasks.push(task); } }); } return result; }); } else { configPromise = TPromise.as<TaskConfiguration>(config); } } else { configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); return value.config; }); } return configPromise.then((config) => { if (!config) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noConfiguration', 'No task runner configured.'), TaskErrors.NotConfigured); } let result: ITaskSystem = null; if (config.buildSystem === 'service') { result = new LanguageServiceTaskSystem(<LanguageServiceTaskConfiguration>config, this.telemetryService, this.modeService); } else if (this.isRunnerConfig(config)) { result = new ProcessRunnerSystem(<FileConfig.ExternalTaskRunnerConfiguration>config, variables, this.markerService, this.modelService, this.telemetryService, this.outputService, TaskService.OutputChannel, clearOutput); } if (result === null) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noBuildType', "No valid task runner configured. Supported task runners are 'service' and 'program'."), TaskErrors.NoValidTaskRunner); } this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event))); this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event))); this._taskSystem = result; return result; }, (err: any) => { this.handleError(err); return Promise.wrapError(err); }); }); } return this._taskSystemPromise; } private printStderr(stderr: string[]): boolean { let result = true; if (stderr && stderr.length > 0) { stderr.forEach((line) => { result = false; this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.outputService.showOutput(TaskService.OutputChannel, true); } return result; } private isRunnerConfig(config: TaskConfiguration): boolean { return !config.buildSystem || config.buildSystem === 'program'; } private hasDetectorSupport(config: FileConfig.ExternalTaskRunnerConfiguration): boolean { if (!config.command) { return false; } return ProcessRunnerDetector.supports(config.command); } public configureAction(): Action { return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this.configurationService, this.editorService, this.fileService, this.contextService, this.outputService, this.messageService, this.quickOpenService); } public build(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.build()); } public rebuild(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.rebuild()); } public clean(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.clean()); } public runTest(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.runTest()); } public run(taskIdentifier: string): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.run(taskIdentifier)); } private executeTarget(fn: (taskSystem: ITaskSystem) => ITaskRunResult): TPromise<ITaskSummary> { return this.textFileService.saveAll().then((value) => { return this.taskSystemPromise. then((taskSystem) => { return taskSystem.isActive().then((active) => { if (!active) { return fn(taskSystem); } else { throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask); } }); }). then((runResult: ITaskRunResult) => { if (runResult.restartOnFileChanges) { let pattern = runResult.restartOnFileChanges; this.fileChangesListener = this.eventService.addListener(FileEventType.FILE_CHANGES, (event: FileChangesEvent) => { let needsRestart = event.changes.some((change) => { return (change.type === FileChangeType.ADDED || change.type === FileChangeType.DELETED) && !!match(pattern, change.resource.fsPath); }); if (needsRestart) { this.terminate().done(() => { // We need to give the child process a change to stop. setTimeout(() => { this.executeTarget(fn); }, 2000); }); } }); } return runResult.promise.then((value) => { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } return value; }); }, (err: any) => { this.handleError(err); }); }); } public isActive(): TPromise<boolean> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => taskSystem.isActive()); } return TPromise.as(false); } public terminate(): TPromise<TerminateResponse> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => { return taskSystem.terminate(); }).then(response => { if (response.success) { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } this.emit(TaskServiceEvents.Terminated, {}); this.disposeFileChangesListener(); } return response; }); } return TPromise.as( { success: true} ); } public tasks(): TPromise<TaskDescription[]> { return this.taskSystemPromise.then(taskSystem => taskSystem.tasks()); } public beforeShutdown(): boolean | TPromise<boolean> { if (this._taskSystem && this._taskSystem.isActiveSync()) { if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({ message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'), primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task") })) { return this._taskSystem.terminate().then((response) => { if (response.success) { this.emit(TaskServiceEvents.Terminated, {}); this._taskSystem = null; this.disposeFileChangesListener(); this.disposeTaskSystemListeners(); return false; // no veto } return true; // veto }, (err) => { return true; // veto }); } else { return true; // veto } } return false; // Nothing to do here } private handleError(err:any):void { let showOutput = true; if (err instanceof TaskError) { let buildError = <TaskError>err; let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask; let needsTerminate = buildError.code === TaskErrors.RunningTask; if (needsConfig || needsTerminate) { let closeAction = new CloseMessageAction(); let action = needsConfig ? this.configureAction() : new TerminateAction(TerminateAction.ID, TerminateAction.TEXT, this, this.telemetryService); closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [closeAction, action ] }); } else { this.messageService.show(buildError.severity, buildError.message); } } else if (err instanceof Error) { let error = <Error>err; this.messageService.show(Severity.Error, error.message); } else if (Types.isString(err)) { this.messageService.show(Severity.Error, <string>err); } else { this.messageService.show(Severity.Error, nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.')); } if (showOutput) { this.outputService.showOutput(TaskService.OutputChannel, true); } } } export class TaskServiceParticipant implements IWorkbenchContribution { constructor(@IInstantiationService private instantiationService: IInstantiationService) { // Force loading the language worker service this.instantiationService.getInstance(ITaskService); } public getId(): string { return 'vs.taskService'; } } let tasksCategory = nls.localize('tasksCategory', "Tasks"); let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), tasksCategory); if (Env.enableTasks) { // Task Service registerSingleton(ITaskService, TaskService); // Actions workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(BuildAction, BuildAction.ID, BuildAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TestAction, TestAction.ID, TestAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_T }), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RebuildAction, RebuildAction.ID, RebuildAction.TEXT), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CleanAction, CleanAction.ID, CleanAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TerminateAction, TerminateAction.ID, TerminateAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowLogAction, ShowLogAction.ID, ShowLogAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RunTaskAction, RunTaskAction.ID, RunTaskAction.TEXT), tasksCategory); // Register Quick Open (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( 'vs/workbench/parts/tasks/browser/taskQuickOpen', 'QuickOpenHandler', 'task ', nls.localize('taskCommands', "Run Task") ) ); // Status bar let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar); statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */)); // Output channel let outputChannelRegistry = <IOutputChannelRegistry>Registry.as(OutputExt.OutputChannels); outputChannelRegistry.registerChannel(TaskService.OutputChannel); (<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench)).registerWorkbenchContribution(TaskServiceParticipant); // tasks.json validation let schemaId = 'vscode://schemas/tasks'; let schema : IJSONSchema = { 'id': schemaId, 'description': 'Task definition file', 'type': 'object', 'default': { 'version': '0.1.0', 'command': 'myCommand', 'isShellCommand': false, 'args': [], 'showOutput': 'always', 'tasks': [ { 'taskName': 'build', 'showOutput': 'silent', 'isBuildCommand': true, 'problemMatcher': ['$tsc', '$lessCompile'] } ] }, 'definitions': { 'showOutputType': { 'type': 'string', 'enum': ['always', 'silent', 'never'], 'default': 'silent' }, 'patternType': { 'anyOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/pattern' }, { 'type': 'array', 'items': { '$ref': '#/definitions/pattern' } } ] }, 'pattern': { 'default': { 'regexp': '^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$', 'file': 1, 'location': 2, 'message': 3 }, 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.pattern.regexp', 'The regular expression to find an error, warning or info in the output.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.file', 'The match group index of the filename. If omitted 1 is used.') }, 'location': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.location', 'The match group index of the problem\'s location. Valid location patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). If omitted line and column is assumed.') }, 'line': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.line', 'The match group index of the problem\'s line. Defaults to 2') }, 'column': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.column', 'The match group index of the problem\'s column. Defaults to 3') }, 'endLine': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endLine', 'The match group index of the problem\'s end line. Defaults to undefined') }, 'endColumn': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endColumn', 'The match group index of the problem\'s end column. Defaults to undefined') }, 'severity': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.severity', 'The match group index of the problem\'s severity. Defaults to undefined') }, 'code': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.code', 'The match group index of the problem\'s code. Defaults to undefined') }, 'message': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.message', 'The match group index of the message. If omitted it defaults to 4 if location is specified. Otherwise it defaults to 5.') }, 'loop': { 'type': 'boolean', 'description': nls.localize('JsonSchema.pattern.loop', 'In a multi line matcher loop indicated whether this pattern is executed in a loop as long as it matches. Can only specified on a last pattern in a multi line pattern.') } } }, 'problemMatcherType': { 'oneOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/problemMatcher' }, { 'type': 'array', 'items': { 'anyOf': [ { '$ref': '#/definitions/problemMatcher' }, { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] } ] } } ] }, 'watchingPattern': { 'type': 'object', 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.watchingPattern.regexp', 'The regular expression to detect the begin or end of a watching task.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.watchingPattern.file', 'The match group index of the filename. Can be omitted.') }, } }, 'problemMatcher': { 'type': 'object', 'additionalProperties': false, 'properties': { 'base': { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'], 'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.') }, 'owner': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.owner', 'The owner of the problem inside Code. Can be omitted if base is specified. Defaults to \'external\' if omitted and base is not specified.') }, 'severity': { 'type': 'string', 'enum': ['error', 'warning', 'info'], 'description': nls.localize('JsonSchema.problemMatcher.severity', 'The default severity for captures problems. Is used if the pattern doesn\'t define a match group for severity.') }, 'applyTo': { 'type': 'string', 'enum': ['allDocuments', 'openDocuments', 'closedDocuments'], 'description': nls.localize('JsonSchema.problemMatcher.applyTo', 'Controls if a problem reported on a text document is applied only to open, closed or all documents.') }, 'pattern': { '$ref': '#/definitions/patternType', 'description': nls.localize('JsonSchema.problemMatcher.pattern', 'A problem pattern or the name of a predefined problem pattern. Can be omitted if base is specified.') }, 'fileLocation': { 'oneOf': [ { 'type': 'string', 'enum': ['absolute', 'relative'] }, { 'type': 'array', 'items': { 'type': 'string' } } ], 'description': nls.localize('JsonSchema.problemMatcher.fileLocation', 'Defines how file names reported in a problem pattern should be interpreted.') }, 'watching': { 'type': 'object', 'additionalProperties': false, 'properties': { 'activeOnStart': { 'type': 'boolean', 'description': nls.localize('JsonSchema.problemMatcher.watching.activeOnStart', 'If set to true the watcher is in active mode when the task starts. This is equals of issuing a line that matches the beginPattern') }, 'beginsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.beginsPattern', 'If matched in the output the start of a watching task is signaled.') }, 'endsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.endsPattern', 'If matched in the output the end of a watching task is signaled.') } } }, 'watchedTaskBeginsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedBegin', 'A regular expression signaling that a watched tasks begins executing triggered through file watching.') }, 'watchedTaskEndsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedEnd', 'A regular expression signaling that a watched tasks ends executing.') } } }, 'baseTaskRunnerConfiguration': { 'type': 'object', 'properties': { 'command': { 'type': 'string', 'description': nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.') }, 'isShellCommand': { 'type': 'boolean', 'default': true, 'description': nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'), 'items': { 'type': 'string' } }, 'options': { 'type': 'object', 'description': nls.localize('JsonSchema.options', 'Additional command options'), 'properties': { 'cwd': { 'type': 'string', 'description': nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.') }, 'env': { 'type': 'object', 'additionalProperties': { 'type': 'string' }, 'description': nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.') } }, 'additionalProperties': { 'type': ['string', 'array', 'object'] } }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.') }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'promptOnClose': { 'type': 'boolean', 'description': nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'), 'default': false }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'), 'default': true }, 'taskSelector': { 'type': 'string', 'description': nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.') }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') }, 'tasks': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'), 'items': { 'type': 'object', '$ref': '#/definitions/taskDescription' } } } }, 'taskDescription': { 'type': 'object', 'required': ['taskName'], 'additionalProperties': false, 'properties': { 'taskName': { 'type': 'string', 'description': nls.localize('JsonSchema.tasks.taskName', "The task's name") }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks.args', 'Additional arguments passed to the command when this task is invoked.'), 'items': { 'type': 'string' } }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'), 'default': true }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.') }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'isBuildCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'), 'default': true }, 'isTestCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'), 'default': true }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') } }, 'defaultSnippets': [ { 'label': 'Empty task', 'body': { 'taskName': '{{taskName}}' } } ] } }, 'allOf': [ { 'type': 'object', 'required': ['version'], 'properties': { 'version': { 'type': 'string', 'enum': ['0.1.0'], 'description': nls.localize('JsonSchema.version', 'The config\'s version number') }, 'windows': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.windows', 'Windows specific build configuration') }, 'osx': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.mac', 'Mac specific build configuration') }, 'linux': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.linux', 'Linux specific build configuration') } } }, { '$ref': '#/definitions/baseTaskRunnerConfiguration' } ] }; let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(schemaId, schema); jsonRegistry.addSchemaFileAssociation('/.vscode/tasks.json', schemaId); }
src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.000552022538613528, 0.00018117933359462768, 0.00016458921891171485, 0.0001710031647235155, 0.00004777706635650247 ]
{ "id": 1, "code_window": [ "export function defaultPattern(name: 'csc'): ProblemPattern;\n", "export function defaultPattern(name: 'vb'): ProblemPattern;\n", "export function defaultPattern(name: 'lessCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint'): ProblemPattern;\n", "export function defaultPattern(name: 'gulp-tsc'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint-stylish'): ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[] {\n", "\treturn _defaultPatterns[name];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function defaultPattern(name: 'go'): ProblemPattern;\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 505 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "clearOutput": "Cancella output", "switchToOutput.label": "Passa all'output", "toggleOutput": "Attiva/Disattiva output" }
i18n/ita/src/vs/workbench/parts/output/browser/outputActions.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00037913673440925777, 0.0002760628703981638, 0.00017298903549090028, 0.0002760628703981638, 0.00010307384945917875 ]
{ "id": 1, "code_window": [ "export function defaultPattern(name: 'csc'): ProblemPattern;\n", "export function defaultPattern(name: 'vb'): ProblemPattern;\n", "export function defaultPattern(name: 'lessCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint'): ProblemPattern;\n", "export function defaultPattern(name: 'gulp-tsc'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint-stylish'): ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[] {\n", "\treturn _defaultPatterns[name];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function defaultPattern(name: 'go'): ProblemPattern;\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 505 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ body { font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 14px; padding-left: 12px; line-height: 22px; } img { max-width: 100%; max-height: 100%; } a { color: #4080D0; text-decoration: none; } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } hr { border: 0; height: 2px; border-bottom: 2px solid; } h1 { padding-bottom: 0.3em; line-height: 1.2; border-bottom-width: 1px; border-bottom-style: solid; } h1, h2, h3 { font-weight: normal; } a:hover { color: #4080D0; text-decoration: underline; } table { border-collapse: collapse; } table > thead > tr > th { text-align: left; border-bottom: 1px solid; } table > thead > tr > th, table > thead > tr > td, table > tbody > tr > th, table > tbody > tr > td { padding: 5px 10px; } table > tbody > tr + tr > td { border-top: 1px solid; } blockquote { margin: 0 0 0 5px; padding-left: 10px; border-left: 5px solid; } code { font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback"; font-size: 14px; line-height: 19px; } .mac code { font-size: 12px; line-height: 18px; } code > div { padding: 16px; border-radius: 3px; overflow: auto; } /** Theming */ .vs { color: rgb(30, 30, 30); } .vs-dark { color: #DDD; } .hc-black { color: white; } .vs code { color: #A31515; } .vs-dark code { color: #D7BA7D; } .vs code > div { background-color: rgba(220, 220, 220, 0.4); } .vs-dark code > div { background-color: rgba(10, 10, 10, 0.4); } .hc-black code > div { background-color: rgb(0, 0, 0); } .hc-black h1 { border-color: rgb(0, 0, 0); } .vs table > thead > tr > th { border-color: rgba(0, 0, 0, 0.69); } .vs-dark table > thead > tr > th { border-color: rgba(255, 255, 255, 0.69); } .vs h1, .vs hr, .vs table > tbody > tr + tr > td { border-color: rgba(0, 0, 0, 0.18); } .vs-dark h1, .vs-dark hr, .vs-dark table > tbody > tr + tr > td { border-color: rgba(255, 255, 255, 0.18); } .vs blockquote, .vs-dark blockquote { background: rgba(127, 127, 127, 0.1); border-color: rgba(0, 122, 204, 0.5); } .hc-black blockquote { background: transparent; border-color: #fff; }
src/vs/languages/markdown/common/markdown.css
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017251513781957328, 0.00017107522580772638, 0.0001686249306658283, 0.0001713689707685262, 0.0000010052292509499239 ]
{ "id": 1, "code_window": [ "export function defaultPattern(name: 'csc'): ProblemPattern;\n", "export function defaultPattern(name: 'vb'): ProblemPattern;\n", "export function defaultPattern(name: 'lessCompile'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint'): ProblemPattern;\n", "export function defaultPattern(name: 'gulp-tsc'): ProblemPattern;\n", "export function defaultPattern(name: 'jshint-stylish'): ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[];\n", "export function defaultPattern(name: string): ProblemPattern | ProblemPattern[] {\n", "\treturn _defaultPatterns[name];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function defaultPattern(name: 'go'): ProblemPattern;\n" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "add", "edit_start_line_idx": 505 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import URI from 'vs/base/common/uri'; import {TextFileEditorModelCache} from 'vs/workbench/parts/files/common/editors/textFileEditorModel'; import {EditorModel} from 'vs/workbench/common/editor'; suite('Files - TextFileEditorModelCache', () => { test('add, remove, clear', function() { let cache = new TextFileEditorModelCache(); let m1 = new EditorModel(); let m2 = new EditorModel(); let m3 = new EditorModel(); cache.add(URI.file('/test.html'), <any>m1); cache.add(URI.file('/some/other.html'), <any>m2); cache.add(URI.file('/some/this.txt'), <any>m3); assert(!cache.get(URI.file('foo'))); assert.strictEqual(cache.get(URI.file('/test.html')), m1); let result = cache.getAll(); assert.strictEqual(3, result.length); result = cache.getAll(URI.file('/yes')); assert.strictEqual(0, result.length); result = cache.getAll(URI.file('/some/other.txt')); assert.strictEqual(0, result.length); result = cache.getAll(URI.file('/some/other.html')); assert.strictEqual(1, result.length); cache.remove(URI.file('')); result = cache.getAll(); assert.strictEqual(3, result.length); cache.remove(URI.file('/test.html')); result = cache.getAll(); assert.strictEqual(2, result.length); cache.clear(); result = cache.getAll(); assert.strictEqual(0, result.length); }); });
src/vs/workbench/parts/files/test/browser/textFileEditorModelCache.test.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.000173520966200158, 0.0001712530356599018, 0.00016957009211182594, 0.0001706480688881129, 0.0000015187284816420288 ]
{ "id": 2, "code_window": [ "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Absolute,\n", "\tpattern: defaultPattern('eslint-stylish')\n", "});\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "});\n", "\n", "registry.add('go', {\n", "\towner: 'typescript',\n", "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Relative,\n", "\tfilePrefix: '${cwd}',\n", "\tpattern: defaultPattern('go')\n", "});" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "replace", "edit_start_line_idx": 1129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/task.contribution'; import 'vs/workbench/parts/tasks/browser/taskQuickOpen'; import * as nls from 'vs/nls'; import * as Env from 'vs/base/common/flags'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import Severity from 'vs/base/common/severity'; import * as Objects from 'vs/base/common/objects'; import { IStringDictionary } from 'vs/base/common/collections'; import { Action } from 'vs/base/common/actions'; import * as Dom from 'vs/base/browser/dom'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { EventEmitter, ListenerUnbind } from 'vs/base/common/eventEmitter'; import * as Builder from 'vs/base/browser/builder'; import * as Types from 'vs/base/common/types'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { match } from 'vs/base/common/glob'; import { setTimeout } from 'vs/base/common/platform'; import { TerminateResponse } from 'vs/base/common/processes'; import { Registry } from 'vs/platform/platform'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IEventService } from 'vs/platform/event/common/event'; import { IEditor } from 'vs/platform/editor/common/editor'; import { IMessageService } from 'vs/platform/message/common/message'; import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration'; import { IFileService, FileChangesEvent, FileChangeType, EventType as FileEventType } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/platform/extensions/common/extensions'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry'); import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry'; import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService'; import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables'; import { ITextFileService, EventType } from 'vs/workbench/parts/files/common/files'; import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/parts/output/common/output'; import { ITaskSystem, ITaskSummary, ITaskRunResult, TaskError, TaskErrors, TaskConfiguration, TaskDescription, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem'; import { ITaskService, TaskServiceEvents } from 'vs/workbench/parts/tasks/common/taskService'; import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates'; import { LanguageServiceTaskSystem, LanguageServiceTaskConfiguration } from 'vs/workbench/parts/tasks/common/languageServiceTaskSystem'; import * as FileConfig from 'vs/workbench/parts/tasks/node/processRunnerConfiguration'; import { ProcessRunnerSystem } from 'vs/workbench/parts/tasks/node/processRunnerSystem'; import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector'; let $ = Builder.$; class AbstractTaskAction extends Action { protected taskService: ITaskService; protected telemetryService: ITelemetryService; constructor(id:string, label:string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label); this.taskService = taskService; this.telemetryService = telemetryService; } } class BuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.build'; public static TEXT = nls.localize('BuildAction.label','Run Build Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.build(); } } class TestAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.test'; public static TEXT = nls.localize('TestAction.label','Run Test Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.runTest(); } } class RebuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.rebuild'; public static TEXT = nls.localize('RebuildAction.label', 'Run Rebuild Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.rebuild(); } } class CleanAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.clean'; public static TEXT = nls.localize('CleanAction.label', 'Run Clean Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.clean(); } } class ConfigureTaskRunnerAction extends Action { public static ID = 'workbench.action.tasks.configureTaskRunner'; public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', 'Configure Task Runner'); private configurationService: IConfigurationService; private fileService: IFileService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private outputService: IOutputService; private messageService: IMessageService; private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(id, label); this.configurationService = configurationService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.outputService = outputService; this.messageService = messageService; this.quickOpenService = quickOpenService; } public run(event?:any): TPromise<IEditor> { if (!this.contextService.getWorkspace()) { this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.')); return TPromise.as(undefined); } let sideBySide = !!(event && (event.ctrlKey || event.metaKey)); return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => { return success; }, (err:any) => { ; return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner')}).then(selection => { if (!selection) { return undefined; } let contentPromise: TPromise<string>; if (selection.autoDetect) { this.outputService.showOutput(TaskService.OutputChannel); this.outputService.append(TaskService.OutputChannel, nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n'); let detector = new ProcessRunnerDetector(this.fileService, this.contextService, new SystemVariables(this.editorService, this.contextService)); contentPromise = detector.detect(false, selection.id).then((value) => { let config = value.config; if (value.stderr && value.stderr.length > 0) { value.stderr.forEach((line) => { this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.')); return selection.content; } else if (config) { if (value.stdout && value.stdout.length > 0) { value.stdout.forEach(line => this.outputService.append(TaskService.OutputChannel, line + '\n')); } let content = JSON.stringify(config, null, '\t'); content = [ '{', '\t// See http://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', ].join('\n') + content.substr(1); return content; } else { return selection.content; } }); } else { contentPromise = TPromise.as(selection.content); } return contentPromise.then(content => { return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content); }); }); }).then((stat) => { if (!stat) { return undefined; } // // (2) Open editor with configuration file return this.editorService.openEditor({ resource: stat.resource, options: { forceOpen: true } }, sideBySide); }, (error) => { throw new Error(nls.localize('ConfigureTaskRunnerAction.failed', "Unable to create the 'tasks.json' file inside the '.vscode' folder. Consult the task output for details.")); }); } } class CloseMessageAction extends Action { public static ID = 'workbench.action.build.closeMessage'; public static TEXT = nls.localize('CloseMessageAction.label', 'Close'); public closeFunction: () => void; constructor() { super(CloseMessageAction.ID, CloseMessageAction.TEXT); } public run(): Promise { if (this.closeFunction) { this.closeFunction(); } return TPromise.as(null); } } class TerminateAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.terminate'; public static TEXT = nls.localize('TerminateAction.label', 'Terminate Running Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.isActive().then((active) => { if (active) { return this.taskService.terminate().then((response) => { if (response.success) { return; } else { return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task')); } }); } }); } } class ShowLogAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.showLog'; public static TEXT = nls.localize('ShowLogAction.label', 'Show Task Log'); private outputService: IOutputService; constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService, @IOutputService outputService:IOutputService) { super(id, label, taskService, telemetryService); this.outputService = outputService; } public run(): Promise { return this.outputService.showOutput(TaskService.OutputChannel); } } class RunTaskAction extends Action { public static ID = 'workbench.action.tasks.runTask'; public static TEXT = nls.localize('RunTaskAction.label', "Run Task"); private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IQuickOpenService quickOpenService:IQuickOpenService) { super(id, label); this.quickOpenService = quickOpenService; } public run(event?:any): Promise { this.quickOpenService.show('task '); return TPromise.as(null); } } class StatusBarItem implements IStatusbarItem { private quickOpenService: IQuickOpenService; private markerService: IMarkerService; private taskService:ITaskService; private outputService: IOutputService; private intervalToken: any; private activeCount: number; private static progressChars:string = '|/-\\'; constructor(@IQuickOpenService quickOpenService:IQuickOpenService, @IMarkerService markerService:IMarkerService, @IOutputService outputService:IOutputService, @ITaskService taskService:ITaskService) { this.quickOpenService = quickOpenService; this.markerService = markerService; this.outputService = outputService; this.taskService = taskService; this.activeCount = 0; } public render(container: HTMLElement): IDisposable { let callOnDispose: IDisposable[] = [], element = document.createElement('div'), // icon = document.createElement('a'), progress = document.createElement('div'), label = document.createElement('a'), error = document.createElement('div'), warning = document.createElement('div'), info = document.createElement('div'); Dom.addClass(element, 'task-statusbar-item'); // dom.addClass(icon, 'task-statusbar-item-icon'); // element.appendChild(icon); Dom.addClass(progress, 'task-statusbar-item-progress'); element.appendChild(progress); progress.innerHTML = StatusBarItem.progressChars[0]; $(progress).hide(); Dom.addClass(label, 'task-statusbar-item-label'); element.appendChild(label); Dom.addClass(error, 'task-statusbar-item-label-error'); error.innerHTML = '0'; label.appendChild(error); Dom.addClass(warning, 'task-statusbar-item-label-warning'); warning.innerHTML = '0'; label.appendChild(warning); Dom.addClass(info, 'task-statusbar-item-label-info'); label.appendChild(info); $(info).hide(); // callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => { // this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true); // })); callOnDispose.push(Dom.addDisposableListener(label, 'click', (e:MouseEvent) => { this.quickOpenService.show('!'); })); let updateStatus = (element:HTMLDivElement, stats:number): boolean => { if (stats > 0) { element.innerHTML = stats.toString(); $(element).show(); return true; } else { $(element).hide(); return false; } }; let manyMarkers = nls.localize('manyMarkers', "99+"); let updateLabel = (stats: MarkerStatistics) => { error.innerHTML = stats.errors < 100 ? stats.errors.toString() : manyMarkers; warning.innerHTML = stats.warnings < 100 ? stats.warnings.toString() : manyMarkers; updateStatus(info, stats.infos); }; this.markerService.onMarkerChanged((changedResources) => { updateLabel(this.markerService.getStatistics()); }); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => { this.activeCount++; if (this.activeCount === 1) { let index = 1; let chars = StatusBarItem.progressChars; progress.innerHTML = chars[0]; this.intervalToken = setInterval(() => { progress.innerHTML = chars[index]; index++; if (index >= chars.length) { index = 0; } }, 50); $(progress).show(); } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data:TaskServiceEventData) => { this.activeCount--; if (this.activeCount === 0) { $(progress).hide(); clearInterval(this.intervalToken); this.intervalToken = null; } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => { if (this.activeCount !== 0) { $(progress).hide(); if (this.intervalToken) { clearInterval(this.intervalToken); this.intervalToken = null; } this.activeCount = 0; } })); container.appendChild(element); return { dispose: () => { callOnDispose = dispose(callOnDispose); } }; } } interface TaskServiceEventData { error?: any; } class TaskService extends EventEmitter implements ITaskService { public serviceId = ITaskService; public static SERVICE_ID: string = 'taskService'; public static OutputChannel:string = 'Tasks'; private modeService: IModeService; private configurationService: IConfigurationService; private markerService: IMarkerService; private outputService: IOutputService; private messageService: IMessageService; private fileService: IFileService; private telemetryService: ITelemetryService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private textFileService: ITextFileService; private eventService: IEventService; private modelService: IModelService; private extensionService: IExtensionService; private quickOpenService: IQuickOpenService; private _taskSystemPromise: TPromise<ITaskSystem>; private _taskSystem: ITaskSystem; private taskSystemListeners: ListenerUnbind[]; private clearTaskSystemPromise: boolean; private fileChangesListener: ListenerUnbind; constructor(@IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService, @IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService:IWorkbenchEditorService, @IFileService fileService:IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService:ITextFileService, @ILifecycleService lifecycleService: ILifecycleService, @IEventService eventService: IEventService, @IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(); this.modeService = modeService; this.configurationService = configurationService; this.markerService = markerService; this.outputService = outputService; this.messageService = messageService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.telemetryService = telemetryService; this.textFileService = textFileService; this.eventService = eventService; this.modelService = modelService; this.extensionService = extensionService; this.quickOpenService = quickOpenService; this.taskSystemListeners = []; this.clearTaskSystemPromise = false; this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, () => { this.emit(TaskServiceEvents.ConfigChanged); if (this._taskSystem && this._taskSystem.isActiveSync()) { this.clearTaskSystemPromise = true; } else { this._taskSystem = null; this._taskSystemPromise = null; } this.disposeTaskSystemListeners(); }); lifecycleService.addBeforeShutdownParticipant(this); } private disposeTaskSystemListeners(): void { this.taskSystemListeners.forEach(unbind => unbind()); this.taskSystemListeners = []; } private disposeFileChangesListener(): void { if (this.fileChangesListener) { this.fileChangesListener(); this.fileChangesListener = null; } } private get taskSystemPromise(): TPromise<ITaskSystem> { if (!this._taskSystemPromise) { let variables = new SystemVariables(this.editorService, this.contextService); let clearOutput = true; this._taskSystemPromise = TPromise.as(this.configurationService.getConfiguration<TaskConfiguration>('tasks')).then((config: TaskConfiguration) => { let parseErrors: string[] = config ? (<any>config).$parseErrors : null; if (parseErrors) { let isAffected = false; for (let i = 0; i < parseErrors.length; i++) { if (/tasks\.json$/.test(parseErrors[i])) { isAffected = true; break; } } if (isAffected) { this.outputService.append(TaskService.OutputChannel, nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n')); this.outputService.showOutput(TaskService.OutputChannel, true); return TPromise.wrapError({}); } } let configPromise: TPromise<TaskConfiguration>; if (config) { if (this.isRunnerConfig(config) && this.hasDetectorSupport(<FileConfig.ExternalTaskRunnerConfiguration>config)) { let fileConfig = <FileConfig.ExternalTaskRunnerConfiguration>config; configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables, fileConfig).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); let detectedConfig = value.config; if (!detectedConfig) { return config; } let result: FileConfig.ExternalTaskRunnerConfiguration = Objects.clone(fileConfig); let configuredTasks: IStringDictionary<FileConfig.TaskDescription> = Object.create(null); if (!result.tasks) { if (detectedConfig.tasks) { result.tasks = detectedConfig.tasks; } } else { result.tasks.forEach(task => configuredTasks[task.taskName] = task); detectedConfig.tasks.forEach((task) => { if (!configuredTasks[task.taskName]) { result.tasks.push(task); } }); } return result; }); } else { configPromise = TPromise.as<TaskConfiguration>(config); } } else { configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); return value.config; }); } return configPromise.then((config) => { if (!config) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noConfiguration', 'No task runner configured.'), TaskErrors.NotConfigured); } let result: ITaskSystem = null; if (config.buildSystem === 'service') { result = new LanguageServiceTaskSystem(<LanguageServiceTaskConfiguration>config, this.telemetryService, this.modeService); } else if (this.isRunnerConfig(config)) { result = new ProcessRunnerSystem(<FileConfig.ExternalTaskRunnerConfiguration>config, variables, this.markerService, this.modelService, this.telemetryService, this.outputService, TaskService.OutputChannel, clearOutput); } if (result === null) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noBuildType', "No valid task runner configured. Supported task runners are 'service' and 'program'."), TaskErrors.NoValidTaskRunner); } this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event))); this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event))); this._taskSystem = result; return result; }, (err: any) => { this.handleError(err); return Promise.wrapError(err); }); }); } return this._taskSystemPromise; } private printStderr(stderr: string[]): boolean { let result = true; if (stderr && stderr.length > 0) { stderr.forEach((line) => { result = false; this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.outputService.showOutput(TaskService.OutputChannel, true); } return result; } private isRunnerConfig(config: TaskConfiguration): boolean { return !config.buildSystem || config.buildSystem === 'program'; } private hasDetectorSupport(config: FileConfig.ExternalTaskRunnerConfiguration): boolean { if (!config.command) { return false; } return ProcessRunnerDetector.supports(config.command); } public configureAction(): Action { return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this.configurationService, this.editorService, this.fileService, this.contextService, this.outputService, this.messageService, this.quickOpenService); } public build(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.build()); } public rebuild(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.rebuild()); } public clean(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.clean()); } public runTest(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.runTest()); } public run(taskIdentifier: string): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.run(taskIdentifier)); } private executeTarget(fn: (taskSystem: ITaskSystem) => ITaskRunResult): TPromise<ITaskSummary> { return this.textFileService.saveAll().then((value) => { return this.taskSystemPromise. then((taskSystem) => { return taskSystem.isActive().then((active) => { if (!active) { return fn(taskSystem); } else { throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask); } }); }). then((runResult: ITaskRunResult) => { if (runResult.restartOnFileChanges) { let pattern = runResult.restartOnFileChanges; this.fileChangesListener = this.eventService.addListener(FileEventType.FILE_CHANGES, (event: FileChangesEvent) => { let needsRestart = event.changes.some((change) => { return (change.type === FileChangeType.ADDED || change.type === FileChangeType.DELETED) && !!match(pattern, change.resource.fsPath); }); if (needsRestart) { this.terminate().done(() => { // We need to give the child process a change to stop. setTimeout(() => { this.executeTarget(fn); }, 2000); }); } }); } return runResult.promise.then((value) => { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } return value; }); }, (err: any) => { this.handleError(err); }); }); } public isActive(): TPromise<boolean> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => taskSystem.isActive()); } return TPromise.as(false); } public terminate(): TPromise<TerminateResponse> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => { return taskSystem.terminate(); }).then(response => { if (response.success) { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } this.emit(TaskServiceEvents.Terminated, {}); this.disposeFileChangesListener(); } return response; }); } return TPromise.as( { success: true} ); } public tasks(): TPromise<TaskDescription[]> { return this.taskSystemPromise.then(taskSystem => taskSystem.tasks()); } public beforeShutdown(): boolean | TPromise<boolean> { if (this._taskSystem && this._taskSystem.isActiveSync()) { if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({ message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'), primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task") })) { return this._taskSystem.terminate().then((response) => { if (response.success) { this.emit(TaskServiceEvents.Terminated, {}); this._taskSystem = null; this.disposeFileChangesListener(); this.disposeTaskSystemListeners(); return false; // no veto } return true; // veto }, (err) => { return true; // veto }); } else { return true; // veto } } return false; // Nothing to do here } private handleError(err:any):void { let showOutput = true; if (err instanceof TaskError) { let buildError = <TaskError>err; let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask; let needsTerminate = buildError.code === TaskErrors.RunningTask; if (needsConfig || needsTerminate) { let closeAction = new CloseMessageAction(); let action = needsConfig ? this.configureAction() : new TerminateAction(TerminateAction.ID, TerminateAction.TEXT, this, this.telemetryService); closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [closeAction, action ] }); } else { this.messageService.show(buildError.severity, buildError.message); } } else if (err instanceof Error) { let error = <Error>err; this.messageService.show(Severity.Error, error.message); } else if (Types.isString(err)) { this.messageService.show(Severity.Error, <string>err); } else { this.messageService.show(Severity.Error, nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.')); } if (showOutput) { this.outputService.showOutput(TaskService.OutputChannel, true); } } } export class TaskServiceParticipant implements IWorkbenchContribution { constructor(@IInstantiationService private instantiationService: IInstantiationService) { // Force loading the language worker service this.instantiationService.getInstance(ITaskService); } public getId(): string { return 'vs.taskService'; } } let tasksCategory = nls.localize('tasksCategory', "Tasks"); let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), tasksCategory); if (Env.enableTasks) { // Task Service registerSingleton(ITaskService, TaskService); // Actions workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(BuildAction, BuildAction.ID, BuildAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TestAction, TestAction.ID, TestAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_T }), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RebuildAction, RebuildAction.ID, RebuildAction.TEXT), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CleanAction, CleanAction.ID, CleanAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TerminateAction, TerminateAction.ID, TerminateAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowLogAction, ShowLogAction.ID, ShowLogAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RunTaskAction, RunTaskAction.ID, RunTaskAction.TEXT), tasksCategory); // Register Quick Open (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( 'vs/workbench/parts/tasks/browser/taskQuickOpen', 'QuickOpenHandler', 'task ', nls.localize('taskCommands', "Run Task") ) ); // Status bar let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar); statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */)); // Output channel let outputChannelRegistry = <IOutputChannelRegistry>Registry.as(OutputExt.OutputChannels); outputChannelRegistry.registerChannel(TaskService.OutputChannel); (<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench)).registerWorkbenchContribution(TaskServiceParticipant); // tasks.json validation let schemaId = 'vscode://schemas/tasks'; let schema : IJSONSchema = { 'id': schemaId, 'description': 'Task definition file', 'type': 'object', 'default': { 'version': '0.1.0', 'command': 'myCommand', 'isShellCommand': false, 'args': [], 'showOutput': 'always', 'tasks': [ { 'taskName': 'build', 'showOutput': 'silent', 'isBuildCommand': true, 'problemMatcher': ['$tsc', '$lessCompile'] } ] }, 'definitions': { 'showOutputType': { 'type': 'string', 'enum': ['always', 'silent', 'never'], 'default': 'silent' }, 'patternType': { 'anyOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/pattern' }, { 'type': 'array', 'items': { '$ref': '#/definitions/pattern' } } ] }, 'pattern': { 'default': { 'regexp': '^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$', 'file': 1, 'location': 2, 'message': 3 }, 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.pattern.regexp', 'The regular expression to find an error, warning or info in the output.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.file', 'The match group index of the filename. If omitted 1 is used.') }, 'location': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.location', 'The match group index of the problem\'s location. Valid location patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). If omitted line and column is assumed.') }, 'line': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.line', 'The match group index of the problem\'s line. Defaults to 2') }, 'column': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.column', 'The match group index of the problem\'s column. Defaults to 3') }, 'endLine': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endLine', 'The match group index of the problem\'s end line. Defaults to undefined') }, 'endColumn': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endColumn', 'The match group index of the problem\'s end column. Defaults to undefined') }, 'severity': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.severity', 'The match group index of the problem\'s severity. Defaults to undefined') }, 'code': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.code', 'The match group index of the problem\'s code. Defaults to undefined') }, 'message': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.message', 'The match group index of the message. If omitted it defaults to 4 if location is specified. Otherwise it defaults to 5.') }, 'loop': { 'type': 'boolean', 'description': nls.localize('JsonSchema.pattern.loop', 'In a multi line matcher loop indicated whether this pattern is executed in a loop as long as it matches. Can only specified on a last pattern in a multi line pattern.') } } }, 'problemMatcherType': { 'oneOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/problemMatcher' }, { 'type': 'array', 'items': { 'anyOf': [ { '$ref': '#/definitions/problemMatcher' }, { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] } ] } } ] }, 'watchingPattern': { 'type': 'object', 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.watchingPattern.regexp', 'The regular expression to detect the begin or end of a watching task.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.watchingPattern.file', 'The match group index of the filename. Can be omitted.') }, } }, 'problemMatcher': { 'type': 'object', 'additionalProperties': false, 'properties': { 'base': { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'], 'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.') }, 'owner': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.owner', 'The owner of the problem inside Code. Can be omitted if base is specified. Defaults to \'external\' if omitted and base is not specified.') }, 'severity': { 'type': 'string', 'enum': ['error', 'warning', 'info'], 'description': nls.localize('JsonSchema.problemMatcher.severity', 'The default severity for captures problems. Is used if the pattern doesn\'t define a match group for severity.') }, 'applyTo': { 'type': 'string', 'enum': ['allDocuments', 'openDocuments', 'closedDocuments'], 'description': nls.localize('JsonSchema.problemMatcher.applyTo', 'Controls if a problem reported on a text document is applied only to open, closed or all documents.') }, 'pattern': { '$ref': '#/definitions/patternType', 'description': nls.localize('JsonSchema.problemMatcher.pattern', 'A problem pattern or the name of a predefined problem pattern. Can be omitted if base is specified.') }, 'fileLocation': { 'oneOf': [ { 'type': 'string', 'enum': ['absolute', 'relative'] }, { 'type': 'array', 'items': { 'type': 'string' } } ], 'description': nls.localize('JsonSchema.problemMatcher.fileLocation', 'Defines how file names reported in a problem pattern should be interpreted.') }, 'watching': { 'type': 'object', 'additionalProperties': false, 'properties': { 'activeOnStart': { 'type': 'boolean', 'description': nls.localize('JsonSchema.problemMatcher.watching.activeOnStart', 'If set to true the watcher is in active mode when the task starts. This is equals of issuing a line that matches the beginPattern') }, 'beginsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.beginsPattern', 'If matched in the output the start of a watching task is signaled.') }, 'endsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.endsPattern', 'If matched in the output the end of a watching task is signaled.') } } }, 'watchedTaskBeginsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedBegin', 'A regular expression signaling that a watched tasks begins executing triggered through file watching.') }, 'watchedTaskEndsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedEnd', 'A regular expression signaling that a watched tasks ends executing.') } } }, 'baseTaskRunnerConfiguration': { 'type': 'object', 'properties': { 'command': { 'type': 'string', 'description': nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.') }, 'isShellCommand': { 'type': 'boolean', 'default': true, 'description': nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'), 'items': { 'type': 'string' } }, 'options': { 'type': 'object', 'description': nls.localize('JsonSchema.options', 'Additional command options'), 'properties': { 'cwd': { 'type': 'string', 'description': nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.') }, 'env': { 'type': 'object', 'additionalProperties': { 'type': 'string' }, 'description': nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.') } }, 'additionalProperties': { 'type': ['string', 'array', 'object'] } }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.') }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'promptOnClose': { 'type': 'boolean', 'description': nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'), 'default': false }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'), 'default': true }, 'taskSelector': { 'type': 'string', 'description': nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.') }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') }, 'tasks': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'), 'items': { 'type': 'object', '$ref': '#/definitions/taskDescription' } } } }, 'taskDescription': { 'type': 'object', 'required': ['taskName'], 'additionalProperties': false, 'properties': { 'taskName': { 'type': 'string', 'description': nls.localize('JsonSchema.tasks.taskName', "The task's name") }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks.args', 'Additional arguments passed to the command when this task is invoked.'), 'items': { 'type': 'string' } }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'), 'default': true }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.') }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'isBuildCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'), 'default': true }, 'isTestCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'), 'default': true }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') } }, 'defaultSnippets': [ { 'label': 'Empty task', 'body': { 'taskName': '{{taskName}}' } } ] } }, 'allOf': [ { 'type': 'object', 'required': ['version'], 'properties': { 'version': { 'type': 'string', 'enum': ['0.1.0'], 'description': nls.localize('JsonSchema.version', 'The config\'s version number') }, 'windows': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.windows', 'Windows specific build configuration') }, 'osx': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.mac', 'Mac specific build configuration') }, 'linux': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.linux', 'Linux specific build configuration') } } }, { '$ref': '#/definitions/baseTaskRunnerConfiguration' } ] }; let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(schemaId, schema); jsonRegistry.addSchemaFileAssociation('/.vscode/tasks.json', schemaId); }
src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00024342263350263238, 0.00017117067181970924, 0.0001639570400584489, 0.00017041005776263773, 0.000008014158993319143 ]
{ "id": 2, "code_window": [ "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Absolute,\n", "\tpattern: defaultPattern('eslint-stylish')\n", "});\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "});\n", "\n", "registry.add('go', {\n", "\towner: 'typescript',\n", "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Relative,\n", "\tfilePrefix: '${cwd}',\n", "\tpattern: defaultPattern('go')\n", "});" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "replace", "edit_start_line_idx": 1129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "typingsReference.already.exists": "{0} ya existe. Asegúrese de que el archivo se incluye en el jsconfig.json del proyecto", "typingsReference.error.download": "No se puede recuperar el archivo d.ts en {0}: {1}", "typingsReference.error.write": "Problema al crear {0}: {1}", "typingsReference.success.nojsconfig": "{0} descargado con éxito", "typingsReference.success.withjsconfig": "{0} descargado con éxito. Asegúrese de que se incluye el archivo d.ts en el 'jsconfig.json' del proyecto." }
i18n/esn/src/vs/languages/typescript/common/features/quickFixMainActions.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017382916121277958, 0.00017326521629001945, 0.00017270127136725932, 0.00017326521629001945, 5.63944922760129e-7 ]
{ "id": 2, "code_window": [ "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Absolute,\n", "\tpattern: defaultPattern('eslint-stylish')\n", "});\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "});\n", "\n", "registry.add('go', {\n", "\towner: 'typescript',\n", "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Relative,\n", "\tfilePrefix: '${cwd}',\n", "\tpattern: defaultPattern('go')\n", "});" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "replace", "edit_start_line_idx": 1129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "linux.wait": "請按任意鍵繼續..." }
i18n/cht/src/vs/workbench/parts/execution/electron-browser/executionService.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017713588022161275, 0.00017713588022161275, 0.00017713588022161275, 0.00017713588022161275, 0 ]
{ "id": 2, "code_window": [ "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Absolute,\n", "\tpattern: defaultPattern('eslint-stylish')\n", "});\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "});\n", "\n", "registry.add('go', {\n", "\towner: 'typescript',\n", "\tapplyTo: ApplyToKind.allDocuments,\n", "\tfileLocation: FileLocationKind.Relative,\n", "\tfilePrefix: '${cwd}',\n", "\tpattern: defaultPattern('go')\n", "});" ], "file_path": "src/vs/platform/markers/common/problemMatcher.ts", "type": "replace", "edit_start_line_idx": 1129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "openSnippet.errorOnCreate": "無法建立 {0}", "openSnippet.label": "程式碼片段", "openSnippet.pickLanguage": "為程式碼片段選取語言", "preferences": "喜好設定", "snippetSchema.json": "使用者程式碼片段組態", "snippetSchema.json.body": "程式碼片段內容。請針對變數使用 '${id}'、'${id:label}'、'${1:label}',並針對游標位置使用 '$0'、'$1'", "snippetSchema.json.default": "空白程式碼片段", "snippetSchema.json.description": "程式碼片段描述。", "snippetSchema.json.prefix": "在 Intellisense 中選取程式碼片段時要使用的前置詞" }
i18n/cht/src/vs/workbench/parts/snippets/electron-browser/snippets.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017491955077275634, 0.00017169983766507357, 0.0001684801245573908, 0.00017169983766507357, 0.0000032197131076827645 ]
{ "id": 3, "code_window": [ "\t\t\t\t'patternType': {\n", "\t\t\t\t\t'anyOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/pattern'\n", "\t\t\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 869 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/task.contribution'; import 'vs/workbench/parts/tasks/browser/taskQuickOpen'; import * as nls from 'vs/nls'; import * as Env from 'vs/base/common/flags'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import Severity from 'vs/base/common/severity'; import * as Objects from 'vs/base/common/objects'; import { IStringDictionary } from 'vs/base/common/collections'; import { Action } from 'vs/base/common/actions'; import * as Dom from 'vs/base/browser/dom'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { EventEmitter, ListenerUnbind } from 'vs/base/common/eventEmitter'; import * as Builder from 'vs/base/browser/builder'; import * as Types from 'vs/base/common/types'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { match } from 'vs/base/common/glob'; import { setTimeout } from 'vs/base/common/platform'; import { TerminateResponse } from 'vs/base/common/processes'; import { Registry } from 'vs/platform/platform'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IEventService } from 'vs/platform/event/common/event'; import { IEditor } from 'vs/platform/editor/common/editor'; import { IMessageService } from 'vs/platform/message/common/message'; import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration'; import { IFileService, FileChangesEvent, FileChangeType, EventType as FileEventType } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/platform/extensions/common/extensions'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry'); import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry'; import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService'; import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables'; import { ITextFileService, EventType } from 'vs/workbench/parts/files/common/files'; import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/parts/output/common/output'; import { ITaskSystem, ITaskSummary, ITaskRunResult, TaskError, TaskErrors, TaskConfiguration, TaskDescription, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem'; import { ITaskService, TaskServiceEvents } from 'vs/workbench/parts/tasks/common/taskService'; import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates'; import { LanguageServiceTaskSystem, LanguageServiceTaskConfiguration } from 'vs/workbench/parts/tasks/common/languageServiceTaskSystem'; import * as FileConfig from 'vs/workbench/parts/tasks/node/processRunnerConfiguration'; import { ProcessRunnerSystem } from 'vs/workbench/parts/tasks/node/processRunnerSystem'; import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector'; let $ = Builder.$; class AbstractTaskAction extends Action { protected taskService: ITaskService; protected telemetryService: ITelemetryService; constructor(id:string, label:string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label); this.taskService = taskService; this.telemetryService = telemetryService; } } class BuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.build'; public static TEXT = nls.localize('BuildAction.label','Run Build Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.build(); } } class TestAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.test'; public static TEXT = nls.localize('TestAction.label','Run Test Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.runTest(); } } class RebuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.rebuild'; public static TEXT = nls.localize('RebuildAction.label', 'Run Rebuild Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.rebuild(); } } class CleanAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.clean'; public static TEXT = nls.localize('CleanAction.label', 'Run Clean Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.clean(); } } class ConfigureTaskRunnerAction extends Action { public static ID = 'workbench.action.tasks.configureTaskRunner'; public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', 'Configure Task Runner'); private configurationService: IConfigurationService; private fileService: IFileService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private outputService: IOutputService; private messageService: IMessageService; private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(id, label); this.configurationService = configurationService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.outputService = outputService; this.messageService = messageService; this.quickOpenService = quickOpenService; } public run(event?:any): TPromise<IEditor> { if (!this.contextService.getWorkspace()) { this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.')); return TPromise.as(undefined); } let sideBySide = !!(event && (event.ctrlKey || event.metaKey)); return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => { return success; }, (err:any) => { ; return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner')}).then(selection => { if (!selection) { return undefined; } let contentPromise: TPromise<string>; if (selection.autoDetect) { this.outputService.showOutput(TaskService.OutputChannel); this.outputService.append(TaskService.OutputChannel, nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n'); let detector = new ProcessRunnerDetector(this.fileService, this.contextService, new SystemVariables(this.editorService, this.contextService)); contentPromise = detector.detect(false, selection.id).then((value) => { let config = value.config; if (value.stderr && value.stderr.length > 0) { value.stderr.forEach((line) => { this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.')); return selection.content; } else if (config) { if (value.stdout && value.stdout.length > 0) { value.stdout.forEach(line => this.outputService.append(TaskService.OutputChannel, line + '\n')); } let content = JSON.stringify(config, null, '\t'); content = [ '{', '\t// See http://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', ].join('\n') + content.substr(1); return content; } else { return selection.content; } }); } else { contentPromise = TPromise.as(selection.content); } return contentPromise.then(content => { return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content); }); }); }).then((stat) => { if (!stat) { return undefined; } // // (2) Open editor with configuration file return this.editorService.openEditor({ resource: stat.resource, options: { forceOpen: true } }, sideBySide); }, (error) => { throw new Error(nls.localize('ConfigureTaskRunnerAction.failed', "Unable to create the 'tasks.json' file inside the '.vscode' folder. Consult the task output for details.")); }); } } class CloseMessageAction extends Action { public static ID = 'workbench.action.build.closeMessage'; public static TEXT = nls.localize('CloseMessageAction.label', 'Close'); public closeFunction: () => void; constructor() { super(CloseMessageAction.ID, CloseMessageAction.TEXT); } public run(): Promise { if (this.closeFunction) { this.closeFunction(); } return TPromise.as(null); } } class TerminateAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.terminate'; public static TEXT = nls.localize('TerminateAction.label', 'Terminate Running Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.isActive().then((active) => { if (active) { return this.taskService.terminate().then((response) => { if (response.success) { return; } else { return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task')); } }); } }); } } class ShowLogAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.showLog'; public static TEXT = nls.localize('ShowLogAction.label', 'Show Task Log'); private outputService: IOutputService; constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService, @IOutputService outputService:IOutputService) { super(id, label, taskService, telemetryService); this.outputService = outputService; } public run(): Promise { return this.outputService.showOutput(TaskService.OutputChannel); } } class RunTaskAction extends Action { public static ID = 'workbench.action.tasks.runTask'; public static TEXT = nls.localize('RunTaskAction.label', "Run Task"); private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IQuickOpenService quickOpenService:IQuickOpenService) { super(id, label); this.quickOpenService = quickOpenService; } public run(event?:any): Promise { this.quickOpenService.show('task '); return TPromise.as(null); } } class StatusBarItem implements IStatusbarItem { private quickOpenService: IQuickOpenService; private markerService: IMarkerService; private taskService:ITaskService; private outputService: IOutputService; private intervalToken: any; private activeCount: number; private static progressChars:string = '|/-\\'; constructor(@IQuickOpenService quickOpenService:IQuickOpenService, @IMarkerService markerService:IMarkerService, @IOutputService outputService:IOutputService, @ITaskService taskService:ITaskService) { this.quickOpenService = quickOpenService; this.markerService = markerService; this.outputService = outputService; this.taskService = taskService; this.activeCount = 0; } public render(container: HTMLElement): IDisposable { let callOnDispose: IDisposable[] = [], element = document.createElement('div'), // icon = document.createElement('a'), progress = document.createElement('div'), label = document.createElement('a'), error = document.createElement('div'), warning = document.createElement('div'), info = document.createElement('div'); Dom.addClass(element, 'task-statusbar-item'); // dom.addClass(icon, 'task-statusbar-item-icon'); // element.appendChild(icon); Dom.addClass(progress, 'task-statusbar-item-progress'); element.appendChild(progress); progress.innerHTML = StatusBarItem.progressChars[0]; $(progress).hide(); Dom.addClass(label, 'task-statusbar-item-label'); element.appendChild(label); Dom.addClass(error, 'task-statusbar-item-label-error'); error.innerHTML = '0'; label.appendChild(error); Dom.addClass(warning, 'task-statusbar-item-label-warning'); warning.innerHTML = '0'; label.appendChild(warning); Dom.addClass(info, 'task-statusbar-item-label-info'); label.appendChild(info); $(info).hide(); // callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => { // this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true); // })); callOnDispose.push(Dom.addDisposableListener(label, 'click', (e:MouseEvent) => { this.quickOpenService.show('!'); })); let updateStatus = (element:HTMLDivElement, stats:number): boolean => { if (stats > 0) { element.innerHTML = stats.toString(); $(element).show(); return true; } else { $(element).hide(); return false; } }; let manyMarkers = nls.localize('manyMarkers', "99+"); let updateLabel = (stats: MarkerStatistics) => { error.innerHTML = stats.errors < 100 ? stats.errors.toString() : manyMarkers; warning.innerHTML = stats.warnings < 100 ? stats.warnings.toString() : manyMarkers; updateStatus(info, stats.infos); }; this.markerService.onMarkerChanged((changedResources) => { updateLabel(this.markerService.getStatistics()); }); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => { this.activeCount++; if (this.activeCount === 1) { let index = 1; let chars = StatusBarItem.progressChars; progress.innerHTML = chars[0]; this.intervalToken = setInterval(() => { progress.innerHTML = chars[index]; index++; if (index >= chars.length) { index = 0; } }, 50); $(progress).show(); } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data:TaskServiceEventData) => { this.activeCount--; if (this.activeCount === 0) { $(progress).hide(); clearInterval(this.intervalToken); this.intervalToken = null; } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => { if (this.activeCount !== 0) { $(progress).hide(); if (this.intervalToken) { clearInterval(this.intervalToken); this.intervalToken = null; } this.activeCount = 0; } })); container.appendChild(element); return { dispose: () => { callOnDispose = dispose(callOnDispose); } }; } } interface TaskServiceEventData { error?: any; } class TaskService extends EventEmitter implements ITaskService { public serviceId = ITaskService; public static SERVICE_ID: string = 'taskService'; public static OutputChannel:string = 'Tasks'; private modeService: IModeService; private configurationService: IConfigurationService; private markerService: IMarkerService; private outputService: IOutputService; private messageService: IMessageService; private fileService: IFileService; private telemetryService: ITelemetryService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private textFileService: ITextFileService; private eventService: IEventService; private modelService: IModelService; private extensionService: IExtensionService; private quickOpenService: IQuickOpenService; private _taskSystemPromise: TPromise<ITaskSystem>; private _taskSystem: ITaskSystem; private taskSystemListeners: ListenerUnbind[]; private clearTaskSystemPromise: boolean; private fileChangesListener: ListenerUnbind; constructor(@IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService, @IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService:IWorkbenchEditorService, @IFileService fileService:IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService:ITextFileService, @ILifecycleService lifecycleService: ILifecycleService, @IEventService eventService: IEventService, @IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(); this.modeService = modeService; this.configurationService = configurationService; this.markerService = markerService; this.outputService = outputService; this.messageService = messageService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.telemetryService = telemetryService; this.textFileService = textFileService; this.eventService = eventService; this.modelService = modelService; this.extensionService = extensionService; this.quickOpenService = quickOpenService; this.taskSystemListeners = []; this.clearTaskSystemPromise = false; this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, () => { this.emit(TaskServiceEvents.ConfigChanged); if (this._taskSystem && this._taskSystem.isActiveSync()) { this.clearTaskSystemPromise = true; } else { this._taskSystem = null; this._taskSystemPromise = null; } this.disposeTaskSystemListeners(); }); lifecycleService.addBeforeShutdownParticipant(this); } private disposeTaskSystemListeners(): void { this.taskSystemListeners.forEach(unbind => unbind()); this.taskSystemListeners = []; } private disposeFileChangesListener(): void { if (this.fileChangesListener) { this.fileChangesListener(); this.fileChangesListener = null; } } private get taskSystemPromise(): TPromise<ITaskSystem> { if (!this._taskSystemPromise) { let variables = new SystemVariables(this.editorService, this.contextService); let clearOutput = true; this._taskSystemPromise = TPromise.as(this.configurationService.getConfiguration<TaskConfiguration>('tasks')).then((config: TaskConfiguration) => { let parseErrors: string[] = config ? (<any>config).$parseErrors : null; if (parseErrors) { let isAffected = false; for (let i = 0; i < parseErrors.length; i++) { if (/tasks\.json$/.test(parseErrors[i])) { isAffected = true; break; } } if (isAffected) { this.outputService.append(TaskService.OutputChannel, nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n')); this.outputService.showOutput(TaskService.OutputChannel, true); return TPromise.wrapError({}); } } let configPromise: TPromise<TaskConfiguration>; if (config) { if (this.isRunnerConfig(config) && this.hasDetectorSupport(<FileConfig.ExternalTaskRunnerConfiguration>config)) { let fileConfig = <FileConfig.ExternalTaskRunnerConfiguration>config; configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables, fileConfig).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); let detectedConfig = value.config; if (!detectedConfig) { return config; } let result: FileConfig.ExternalTaskRunnerConfiguration = Objects.clone(fileConfig); let configuredTasks: IStringDictionary<FileConfig.TaskDescription> = Object.create(null); if (!result.tasks) { if (detectedConfig.tasks) { result.tasks = detectedConfig.tasks; } } else { result.tasks.forEach(task => configuredTasks[task.taskName] = task); detectedConfig.tasks.forEach((task) => { if (!configuredTasks[task.taskName]) { result.tasks.push(task); } }); } return result; }); } else { configPromise = TPromise.as<TaskConfiguration>(config); } } else { configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); return value.config; }); } return configPromise.then((config) => { if (!config) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noConfiguration', 'No task runner configured.'), TaskErrors.NotConfigured); } let result: ITaskSystem = null; if (config.buildSystem === 'service') { result = new LanguageServiceTaskSystem(<LanguageServiceTaskConfiguration>config, this.telemetryService, this.modeService); } else if (this.isRunnerConfig(config)) { result = new ProcessRunnerSystem(<FileConfig.ExternalTaskRunnerConfiguration>config, variables, this.markerService, this.modelService, this.telemetryService, this.outputService, TaskService.OutputChannel, clearOutput); } if (result === null) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noBuildType', "No valid task runner configured. Supported task runners are 'service' and 'program'."), TaskErrors.NoValidTaskRunner); } this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event))); this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event))); this._taskSystem = result; return result; }, (err: any) => { this.handleError(err); return Promise.wrapError(err); }); }); } return this._taskSystemPromise; } private printStderr(stderr: string[]): boolean { let result = true; if (stderr && stderr.length > 0) { stderr.forEach((line) => { result = false; this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.outputService.showOutput(TaskService.OutputChannel, true); } return result; } private isRunnerConfig(config: TaskConfiguration): boolean { return !config.buildSystem || config.buildSystem === 'program'; } private hasDetectorSupport(config: FileConfig.ExternalTaskRunnerConfiguration): boolean { if (!config.command) { return false; } return ProcessRunnerDetector.supports(config.command); } public configureAction(): Action { return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this.configurationService, this.editorService, this.fileService, this.contextService, this.outputService, this.messageService, this.quickOpenService); } public build(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.build()); } public rebuild(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.rebuild()); } public clean(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.clean()); } public runTest(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.runTest()); } public run(taskIdentifier: string): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.run(taskIdentifier)); } private executeTarget(fn: (taskSystem: ITaskSystem) => ITaskRunResult): TPromise<ITaskSummary> { return this.textFileService.saveAll().then((value) => { return this.taskSystemPromise. then((taskSystem) => { return taskSystem.isActive().then((active) => { if (!active) { return fn(taskSystem); } else { throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask); } }); }). then((runResult: ITaskRunResult) => { if (runResult.restartOnFileChanges) { let pattern = runResult.restartOnFileChanges; this.fileChangesListener = this.eventService.addListener(FileEventType.FILE_CHANGES, (event: FileChangesEvent) => { let needsRestart = event.changes.some((change) => { return (change.type === FileChangeType.ADDED || change.type === FileChangeType.DELETED) && !!match(pattern, change.resource.fsPath); }); if (needsRestart) { this.terminate().done(() => { // We need to give the child process a change to stop. setTimeout(() => { this.executeTarget(fn); }, 2000); }); } }); } return runResult.promise.then((value) => { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } return value; }); }, (err: any) => { this.handleError(err); }); }); } public isActive(): TPromise<boolean> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => taskSystem.isActive()); } return TPromise.as(false); } public terminate(): TPromise<TerminateResponse> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => { return taskSystem.terminate(); }).then(response => { if (response.success) { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } this.emit(TaskServiceEvents.Terminated, {}); this.disposeFileChangesListener(); } return response; }); } return TPromise.as( { success: true} ); } public tasks(): TPromise<TaskDescription[]> { return this.taskSystemPromise.then(taskSystem => taskSystem.tasks()); } public beforeShutdown(): boolean | TPromise<boolean> { if (this._taskSystem && this._taskSystem.isActiveSync()) { if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({ message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'), primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task") })) { return this._taskSystem.terminate().then((response) => { if (response.success) { this.emit(TaskServiceEvents.Terminated, {}); this._taskSystem = null; this.disposeFileChangesListener(); this.disposeTaskSystemListeners(); return false; // no veto } return true; // veto }, (err) => { return true; // veto }); } else { return true; // veto } } return false; // Nothing to do here } private handleError(err:any):void { let showOutput = true; if (err instanceof TaskError) { let buildError = <TaskError>err; let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask; let needsTerminate = buildError.code === TaskErrors.RunningTask; if (needsConfig || needsTerminate) { let closeAction = new CloseMessageAction(); let action = needsConfig ? this.configureAction() : new TerminateAction(TerminateAction.ID, TerminateAction.TEXT, this, this.telemetryService); closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [closeAction, action ] }); } else { this.messageService.show(buildError.severity, buildError.message); } } else if (err instanceof Error) { let error = <Error>err; this.messageService.show(Severity.Error, error.message); } else if (Types.isString(err)) { this.messageService.show(Severity.Error, <string>err); } else { this.messageService.show(Severity.Error, nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.')); } if (showOutput) { this.outputService.showOutput(TaskService.OutputChannel, true); } } } export class TaskServiceParticipant implements IWorkbenchContribution { constructor(@IInstantiationService private instantiationService: IInstantiationService) { // Force loading the language worker service this.instantiationService.getInstance(ITaskService); } public getId(): string { return 'vs.taskService'; } } let tasksCategory = nls.localize('tasksCategory', "Tasks"); let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), tasksCategory); if (Env.enableTasks) { // Task Service registerSingleton(ITaskService, TaskService); // Actions workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(BuildAction, BuildAction.ID, BuildAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TestAction, TestAction.ID, TestAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_T }), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RebuildAction, RebuildAction.ID, RebuildAction.TEXT), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CleanAction, CleanAction.ID, CleanAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TerminateAction, TerminateAction.ID, TerminateAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowLogAction, ShowLogAction.ID, ShowLogAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RunTaskAction, RunTaskAction.ID, RunTaskAction.TEXT), tasksCategory); // Register Quick Open (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( 'vs/workbench/parts/tasks/browser/taskQuickOpen', 'QuickOpenHandler', 'task ', nls.localize('taskCommands', "Run Task") ) ); // Status bar let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar); statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */)); // Output channel let outputChannelRegistry = <IOutputChannelRegistry>Registry.as(OutputExt.OutputChannels); outputChannelRegistry.registerChannel(TaskService.OutputChannel); (<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench)).registerWorkbenchContribution(TaskServiceParticipant); // tasks.json validation let schemaId = 'vscode://schemas/tasks'; let schema : IJSONSchema = { 'id': schemaId, 'description': 'Task definition file', 'type': 'object', 'default': { 'version': '0.1.0', 'command': 'myCommand', 'isShellCommand': false, 'args': [], 'showOutput': 'always', 'tasks': [ { 'taskName': 'build', 'showOutput': 'silent', 'isBuildCommand': true, 'problemMatcher': ['$tsc', '$lessCompile'] } ] }, 'definitions': { 'showOutputType': { 'type': 'string', 'enum': ['always', 'silent', 'never'], 'default': 'silent' }, 'patternType': { 'anyOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/pattern' }, { 'type': 'array', 'items': { '$ref': '#/definitions/pattern' } } ] }, 'pattern': { 'default': { 'regexp': '^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$', 'file': 1, 'location': 2, 'message': 3 }, 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.pattern.regexp', 'The regular expression to find an error, warning or info in the output.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.file', 'The match group index of the filename. If omitted 1 is used.') }, 'location': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.location', 'The match group index of the problem\'s location. Valid location patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). If omitted line and column is assumed.') }, 'line': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.line', 'The match group index of the problem\'s line. Defaults to 2') }, 'column': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.column', 'The match group index of the problem\'s column. Defaults to 3') }, 'endLine': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endLine', 'The match group index of the problem\'s end line. Defaults to undefined') }, 'endColumn': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endColumn', 'The match group index of the problem\'s end column. Defaults to undefined') }, 'severity': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.severity', 'The match group index of the problem\'s severity. Defaults to undefined') }, 'code': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.code', 'The match group index of the problem\'s code. Defaults to undefined') }, 'message': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.message', 'The match group index of the message. If omitted it defaults to 4 if location is specified. Otherwise it defaults to 5.') }, 'loop': { 'type': 'boolean', 'description': nls.localize('JsonSchema.pattern.loop', 'In a multi line matcher loop indicated whether this pattern is executed in a loop as long as it matches. Can only specified on a last pattern in a multi line pattern.') } } }, 'problemMatcherType': { 'oneOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/problemMatcher' }, { 'type': 'array', 'items': { 'anyOf': [ { '$ref': '#/definitions/problemMatcher' }, { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] } ] } } ] }, 'watchingPattern': { 'type': 'object', 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.watchingPattern.regexp', 'The regular expression to detect the begin or end of a watching task.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.watchingPattern.file', 'The match group index of the filename. Can be omitted.') }, } }, 'problemMatcher': { 'type': 'object', 'additionalProperties': false, 'properties': { 'base': { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'], 'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.') }, 'owner': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.owner', 'The owner of the problem inside Code. Can be omitted if base is specified. Defaults to \'external\' if omitted and base is not specified.') }, 'severity': { 'type': 'string', 'enum': ['error', 'warning', 'info'], 'description': nls.localize('JsonSchema.problemMatcher.severity', 'The default severity for captures problems. Is used if the pattern doesn\'t define a match group for severity.') }, 'applyTo': { 'type': 'string', 'enum': ['allDocuments', 'openDocuments', 'closedDocuments'], 'description': nls.localize('JsonSchema.problemMatcher.applyTo', 'Controls if a problem reported on a text document is applied only to open, closed or all documents.') }, 'pattern': { '$ref': '#/definitions/patternType', 'description': nls.localize('JsonSchema.problemMatcher.pattern', 'A problem pattern or the name of a predefined problem pattern. Can be omitted if base is specified.') }, 'fileLocation': { 'oneOf': [ { 'type': 'string', 'enum': ['absolute', 'relative'] }, { 'type': 'array', 'items': { 'type': 'string' } } ], 'description': nls.localize('JsonSchema.problemMatcher.fileLocation', 'Defines how file names reported in a problem pattern should be interpreted.') }, 'watching': { 'type': 'object', 'additionalProperties': false, 'properties': { 'activeOnStart': { 'type': 'boolean', 'description': nls.localize('JsonSchema.problemMatcher.watching.activeOnStart', 'If set to true the watcher is in active mode when the task starts. This is equals of issuing a line that matches the beginPattern') }, 'beginsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.beginsPattern', 'If matched in the output the start of a watching task is signaled.') }, 'endsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.endsPattern', 'If matched in the output the end of a watching task is signaled.') } } }, 'watchedTaskBeginsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedBegin', 'A regular expression signaling that a watched tasks begins executing triggered through file watching.') }, 'watchedTaskEndsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedEnd', 'A regular expression signaling that a watched tasks ends executing.') } } }, 'baseTaskRunnerConfiguration': { 'type': 'object', 'properties': { 'command': { 'type': 'string', 'description': nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.') }, 'isShellCommand': { 'type': 'boolean', 'default': true, 'description': nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'), 'items': { 'type': 'string' } }, 'options': { 'type': 'object', 'description': nls.localize('JsonSchema.options', 'Additional command options'), 'properties': { 'cwd': { 'type': 'string', 'description': nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.') }, 'env': { 'type': 'object', 'additionalProperties': { 'type': 'string' }, 'description': nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.') } }, 'additionalProperties': { 'type': ['string', 'array', 'object'] } }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.') }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'promptOnClose': { 'type': 'boolean', 'description': nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'), 'default': false }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'), 'default': true }, 'taskSelector': { 'type': 'string', 'description': nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.') }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') }, 'tasks': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'), 'items': { 'type': 'object', '$ref': '#/definitions/taskDescription' } } } }, 'taskDescription': { 'type': 'object', 'required': ['taskName'], 'additionalProperties': false, 'properties': { 'taskName': { 'type': 'string', 'description': nls.localize('JsonSchema.tasks.taskName', "The task's name") }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks.args', 'Additional arguments passed to the command when this task is invoked.'), 'items': { 'type': 'string' } }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'), 'default': true }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.') }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'isBuildCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'), 'default': true }, 'isTestCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'), 'default': true }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') } }, 'defaultSnippets': [ { 'label': 'Empty task', 'body': { 'taskName': '{{taskName}}' } } ] } }, 'allOf': [ { 'type': 'object', 'required': ['version'], 'properties': { 'version': { 'type': 'string', 'enum': ['0.1.0'], 'description': nls.localize('JsonSchema.version', 'The config\'s version number') }, 'windows': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.windows', 'Windows specific build configuration') }, 'osx': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.mac', 'Mac specific build configuration') }, 'linux': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.linux', 'Linux specific build configuration') } } }, { '$ref': '#/definitions/baseTaskRunnerConfiguration' } ] }; let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(schemaId, schema); jsonRegistry.addSchemaFileAssociation('/.vscode/tasks.json', schemaId); }
src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.9034742116928101, 0.007475807797163725, 0.00015889493806753308, 0.0001705920440144837, 0.08078956604003906 ]
{ "id": 3, "code_window": [ "\t\t\t\t'patternType': {\n", "\t\t\t\t\t'anyOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/pattern'\n", "\t\t\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 869 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import assert = require('assert'); import jsonworker = require('vs/languages/json/common/jsonWorker'); import jsonSchema = require('vs/base/common/jsonSchema'); import resourceService = require('vs/editor/common/services/resourceServiceImpl'); import {IResourceService} from 'vs/editor/common/services/resourceService'; import instantiationService = require('vs/platform/instantiation/common/instantiationService'); import mirrorModel = require('vs/editor/common/model/mirrorModel'); import URI from 'vs/base/common/uri'; import SchemaService = require('vs/languages/json/common/jsonSchemaService'); import EditorCommon = require('vs/editor/common/editorCommon'); import Modes = require('vs/editor/common/modes'); import WinJS = require('vs/base/common/winjs.base'); import modesUtil = require('vs/editor/test/common/modesTestUtils'); import strings = require('vs/base/common/strings'); suite('JSON - Worker', () => { var assertOutline:any = function(actual: Modes.IOutlineEntry[], expected: any[], message: string) { assert.equal(actual.length, expected.length, message); for (var i = 0; i < expected.length; i++) { assert.equal(actual[i].label, expected[i].label, message); assert.equal(actual[i].type, expected[i].type, message); var childrenExpected = expected[i].children || []; var childrenActual = actual[i].children || []; assertOutline(childrenExpected, childrenActual, message); } }; function mockWorkerEnv(url: URI, content: string): { worker: jsonworker.JSONWorker; model: EditorCommon.IMirrorModel; } { var mm = mirrorModel.createTestMirrorModelFromString(content, null, url); var resourceModelMock: IResourceService = new resourceService.ResourceService(); resourceModelMock.insert(url, mm); var _instantiationService = instantiationService.createInstantiationService({ resourceService: resourceModelMock }); var worker = _instantiationService.createInstance(jsonworker.JSONWorker, mm.getMode().getId()); return { worker: worker, model: mm }; }; var prepareSchemaServer = function(schema:jsonSchema.IJSONSchema, worker: jsonworker.JSONWorker) : void { if (schema) { var id = "http://myschemastore/test1"; var schemaService = <SchemaService.JSONSchemaService> (<any>worker).schemaService; schemaService.registerExternalSchema(id, [ "*.json" ], schema); } } var testSuggestionsFor = function(value:string, stringAfter:string, schema?:jsonSchema.IJSONSchema):WinJS.TPromise<Modes.ISuggestResult> { var url = URI.parse('test://test.json'); var env = mockWorkerEnv(url, value); prepareSchemaServer(schema, env.worker); var idx = stringAfter ? value.indexOf(stringAfter) : 0; var position = env.model.getPositionFromOffset(idx); return env.worker.suggest(url, position).then(result => result[0]); }; function testComputeInfo(content:string, schema:jsonSchema.IJSONSchema, position:EditorCommon.IPosition):WinJS.TPromise<Modes.IComputeExtraInfoResult> { var url = URI.parse('test://test.json'); var env = mockWorkerEnv(url, content); prepareSchemaServer(schema, env.worker); return env.worker.computeInfo(url, position); } var testValueSetFor = function(value:string, schema:jsonSchema.IJSONSchema, selection:string, selectionLength: number, up: boolean):WinJS.TPromise<Modes.IInplaceReplaceSupportResult> { var url = URI.parse('test://test.json'); var env = mockWorkerEnv(url, value); prepareSchemaServer(schema, env.worker); var pos = env.model.getPositionFromOffset(value.indexOf(selection)); var range = { startLineNumber: pos.lineNumber, startColumn: pos.column, endLineNumber: pos.lineNumber, endColumn: pos.column + selectionLength }; return env.worker.navigateValueSet(url, range, up); }; function getOutline(content: string):WinJS.TPromise<Modes.IOutlineEntry[]> { var url = URI.parse('test'); var workerEnv = mockWorkerEnv(url, content); return workerEnv.worker.getOutline(url); }; var assertSuggestion= function(completion:Modes.ISuggestResult, label:string, documentationLabel?: string) { var matches = completion.suggestions.filter(function(suggestion: Modes.ISuggestion) { return suggestion.label === label && (!documentationLabel || suggestion.documentationLabel === documentationLabel); }).length; assert.equal(matches, 1, label + " should only existing once"); }; test('JSON outline - base types', function(testDone) { var content= '{ "key1": 1, "key2": "foo", "key3" : true }'; var expected= [ { label: 'key1', type: 'number'}, { label: 'key2', type: 'string'}, { label: 'key3', type: 'boolean'}, ]; getOutline(content).then((entries: Modes.IOutlineEntry[]) => { assertOutline(entries, expected); }).done(() => testDone(), (error) => { testDone(error); }); }); test('JSON outline - arrays', function(testDone) { var content= '{ "key1": 1, "key2": [ 1, 2, 3 ], "key3" : [ { "k1": 1 }, {"k2": 2 } ] }'; var expected= [ { label: 'key1', type: 'number'}, { label: 'key2', type: 'array'}, { label: 'key3', type: 'array', children : [ { label: 'k1', type: 'number'}, { label: 'k2', type: 'number'} ]}, ]; getOutline(content).then((entries: Modes.IOutlineEntry[]) => { assertOutline(entries, expected); }).done(() => testDone(), (error) => { testDone(error); }); }); test('JSON outline - objects', function(testDone) { var content= '{ "key1": { "key2": true }, "key3" : { "k1": { } }'; var expected= [ { label: 'key1', type: 'object', children : [ { label: 'key2', type: 'boolean'} ] }, { label: 'key3', type: 'object', children : [ { label: 'k1', type: 'object'} ] } ]; getOutline(content).then((entries: Modes.IOutlineEntry[]) => { assertOutline(entries, expected); }).done(() => testDone(), (error) => { testDone(error); }); }); test('JSON outline - object with syntax error', function(testDone) { var content= '{ "key1": { "key2": true, "key3":, "key4": false } }'; var expected= [ { label: 'key1', type: 'object', children : [ { label: 'key2', type: 'boolean'}, { label: 'key4', type: 'boolean'} ] }, ]; getOutline(content).then((entries: Modes.IOutlineEntry[]) => { assertOutline(entries, expected); }).done(() => testDone(), (error) => { testDone(error); }); }); test('JSON suggest for keys no schema', function(testDone) { WinJS.Promise.join([ testSuggestionsFor('[ { "name": "John", "age": 44 }, { /**/ }', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'name'); assertSuggestion(result, 'age'); }), testSuggestionsFor('[ { "name": "John", "age": 44 }, { "/**/ }', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'name'); assertSuggestion(result, 'age'); }), testSuggestionsFor('[ { "name": "John", "age": 44 }, { "n/**/ }', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, 'name'); }), testSuggestionsFor('[ { "name": "John", "age": 44 }, { "name/**/" }', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, 'name'); }), testSuggestionsFor('[ { "name": "John", "address": { "street" : "MH Road", "number" : 5 } }, { "name": "Jack", "address": { "street" : "100 Feet Road", /**/ }', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, 'number'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest for values no schema', function(testDone) { WinJS.Promise.join([ testSuggestionsFor('[ { "name": "John", "age": 44 }, { "name": /**/', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, '"John"'); }), testSuggestionsFor('[ { "data": { "key": 1, "data": true } }, { "data": /**/', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, '{}'); assertSuggestion(result, 'true'); assertSuggestion(result, 'false'); }), testSuggestionsFor('[ { "data": "foo" }, { "data": "bar" }, { "data": "/**/" } ]', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, '"foo"'); assertSuggestion(result, '"bar"'); assertSuggestion(result, '"/**/"'); }), testSuggestionsFor('[ { "data": "foo" }, { "data": "bar" }, { "data": "f/**/" } ]', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, '"foo"'); assertSuggestion(result, '"f/**/"'); }), testSuggestionsFor('[ { "data": "foo" }, { "data": "bar" }, { "data": "xoo"/**/ } ]', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, '"xoo"'); }), testSuggestionsFor('[ { "data": "foo" }, { "data": "bar" }, { "data": "xoo" /**/ } ]', '/**/').then((result) => { assert.strictEqual(result.suggestions.length, 0); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest for keys with schema', function(testDone) { var schema:jsonSchema.IJSONSchema = { type: 'object', properties: { 'a' : { type: 'number', description: 'A' }, 'b' : { type: 'string', description: 'B' }, 'c' : { type: 'boolean', description: 'C' } } }; WinJS.Promise.join([ testSuggestionsFor('{/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, 'a', 'A'); assertSuggestion(result, 'b', 'B'); assertSuggestion(result, 'c', 'C'); }), testSuggestionsFor('{ "/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, 'a', 'A'); assertSuggestion(result, 'b', 'B'); assertSuggestion(result, 'c', 'C'); }), testSuggestionsFor('{ "a/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, 'a', 'A'); }), testSuggestionsFor('{ "a" = 1;/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'b', 'B'); assertSuggestion(result, 'c', 'C'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest for value with schema', function(testDone) { var schema:jsonSchema.IJSONSchema = { type: 'object', properties: { 'a' : { enum: [ 'John', 'Jeff', 'George' ] } } }; WinJS.Promise.join([ testSuggestionsFor('{ "a": /**/ }', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, '"John"'); assertSuggestion(result, '"Jeff"'); assertSuggestion(result, '"George"'); }), testSuggestionsFor('{ "a": "J/**/ }', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, '"John"'); assertSuggestion(result, '"Jeff"'); }), testSuggestionsFor('{ "a": "John"/**/ }', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, '"John"'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest with nested schema', function(testDone) { var content = '{/**/}'; var schema:jsonSchema.IJSONSchema = { oneOf: [{ type: 'object', properties: { 'a' : { type: 'number', description: 'A' }, 'b' : { type: 'string', description: 'B' }, } }, { type: 'array' }] }; WinJS.Promise.join([ testSuggestionsFor(content, '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'a', 'A'); assertSuggestion(result, 'b', 'B'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest with required anyOf', function(testDone) { var schema: jsonSchema.IJSONSchema = { anyOf: [{ type: 'object', required: ['a', 'b'], properties: { 'a': { type: 'string', description: 'A' }, 'b': { type: 'string', description: 'B' }, } }, { type: 'object', required: ['c', 'd'], properties: { 'c': { type: 'string', description: 'C' }, 'd': { type: 'string', description: 'D' }, } }] }; WinJS.Promise.join([ testSuggestionsFor('{/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 4); assertSuggestion(result, 'a', 'A'); assertSuggestion(result, 'b', 'B'); assertSuggestion(result, 'c', 'C'); assertSuggestion(result, 'd', 'D'); }), testSuggestionsFor('{ "a": "", /**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, 'b', 'B'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest with anyOf', function(testDone) { var schema:jsonSchema.IJSONSchema = { anyOf: [{ type: 'object', properties: { 'type' : { enum: [ 'house' ] }, 'b' : { type: 'string' }, } }, { type: 'object', properties: { 'type' : { enum: [ 'appartment' ] }, 'c' : { type: 'string' }, } }] }; WinJS.Promise.join([ testSuggestionsFor('{/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, 'type'); assertSuggestion(result, 'b'); assertSuggestion(result, 'c'); }), testSuggestionsFor('{ "type": "appartment", /**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 1); assertSuggestion(result, 'c'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest with oneOf', function(testDone) { var schema:jsonSchema.IJSONSchema = { oneOf: [{ type: 'object', allOf: [{ properties: { 'a' : { type: 'string', description: 'A' } } }, { anyOf: [{ properties: { 'b1' : { type: 'string', description: 'B1' } }, }, { properties: { 'b2' : { type: 'string', description: 'B2' } }, }] }] }, { type: 'object', properties: { 'c' : { type: 'string', description: 'C' }, 'd' : { type: 'string', description: 'D' }, } }] }; WinJS.Promise.join([ testSuggestionsFor('{/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 5); assertSuggestion(result, 'a', 'A'); assertSuggestion(result, 'b1', 'B1'); assertSuggestion(result, 'b2', 'B2'); assertSuggestion(result, 'c', 'C'); assertSuggestion(result, 'd', 'D'); }), testSuggestionsFor('{ "b1": "", /**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'a', 'A'); assertSuggestion(result, 'b2', 'B2'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON suggest with oneOf and enums', function(testDone) { var schema:jsonSchema.IJSONSchema = { oneOf: [{ type: 'object', properties: { 'type' : { type: 'string', enum: [ '1', '2' ] }, 'a' : { type: 'object', properties: { 'x': { type: 'string' }, 'y': { type: 'string' } }, "required" : [ 'x', 'y'] }, 'b': {} }, }, { type: 'object', properties: { 'type' : { type: 'string', enum: [ '3' ] }, 'a' : { type: 'object', properties: { 'x': { type: 'string' }, 'z': { type: 'string' } }, "required" : [ 'x', 'z'] }, 'c': {} }, }] }; WinJS.Promise.join([ testSuggestionsFor('{/**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 4); assertSuggestion(result, 'type'); assertSuggestion(result, 'a'); assertSuggestion(result, 'b'); assertSuggestion(result, 'c'); }), testSuggestionsFor('{ "type": /**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 3); assertSuggestion(result, '"1"'); assertSuggestion(result, '"2"'); assertSuggestion(result, '"3"'); }), testSuggestionsFor('{ "a": { "x": "", "y": "" }, "type": /**/}', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, '"1"'); assertSuggestion(result, '"2"'); }), testSuggestionsFor('{ "type": "1", "a" : { /**/ }', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'x'); assertSuggestion(result, 'y'); }), testSuggestionsFor('{ "type": "1", "a" : { "x": "", "z":"" }, /**/', '/**/', schema).then((result) => { // both alternatives have errors: intellisense proposes all options assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'b'); assertSuggestion(result, 'c'); }), testSuggestionsFor('{ "a" : { "x": "", "z":"" }, /**/', '/**/', schema).then((result) => { assert.strictEqual(result.suggestions.length, 2); assertSuggestion(result, 'type'); assertSuggestion(result, 'c'); }), ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON Compute Info', function(testDone) { var content = '{"a": 42, "b": "hello", "c": false}'; var schema:jsonSchema.IJSONSchema = { type: 'object', description: 'a very special object', properties: { 'a' : { type: 'number', description: 'A' }, 'b' : { type: 'string', description: 'B' }, 'c' : { type: 'boolean', description: 'C' } } }; WinJS.Promise.join([ testComputeInfo(content, schema, {lineNumber:1, column:1}).then((result) => { assert.deepEqual(result.htmlContent, [ { className: 'documentation', text: 'a very special object' } ]); }), testComputeInfo(content, schema, {lineNumber: 1, column: 2}).then((result) => { assert.deepEqual(result.htmlContent, [ { className: 'documentation', text: 'A' } ]); }), testComputeInfo(content, schema, {lineNumber:1, column:33}).then((result) => { assert.deepEqual(result.htmlContent, [ { className: 'documentation', text: 'C' } ]); }), testComputeInfo(content, schema, {lineNumber:1, column:8}).then((result) => { assert.deepEqual(result.htmlContent, [ { className: 'documentation', text: 'A' } ]); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); test('JSON ComputeInfo with nested schema', function(testDone) { var content = '{"a": 42, "b": "hello"}'; var schema:jsonSchema.IJSONSchema = { oneOf: [{ type: 'object', description: 'a very special object', properties: { 'a' : { type: 'number', description: 'A' }, 'b' : { type: 'string', description: 'B' }, } }, { type: 'array' }] }; WinJS.Promise.join([ testComputeInfo(content, schema, {lineNumber:1, column:10}).then((result) => { assert.deepEqual(result.htmlContent, [ { className: 'documentation', text: 'a very special object' } ]); }), testComputeInfo(content, schema, {lineNumber:1, column:2}).then((result) => { assert.deepEqual(result.htmlContent, [ { className: 'documentation', text: 'A' } ]); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); var assertReplaceResult= function(result:Modes.IInplaceReplaceSupportResult, expected:string) { assert.ok(!!result); assert.equal(result.value, expected); }; test('JSON value replace', function(testDone) { var content = '{ "a" : "error", "b": true }'; var schema:jsonSchema.IJSONSchema = { type: 'object', properties: { 'a' : { type: 'string', enum : [ 'error', 'warning', 'ignore' ] }, 'b' : { type: 'boolean' } } }; WinJS.Promise.join([ testValueSetFor(content, schema, 'error', 0, true).then((result) => { assertReplaceResult(result, '"warning"'); }), testValueSetFor(content, schema, 'error', 0, false).then((result) => { assertReplaceResult(result, '"ignore"'); }), testValueSetFor(content, schema, 'true', 0, false).then((result) => { assertReplaceResult(result, 'false'); }) ]).done(() => testDone(), (errors:any[]) => { testDone(errors.reduce((e1, e2) => e1 || e2)); }); }); });
src/vs/languages/json/test/common/jsonworker.test.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017528953321743757, 0.00016996711201500148, 0.00016458687605336308, 0.00017015374032780528, 0.0000026878551580011845 ]
{ "id": 3, "code_window": [ "\t\t\t\t'patternType': {\n", "\t\t\t\t\t'anyOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/pattern'\n", "\t\t\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 869 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'emmet' { export interface Range { start: number; end: number; } export interface Editor { /** * Returns character indexes of selected text: object with <code>start</code> * and <code>end</code> properties. If there's no selection, should return * object with <code>start</code> and <code>end</code> properties referring * to current caret position * @return {Object} * @example * var selection = editor.getSelectionRange(); * alert(selection.start + ', ' + selection.end); */ getSelectionRange(): Range; /** * Creates selection from <code>start</code> to <code>end</code> character * indexes. If <code>end</code> is omitted, this method should place caret * and <code>start</code> index * @param {Number} start * @param {Number} [end] * @example * editor.createSelection(10, 40); * * //move caret to 15th character * editor.createSelection(15); */ createSelection(start: number, end: number): void; /** * Returns current line's start and end indexes as object with <code>start</code> * and <code>end</code> properties * @return {Object} * @example * var range = editor.getCurrentLineRange(); * alert(range.start + ', ' + range.end); */ getCurrentLineRange(): Range; /** * Returns current caret position * @return {Number|null} */ getCaretPos(): number; /** * Set new caret position * @param {Number} pos Caret position */ setCaretPos(pos: number): void; /** * Returns content of current line * @return {String} */ getCurrentLine(): string; /** * Replace editor's content or it's part (from <code>start</code> to * <code>end</code> index). If <code>value</code> contains * <code>caret_placeholder</code>, the editor will put caret into * this position. If you skip <code>start</code> and <code>end</code> * arguments, the whole target's content will be replaced with * <code>value</code>. * * If you pass <code>start</code> argument only, * the <code>value</code> will be placed at <code>start</code> string * index of current content. * * If you pass <code>start</code> and <code>end</code> arguments, * the corresponding substring of current target's content will be * replaced with <code>value</code>. * @param {String} value Content you want to paste * @param {Number} [start] Start index of editor's content * @param {Number} [end] End index of editor's content * @param {Boolean} [no_indent] Do not auto indent <code>value</code> */ replaceContent(value: string, start: number, end: number, no_indent: boolean): void; /** * Returns editor's content * @return {String} */ getContent(): string; /** * Returns current editor's syntax mode * @return {String} */ getSyntax(): string; /** * Returns current output profile name (see profile module). * In most cases, this method should return <code>null</code> and let * Emmet guess best profile name for current syntax and user data. * In case you’re using advanced editor with access to syntax scopes * (like Sublime Text 2), you can return syntax name for current scope. * For example, you may return `line` profile when editor caret is inside * string of programming language. * * @return {String} */ getProfileName(): string; /** * Ask user to enter something * @param {String} title Dialog title * @return {String} Entered data * @since 0.65 */ prompt(title: string): void getSelection(): string; getFilePath(): string; } /** * Runs given action * @param {String} name Action name * @param {IEmmetEditor} editor Editor instance * @return {Boolean} Returns true if action was performed successfully */ export function run(action: string, editor: Editor): boolean; }
src/vs/workbench/parts/emmet/node/emmet.d.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00018515545525588095, 0.00016858500021044165, 0.0001616425724932924, 0.00016707569011487067, 0.000005515073553397087 ]
{ "id": 3, "code_window": [ "\t\t\t\t'patternType': {\n", "\t\t\t\t\t'anyOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/pattern'\n", "\t\t\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 869 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import crypto = require('crypto'); import fs = require('fs'); import path = require('path'); import os = require('os'); import {app} from 'electron'; import arrays = require('vs/base/common/arrays'); import strings = require('vs/base/common/strings'); import paths = require('vs/base/common/paths'); import platform = require('vs/base/common/platform'); import uri from 'vs/base/common/uri'; import types = require('vs/base/common/types'); export interface IUpdateInfo { baseUrl: string; } export interface IProductConfiguration { nameShort: string; nameLong: string; applicationName: string; win32AppUserModelId: string; win32MutexName: string; darwinBundleIdentifier: string; dataFolderName: string; downloadUrl: string; updateUrl?: string; quality?: string; commit: string; date: string; extensionsGallery: { serviceUrl: string; itemUrl: string; }; extensionTips: { [id: string]: string; }; crashReporter: Electron.CrashReporterStartOptions; welcomePage: string; enableTelemetry: boolean; aiConfig: { key: string; asimovKey: string; }; sendASmile: { reportIssueUrl: string, requestFeatureUrl: string }; documentationUrl: string; releaseNotesUrl: string; twitterUrl: string; requestFeatureUrl: string; reportIssueUrl: string; licenseUrl: string; privacyStatementUrl: string; } export const isBuilt = !process.env.VSCODE_DEV; export const appRoot = path.dirname(uri.parse(require.toUrl('')).fsPath); export const currentWorkingDirectory = process.env.VSCODE_CWD || process.cwd(); let productContents: IProductConfiguration; try { productContents = JSON.parse(fs.readFileSync(path.join(appRoot, 'product.json'), 'utf8')); } catch (error) { productContents = Object.create(null); } export const product: IProductConfiguration = productContents; product.nameShort = product.nameShort + (isBuilt ? '' : ' Dev'); product.nameLong = product.nameLong + (isBuilt ? '' : ' Dev'); product.dataFolderName = product.dataFolderName + (isBuilt ? '' : '-dev'); export const updateUrl = product.updateUrl; export const quality = product.quality; export const mainIPCHandle = getMainIPCHandle(); export const sharedIPCHandle = getSharedIPCHandle(); export const version = app.getVersion(); export const cliArgs = parseCli(); export const appHome = app.getPath('userData'); export const appSettingsHome = path.join(appHome, 'User'); if (!fs.existsSync(appSettingsHome)) { fs.mkdirSync(appSettingsHome); } export const appSettingsPath = path.join(appSettingsHome, 'settings.json'); export const appKeybindingsPath = path.join(appSettingsHome, 'keybindings.json'); export const userHome = path.join(app.getPath('home'), product.dataFolderName); if (!fs.existsSync(userHome)) { fs.mkdirSync(userHome); } export const userExtensionsHome = cliArgs.pluginHomePath || path.join(userHome, 'extensions'); if (!fs.existsSync(userExtensionsHome)) { fs.mkdirSync(userExtensionsHome); } // Helper to identify if we have plugin tests to run from the command line without debugger export const isTestingFromCli = cliArgs.extensionTestsPath && !cliArgs.debugBrkExtensionHost; export function log(...a: any[]): void { if (cliArgs.verboseLogging) { console.log.call(null, `(${new Date().toLocaleTimeString()})`, ...a); } } export interface IProcessEnvironment { [key: string]: string; } export interface ICommandLineArguments { verboseLogging: boolean; debugExtensionHostPort: number; debugBrkExtensionHost: boolean; logExtensionHostCommunication: boolean; disableExtensions: boolean; pluginHomePath: string; extensionDevelopmentPath: string; extensionTestsPath: string; programStart: number; pathArguments?: string[]; enablePerformance?: boolean; firstrun?: boolean; openNewWindow?: boolean; openInSameWindow?: boolean; gotoLineMode?: boolean; diffMode?: boolean; locale?: string; waitForWindowClose?: boolean; } function parseCli(): ICommandLineArguments { // We need to do some argv massaging. First, remove the Electron executable let args = Array.prototype.slice.call(process.argv, 1); // Then, when in dev, remove the first non option argument, it will be the app location if (!isBuilt) { let i = (() => { for (let j = 0; j < args.length; j++) { if (args[j][0] !== '-') { return j; } } return -1; })(); if (i > -1) { args.splice(i, 1); } } // Finally, any extra arguments in the 'argv' file should be prepended if (fs.existsSync(path.join(appRoot, 'argv'))) { let extraargs: string[] = JSON.parse(fs.readFileSync(path.join(appRoot, 'argv'), 'utf8')); args = extraargs.concat(args); } let opts = parseOpts(args); let gotoLineMode = !!opts['g'] || !!opts['goto']; let debugBrkExtensionHostPort = parseNumber(args, '--debugBrkPluginHost', 5870); let debugExtensionHostPort: number; let debugBrkExtensionHost: boolean; if (debugBrkExtensionHostPort) { debugExtensionHostPort = debugBrkExtensionHostPort; debugBrkExtensionHost = true; } else { debugExtensionHostPort = parseNumber(args, '--debugPluginHost', 5870, isBuilt ? void 0 : 5870); } let pathArguments = parsePathArguments(args, gotoLineMode); return { pathArguments: pathArguments, programStart: parseNumber(args, '--timestamp', 0, 0), enablePerformance: !!opts['p'], verboseLogging: !!opts['verbose'], debugExtensionHostPort: debugExtensionHostPort, debugBrkExtensionHost: debugBrkExtensionHost, logExtensionHostCommunication: !!opts['logPluginHostCommunication'], firstrun: !!opts['squirrel-firstrun'], openNewWindow: !!opts['n'] || !!opts['new-window'], openInSameWindow: !!opts['r'] || !!opts['reuse-window'], gotoLineMode: gotoLineMode, diffMode: (!!opts['d'] || !!opts['diff']) && pathArguments.length === 2, pluginHomePath: normalizePath(parseString(args, '--extensionHomePath')), extensionDevelopmentPath: normalizePath(parseString(args, '--extensionDevelopmentPath')), extensionTestsPath: normalizePath(parseString(args, '--extensionTestsPath')), disableExtensions: !!opts['disableExtensions'] || !!opts['disable-extensions'], locale: parseString(args, '--locale'), waitForWindowClose: !!opts['w'] || !!opts['wait'] }; } function getIPCHandleName(): string { let handleName = app.getName(); if (!isBuilt) { handleName += '-dev'; } // Support to run VS Code multiple times as different user // by making the socket unique over the logged in user let userId = uniqueUserId(); if (userId) { handleName += ('-' + userId); } if (process.platform === 'win32') { return '\\\\.\\pipe\\' + handleName; } return path.join(os.tmpdir(), handleName); } function getMainIPCHandle(): string { return getIPCHandleName() + (process.platform === 'win32' ? '-sock' : '.sock'); } function getSharedIPCHandle(): string { return getIPCHandleName() + '-shared' + (process.platform === 'win32' ? '-sock' : '.sock'); } function uniqueUserId(): string { let username: string; if (platform.isWindows) { username = process.env.USERNAME; } else { username = process.env.USER; } if (!username) { return ''; // fail gracefully if there is no user name } // use sha256 to ensure the userid value can be used in filenames and are unique return crypto.createHash('sha256').update(username).digest('hex').substr(0, 6); } type OptionBag = { [opt: string]: boolean; }; function parseOpts(argv: string[]): OptionBag { return argv .filter(a => /^-/.test(a)) .map(a => a.replace(/^-*/, '')) .reduce((r, a) => { r[a] = true; return r; }, <OptionBag>{}); } function parsePathArguments(argv: string[], gotoLineMode?: boolean): string[] { return arrays.coalesce( // no invalid paths arrays.distinct( // no duplicates argv.filter(a => !(/^-/.test(a))) // arguments without leading "-" .map((arg) => { let pathCandidate = arg; let parsedPath: IParsedPath; if (gotoLineMode) { parsedPath = parseLineAndColumnAware(arg); pathCandidate = parsedPath.path; } if (pathCandidate) { pathCandidate = preparePath(pathCandidate); } let realPath: string; try { realPath = fs.realpathSync(pathCandidate); } catch (error) { // in case of an error, assume the user wants to create this file // if the path is relative, we join it to the cwd realPath = path.normalize(path.isAbsolute(pathCandidate) ? pathCandidate : path.join(currentWorkingDirectory, pathCandidate)); } if (!paths.isValidBasename(path.basename(realPath))) { return null; // do not allow invalid file names } if (gotoLineMode) { parsedPath.path = realPath; return toLineAndColumnPath(parsedPath); } return realPath; }), (element) => { return element && (platform.isWindows || platform.isMacintosh) ? element.toLowerCase() : element; // only linux is case sensitive on the fs } ) ); } function preparePath(p: string): string { // Trim trailing quotes if (platform.isWindows) { p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498 } // Trim whitespaces p = strings.trim(strings.trim(p, ' '), '\t'); if (platform.isWindows) { // Resolve the path against cwd if it is relative p = path.resolve(currentWorkingDirectory, p); // Trim trailing '.' chars on Windows to prevent invalid file names p = strings.rtrim(p, '.'); } return p; } function normalizePath(p?: string): string { return p ? path.normalize(p) : p; } function parseNumber(argv: string[], key: string, defaultValue?: number, fallbackValue?: number): number { let value: number; for (let i = 0; i < argv.length; i++) { let segments = argv[i].split('='); if (segments[0] === key) { value = Number(segments[1]) || defaultValue; break; } } return types.isNumber(value) ? value : fallbackValue; } function parseString(argv: string[], key: string, defaultValue?: string, fallbackValue?: string): string { let value: string; for (let i = 0; i < argv.length; i++) { let segments = argv[i].split('='); if (segments[0] === key) { value = String(segments[1]) || defaultValue; break; } } return types.isString(value) ? strings.trim(value, '"') : fallbackValue; } export function getPlatformIdentifier(): string { if (process.platform === 'linux') { return `linux-${process.arch}`; } return process.platform; } export interface IParsedPath { path: string; line?: number; column?: number; } export function parseLineAndColumnAware(rawPath: string): IParsedPath { let segments = rawPath.split(':'); // C:\file.txt:<line>:<column> let path: string; let line: number = null; let column: number = null; segments.forEach(segment => { let segmentAsNumber = Number(segment); if (!types.isNumber(segmentAsNumber)) { path = !!path ? [path, segment].join(':') : segment; // a colon can well be part of a path (e.g. C:\...) } else if (line === null) { line = segmentAsNumber; } else if (column === null) { column = segmentAsNumber; } }); return { path: path, line: line !== null ? line : void 0, column: column !== null ? column : line !== null ? 1 : void 0 // if we have a line, make sure column is also set }; } export function toLineAndColumnPath(parsedPath: IParsedPath): string { let segments = [parsedPath.path]; if (types.isNumber(parsedPath.line)) { segments.push(String(parsedPath.line)); } if (types.isNumber(parsedPath.column)) { segments.push(String(parsedPath.column)); } return segments.join(':'); }
src/vs/workbench/electron-main/env.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00021611666306853294, 0.00017044013657141477, 0.00016175172640942037, 0.00017006200505420566, 0.00000773679403209826 ]
{ "id": 4, "code_window": [ "\t\t\t\t'problemMatcherType': {\n", "\t\t\t\t\t'oneOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 941 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/task.contribution'; import 'vs/workbench/parts/tasks/browser/taskQuickOpen'; import * as nls from 'vs/nls'; import * as Env from 'vs/base/common/flags'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import Severity from 'vs/base/common/severity'; import * as Objects from 'vs/base/common/objects'; import { IStringDictionary } from 'vs/base/common/collections'; import { Action } from 'vs/base/common/actions'; import * as Dom from 'vs/base/browser/dom'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { EventEmitter, ListenerUnbind } from 'vs/base/common/eventEmitter'; import * as Builder from 'vs/base/browser/builder'; import * as Types from 'vs/base/common/types'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { match } from 'vs/base/common/glob'; import { setTimeout } from 'vs/base/common/platform'; import { TerminateResponse } from 'vs/base/common/processes'; import { Registry } from 'vs/platform/platform'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IEventService } from 'vs/platform/event/common/event'; import { IEditor } from 'vs/platform/editor/common/editor'; import { IMessageService } from 'vs/platform/message/common/message'; import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration'; import { IFileService, FileChangesEvent, FileChangeType, EventType as FileEventType } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/platform/extensions/common/extensions'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry'); import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry'; import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService'; import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables'; import { ITextFileService, EventType } from 'vs/workbench/parts/files/common/files'; import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/parts/output/common/output'; import { ITaskSystem, ITaskSummary, ITaskRunResult, TaskError, TaskErrors, TaskConfiguration, TaskDescription, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem'; import { ITaskService, TaskServiceEvents } from 'vs/workbench/parts/tasks/common/taskService'; import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates'; import { LanguageServiceTaskSystem, LanguageServiceTaskConfiguration } from 'vs/workbench/parts/tasks/common/languageServiceTaskSystem'; import * as FileConfig from 'vs/workbench/parts/tasks/node/processRunnerConfiguration'; import { ProcessRunnerSystem } from 'vs/workbench/parts/tasks/node/processRunnerSystem'; import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector'; let $ = Builder.$; class AbstractTaskAction extends Action { protected taskService: ITaskService; protected telemetryService: ITelemetryService; constructor(id:string, label:string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label); this.taskService = taskService; this.telemetryService = telemetryService; } } class BuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.build'; public static TEXT = nls.localize('BuildAction.label','Run Build Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.build(); } } class TestAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.test'; public static TEXT = nls.localize('TestAction.label','Run Test Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.runTest(); } } class RebuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.rebuild'; public static TEXT = nls.localize('RebuildAction.label', 'Run Rebuild Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.rebuild(); } } class CleanAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.clean'; public static TEXT = nls.localize('CleanAction.label', 'Run Clean Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.clean(); } } class ConfigureTaskRunnerAction extends Action { public static ID = 'workbench.action.tasks.configureTaskRunner'; public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', 'Configure Task Runner'); private configurationService: IConfigurationService; private fileService: IFileService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private outputService: IOutputService; private messageService: IMessageService; private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(id, label); this.configurationService = configurationService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.outputService = outputService; this.messageService = messageService; this.quickOpenService = quickOpenService; } public run(event?:any): TPromise<IEditor> { if (!this.contextService.getWorkspace()) { this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.')); return TPromise.as(undefined); } let sideBySide = !!(event && (event.ctrlKey || event.metaKey)); return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => { return success; }, (err:any) => { ; return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner')}).then(selection => { if (!selection) { return undefined; } let contentPromise: TPromise<string>; if (selection.autoDetect) { this.outputService.showOutput(TaskService.OutputChannel); this.outputService.append(TaskService.OutputChannel, nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n'); let detector = new ProcessRunnerDetector(this.fileService, this.contextService, new SystemVariables(this.editorService, this.contextService)); contentPromise = detector.detect(false, selection.id).then((value) => { let config = value.config; if (value.stderr && value.stderr.length > 0) { value.stderr.forEach((line) => { this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.')); return selection.content; } else if (config) { if (value.stdout && value.stdout.length > 0) { value.stdout.forEach(line => this.outputService.append(TaskService.OutputChannel, line + '\n')); } let content = JSON.stringify(config, null, '\t'); content = [ '{', '\t// See http://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', ].join('\n') + content.substr(1); return content; } else { return selection.content; } }); } else { contentPromise = TPromise.as(selection.content); } return contentPromise.then(content => { return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content); }); }); }).then((stat) => { if (!stat) { return undefined; } // // (2) Open editor with configuration file return this.editorService.openEditor({ resource: stat.resource, options: { forceOpen: true } }, sideBySide); }, (error) => { throw new Error(nls.localize('ConfigureTaskRunnerAction.failed', "Unable to create the 'tasks.json' file inside the '.vscode' folder. Consult the task output for details.")); }); } } class CloseMessageAction extends Action { public static ID = 'workbench.action.build.closeMessage'; public static TEXT = nls.localize('CloseMessageAction.label', 'Close'); public closeFunction: () => void; constructor() { super(CloseMessageAction.ID, CloseMessageAction.TEXT); } public run(): Promise { if (this.closeFunction) { this.closeFunction(); } return TPromise.as(null); } } class TerminateAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.terminate'; public static TEXT = nls.localize('TerminateAction.label', 'Terminate Running Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.isActive().then((active) => { if (active) { return this.taskService.terminate().then((response) => { if (response.success) { return; } else { return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task')); } }); } }); } } class ShowLogAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.showLog'; public static TEXT = nls.localize('ShowLogAction.label', 'Show Task Log'); private outputService: IOutputService; constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService, @IOutputService outputService:IOutputService) { super(id, label, taskService, telemetryService); this.outputService = outputService; } public run(): Promise { return this.outputService.showOutput(TaskService.OutputChannel); } } class RunTaskAction extends Action { public static ID = 'workbench.action.tasks.runTask'; public static TEXT = nls.localize('RunTaskAction.label', "Run Task"); private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IQuickOpenService quickOpenService:IQuickOpenService) { super(id, label); this.quickOpenService = quickOpenService; } public run(event?:any): Promise { this.quickOpenService.show('task '); return TPromise.as(null); } } class StatusBarItem implements IStatusbarItem { private quickOpenService: IQuickOpenService; private markerService: IMarkerService; private taskService:ITaskService; private outputService: IOutputService; private intervalToken: any; private activeCount: number; private static progressChars:string = '|/-\\'; constructor(@IQuickOpenService quickOpenService:IQuickOpenService, @IMarkerService markerService:IMarkerService, @IOutputService outputService:IOutputService, @ITaskService taskService:ITaskService) { this.quickOpenService = quickOpenService; this.markerService = markerService; this.outputService = outputService; this.taskService = taskService; this.activeCount = 0; } public render(container: HTMLElement): IDisposable { let callOnDispose: IDisposable[] = [], element = document.createElement('div'), // icon = document.createElement('a'), progress = document.createElement('div'), label = document.createElement('a'), error = document.createElement('div'), warning = document.createElement('div'), info = document.createElement('div'); Dom.addClass(element, 'task-statusbar-item'); // dom.addClass(icon, 'task-statusbar-item-icon'); // element.appendChild(icon); Dom.addClass(progress, 'task-statusbar-item-progress'); element.appendChild(progress); progress.innerHTML = StatusBarItem.progressChars[0]; $(progress).hide(); Dom.addClass(label, 'task-statusbar-item-label'); element.appendChild(label); Dom.addClass(error, 'task-statusbar-item-label-error'); error.innerHTML = '0'; label.appendChild(error); Dom.addClass(warning, 'task-statusbar-item-label-warning'); warning.innerHTML = '0'; label.appendChild(warning); Dom.addClass(info, 'task-statusbar-item-label-info'); label.appendChild(info); $(info).hide(); // callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => { // this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true); // })); callOnDispose.push(Dom.addDisposableListener(label, 'click', (e:MouseEvent) => { this.quickOpenService.show('!'); })); let updateStatus = (element:HTMLDivElement, stats:number): boolean => { if (stats > 0) { element.innerHTML = stats.toString(); $(element).show(); return true; } else { $(element).hide(); return false; } }; let manyMarkers = nls.localize('manyMarkers', "99+"); let updateLabel = (stats: MarkerStatistics) => { error.innerHTML = stats.errors < 100 ? stats.errors.toString() : manyMarkers; warning.innerHTML = stats.warnings < 100 ? stats.warnings.toString() : manyMarkers; updateStatus(info, stats.infos); }; this.markerService.onMarkerChanged((changedResources) => { updateLabel(this.markerService.getStatistics()); }); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => { this.activeCount++; if (this.activeCount === 1) { let index = 1; let chars = StatusBarItem.progressChars; progress.innerHTML = chars[0]; this.intervalToken = setInterval(() => { progress.innerHTML = chars[index]; index++; if (index >= chars.length) { index = 0; } }, 50); $(progress).show(); } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data:TaskServiceEventData) => { this.activeCount--; if (this.activeCount === 0) { $(progress).hide(); clearInterval(this.intervalToken); this.intervalToken = null; } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => { if (this.activeCount !== 0) { $(progress).hide(); if (this.intervalToken) { clearInterval(this.intervalToken); this.intervalToken = null; } this.activeCount = 0; } })); container.appendChild(element); return { dispose: () => { callOnDispose = dispose(callOnDispose); } }; } } interface TaskServiceEventData { error?: any; } class TaskService extends EventEmitter implements ITaskService { public serviceId = ITaskService; public static SERVICE_ID: string = 'taskService'; public static OutputChannel:string = 'Tasks'; private modeService: IModeService; private configurationService: IConfigurationService; private markerService: IMarkerService; private outputService: IOutputService; private messageService: IMessageService; private fileService: IFileService; private telemetryService: ITelemetryService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private textFileService: ITextFileService; private eventService: IEventService; private modelService: IModelService; private extensionService: IExtensionService; private quickOpenService: IQuickOpenService; private _taskSystemPromise: TPromise<ITaskSystem>; private _taskSystem: ITaskSystem; private taskSystemListeners: ListenerUnbind[]; private clearTaskSystemPromise: boolean; private fileChangesListener: ListenerUnbind; constructor(@IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService, @IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService:IWorkbenchEditorService, @IFileService fileService:IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService:ITextFileService, @ILifecycleService lifecycleService: ILifecycleService, @IEventService eventService: IEventService, @IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(); this.modeService = modeService; this.configurationService = configurationService; this.markerService = markerService; this.outputService = outputService; this.messageService = messageService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.telemetryService = telemetryService; this.textFileService = textFileService; this.eventService = eventService; this.modelService = modelService; this.extensionService = extensionService; this.quickOpenService = quickOpenService; this.taskSystemListeners = []; this.clearTaskSystemPromise = false; this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, () => { this.emit(TaskServiceEvents.ConfigChanged); if (this._taskSystem && this._taskSystem.isActiveSync()) { this.clearTaskSystemPromise = true; } else { this._taskSystem = null; this._taskSystemPromise = null; } this.disposeTaskSystemListeners(); }); lifecycleService.addBeforeShutdownParticipant(this); } private disposeTaskSystemListeners(): void { this.taskSystemListeners.forEach(unbind => unbind()); this.taskSystemListeners = []; } private disposeFileChangesListener(): void { if (this.fileChangesListener) { this.fileChangesListener(); this.fileChangesListener = null; } } private get taskSystemPromise(): TPromise<ITaskSystem> { if (!this._taskSystemPromise) { let variables = new SystemVariables(this.editorService, this.contextService); let clearOutput = true; this._taskSystemPromise = TPromise.as(this.configurationService.getConfiguration<TaskConfiguration>('tasks')).then((config: TaskConfiguration) => { let parseErrors: string[] = config ? (<any>config).$parseErrors : null; if (parseErrors) { let isAffected = false; for (let i = 0; i < parseErrors.length; i++) { if (/tasks\.json$/.test(parseErrors[i])) { isAffected = true; break; } } if (isAffected) { this.outputService.append(TaskService.OutputChannel, nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n')); this.outputService.showOutput(TaskService.OutputChannel, true); return TPromise.wrapError({}); } } let configPromise: TPromise<TaskConfiguration>; if (config) { if (this.isRunnerConfig(config) && this.hasDetectorSupport(<FileConfig.ExternalTaskRunnerConfiguration>config)) { let fileConfig = <FileConfig.ExternalTaskRunnerConfiguration>config; configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables, fileConfig).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); let detectedConfig = value.config; if (!detectedConfig) { return config; } let result: FileConfig.ExternalTaskRunnerConfiguration = Objects.clone(fileConfig); let configuredTasks: IStringDictionary<FileConfig.TaskDescription> = Object.create(null); if (!result.tasks) { if (detectedConfig.tasks) { result.tasks = detectedConfig.tasks; } } else { result.tasks.forEach(task => configuredTasks[task.taskName] = task); detectedConfig.tasks.forEach((task) => { if (!configuredTasks[task.taskName]) { result.tasks.push(task); } }); } return result; }); } else { configPromise = TPromise.as<TaskConfiguration>(config); } } else { configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); return value.config; }); } return configPromise.then((config) => { if (!config) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noConfiguration', 'No task runner configured.'), TaskErrors.NotConfigured); } let result: ITaskSystem = null; if (config.buildSystem === 'service') { result = new LanguageServiceTaskSystem(<LanguageServiceTaskConfiguration>config, this.telemetryService, this.modeService); } else if (this.isRunnerConfig(config)) { result = new ProcessRunnerSystem(<FileConfig.ExternalTaskRunnerConfiguration>config, variables, this.markerService, this.modelService, this.telemetryService, this.outputService, TaskService.OutputChannel, clearOutput); } if (result === null) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noBuildType', "No valid task runner configured. Supported task runners are 'service' and 'program'."), TaskErrors.NoValidTaskRunner); } this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event))); this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event))); this._taskSystem = result; return result; }, (err: any) => { this.handleError(err); return Promise.wrapError(err); }); }); } return this._taskSystemPromise; } private printStderr(stderr: string[]): boolean { let result = true; if (stderr && stderr.length > 0) { stderr.forEach((line) => { result = false; this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.outputService.showOutput(TaskService.OutputChannel, true); } return result; } private isRunnerConfig(config: TaskConfiguration): boolean { return !config.buildSystem || config.buildSystem === 'program'; } private hasDetectorSupport(config: FileConfig.ExternalTaskRunnerConfiguration): boolean { if (!config.command) { return false; } return ProcessRunnerDetector.supports(config.command); } public configureAction(): Action { return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this.configurationService, this.editorService, this.fileService, this.contextService, this.outputService, this.messageService, this.quickOpenService); } public build(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.build()); } public rebuild(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.rebuild()); } public clean(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.clean()); } public runTest(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.runTest()); } public run(taskIdentifier: string): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.run(taskIdentifier)); } private executeTarget(fn: (taskSystem: ITaskSystem) => ITaskRunResult): TPromise<ITaskSummary> { return this.textFileService.saveAll().then((value) => { return this.taskSystemPromise. then((taskSystem) => { return taskSystem.isActive().then((active) => { if (!active) { return fn(taskSystem); } else { throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask); } }); }). then((runResult: ITaskRunResult) => { if (runResult.restartOnFileChanges) { let pattern = runResult.restartOnFileChanges; this.fileChangesListener = this.eventService.addListener(FileEventType.FILE_CHANGES, (event: FileChangesEvent) => { let needsRestart = event.changes.some((change) => { return (change.type === FileChangeType.ADDED || change.type === FileChangeType.DELETED) && !!match(pattern, change.resource.fsPath); }); if (needsRestart) { this.terminate().done(() => { // We need to give the child process a change to stop. setTimeout(() => { this.executeTarget(fn); }, 2000); }); } }); } return runResult.promise.then((value) => { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } return value; }); }, (err: any) => { this.handleError(err); }); }); } public isActive(): TPromise<boolean> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => taskSystem.isActive()); } return TPromise.as(false); } public terminate(): TPromise<TerminateResponse> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => { return taskSystem.terminate(); }).then(response => { if (response.success) { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } this.emit(TaskServiceEvents.Terminated, {}); this.disposeFileChangesListener(); } return response; }); } return TPromise.as( { success: true} ); } public tasks(): TPromise<TaskDescription[]> { return this.taskSystemPromise.then(taskSystem => taskSystem.tasks()); } public beforeShutdown(): boolean | TPromise<boolean> { if (this._taskSystem && this._taskSystem.isActiveSync()) { if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({ message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'), primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task") })) { return this._taskSystem.terminate().then((response) => { if (response.success) { this.emit(TaskServiceEvents.Terminated, {}); this._taskSystem = null; this.disposeFileChangesListener(); this.disposeTaskSystemListeners(); return false; // no veto } return true; // veto }, (err) => { return true; // veto }); } else { return true; // veto } } return false; // Nothing to do here } private handleError(err:any):void { let showOutput = true; if (err instanceof TaskError) { let buildError = <TaskError>err; let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask; let needsTerminate = buildError.code === TaskErrors.RunningTask; if (needsConfig || needsTerminate) { let closeAction = new CloseMessageAction(); let action = needsConfig ? this.configureAction() : new TerminateAction(TerminateAction.ID, TerminateAction.TEXT, this, this.telemetryService); closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [closeAction, action ] }); } else { this.messageService.show(buildError.severity, buildError.message); } } else if (err instanceof Error) { let error = <Error>err; this.messageService.show(Severity.Error, error.message); } else if (Types.isString(err)) { this.messageService.show(Severity.Error, <string>err); } else { this.messageService.show(Severity.Error, nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.')); } if (showOutput) { this.outputService.showOutput(TaskService.OutputChannel, true); } } } export class TaskServiceParticipant implements IWorkbenchContribution { constructor(@IInstantiationService private instantiationService: IInstantiationService) { // Force loading the language worker service this.instantiationService.getInstance(ITaskService); } public getId(): string { return 'vs.taskService'; } } let tasksCategory = nls.localize('tasksCategory', "Tasks"); let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), tasksCategory); if (Env.enableTasks) { // Task Service registerSingleton(ITaskService, TaskService); // Actions workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(BuildAction, BuildAction.ID, BuildAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TestAction, TestAction.ID, TestAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_T }), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RebuildAction, RebuildAction.ID, RebuildAction.TEXT), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CleanAction, CleanAction.ID, CleanAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TerminateAction, TerminateAction.ID, TerminateAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowLogAction, ShowLogAction.ID, ShowLogAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RunTaskAction, RunTaskAction.ID, RunTaskAction.TEXT), tasksCategory); // Register Quick Open (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( 'vs/workbench/parts/tasks/browser/taskQuickOpen', 'QuickOpenHandler', 'task ', nls.localize('taskCommands', "Run Task") ) ); // Status bar let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar); statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */)); // Output channel let outputChannelRegistry = <IOutputChannelRegistry>Registry.as(OutputExt.OutputChannels); outputChannelRegistry.registerChannel(TaskService.OutputChannel); (<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench)).registerWorkbenchContribution(TaskServiceParticipant); // tasks.json validation let schemaId = 'vscode://schemas/tasks'; let schema : IJSONSchema = { 'id': schemaId, 'description': 'Task definition file', 'type': 'object', 'default': { 'version': '0.1.0', 'command': 'myCommand', 'isShellCommand': false, 'args': [], 'showOutput': 'always', 'tasks': [ { 'taskName': 'build', 'showOutput': 'silent', 'isBuildCommand': true, 'problemMatcher': ['$tsc', '$lessCompile'] } ] }, 'definitions': { 'showOutputType': { 'type': 'string', 'enum': ['always', 'silent', 'never'], 'default': 'silent' }, 'patternType': { 'anyOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/pattern' }, { 'type': 'array', 'items': { '$ref': '#/definitions/pattern' } } ] }, 'pattern': { 'default': { 'regexp': '^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$', 'file': 1, 'location': 2, 'message': 3 }, 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.pattern.regexp', 'The regular expression to find an error, warning or info in the output.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.file', 'The match group index of the filename. If omitted 1 is used.') }, 'location': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.location', 'The match group index of the problem\'s location. Valid location patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). If omitted line and column is assumed.') }, 'line': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.line', 'The match group index of the problem\'s line. Defaults to 2') }, 'column': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.column', 'The match group index of the problem\'s column. Defaults to 3') }, 'endLine': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endLine', 'The match group index of the problem\'s end line. Defaults to undefined') }, 'endColumn': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endColumn', 'The match group index of the problem\'s end column. Defaults to undefined') }, 'severity': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.severity', 'The match group index of the problem\'s severity. Defaults to undefined') }, 'code': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.code', 'The match group index of the problem\'s code. Defaults to undefined') }, 'message': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.message', 'The match group index of the message. If omitted it defaults to 4 if location is specified. Otherwise it defaults to 5.') }, 'loop': { 'type': 'boolean', 'description': nls.localize('JsonSchema.pattern.loop', 'In a multi line matcher loop indicated whether this pattern is executed in a loop as long as it matches. Can only specified on a last pattern in a multi line pattern.') } } }, 'problemMatcherType': { 'oneOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/problemMatcher' }, { 'type': 'array', 'items': { 'anyOf': [ { '$ref': '#/definitions/problemMatcher' }, { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] } ] } } ] }, 'watchingPattern': { 'type': 'object', 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.watchingPattern.regexp', 'The regular expression to detect the begin or end of a watching task.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.watchingPattern.file', 'The match group index of the filename. Can be omitted.') }, } }, 'problemMatcher': { 'type': 'object', 'additionalProperties': false, 'properties': { 'base': { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'], 'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.') }, 'owner': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.owner', 'The owner of the problem inside Code. Can be omitted if base is specified. Defaults to \'external\' if omitted and base is not specified.') }, 'severity': { 'type': 'string', 'enum': ['error', 'warning', 'info'], 'description': nls.localize('JsonSchema.problemMatcher.severity', 'The default severity for captures problems. Is used if the pattern doesn\'t define a match group for severity.') }, 'applyTo': { 'type': 'string', 'enum': ['allDocuments', 'openDocuments', 'closedDocuments'], 'description': nls.localize('JsonSchema.problemMatcher.applyTo', 'Controls if a problem reported on a text document is applied only to open, closed or all documents.') }, 'pattern': { '$ref': '#/definitions/patternType', 'description': nls.localize('JsonSchema.problemMatcher.pattern', 'A problem pattern or the name of a predefined problem pattern. Can be omitted if base is specified.') }, 'fileLocation': { 'oneOf': [ { 'type': 'string', 'enum': ['absolute', 'relative'] }, { 'type': 'array', 'items': { 'type': 'string' } } ], 'description': nls.localize('JsonSchema.problemMatcher.fileLocation', 'Defines how file names reported in a problem pattern should be interpreted.') }, 'watching': { 'type': 'object', 'additionalProperties': false, 'properties': { 'activeOnStart': { 'type': 'boolean', 'description': nls.localize('JsonSchema.problemMatcher.watching.activeOnStart', 'If set to true the watcher is in active mode when the task starts. This is equals of issuing a line that matches the beginPattern') }, 'beginsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.beginsPattern', 'If matched in the output the start of a watching task is signaled.') }, 'endsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.endsPattern', 'If matched in the output the end of a watching task is signaled.') } } }, 'watchedTaskBeginsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedBegin', 'A regular expression signaling that a watched tasks begins executing triggered through file watching.') }, 'watchedTaskEndsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedEnd', 'A regular expression signaling that a watched tasks ends executing.') } } }, 'baseTaskRunnerConfiguration': { 'type': 'object', 'properties': { 'command': { 'type': 'string', 'description': nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.') }, 'isShellCommand': { 'type': 'boolean', 'default': true, 'description': nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'), 'items': { 'type': 'string' } }, 'options': { 'type': 'object', 'description': nls.localize('JsonSchema.options', 'Additional command options'), 'properties': { 'cwd': { 'type': 'string', 'description': nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.') }, 'env': { 'type': 'object', 'additionalProperties': { 'type': 'string' }, 'description': nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.') } }, 'additionalProperties': { 'type': ['string', 'array', 'object'] } }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.') }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'promptOnClose': { 'type': 'boolean', 'description': nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'), 'default': false }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'), 'default': true }, 'taskSelector': { 'type': 'string', 'description': nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.') }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') }, 'tasks': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'), 'items': { 'type': 'object', '$ref': '#/definitions/taskDescription' } } } }, 'taskDescription': { 'type': 'object', 'required': ['taskName'], 'additionalProperties': false, 'properties': { 'taskName': { 'type': 'string', 'description': nls.localize('JsonSchema.tasks.taskName', "The task's name") }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks.args', 'Additional arguments passed to the command when this task is invoked.'), 'items': { 'type': 'string' } }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'), 'default': true }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.') }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'isBuildCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'), 'default': true }, 'isTestCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'), 'default': true }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') } }, 'defaultSnippets': [ { 'label': 'Empty task', 'body': { 'taskName': '{{taskName}}' } } ] } }, 'allOf': [ { 'type': 'object', 'required': ['version'], 'properties': { 'version': { 'type': 'string', 'enum': ['0.1.0'], 'description': nls.localize('JsonSchema.version', 'The config\'s version number') }, 'windows': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.windows', 'Windows specific build configuration') }, 'osx': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.mac', 'Mac specific build configuration') }, 'linux': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.linux', 'Linux specific build configuration') } } }, { '$ref': '#/definitions/baseTaskRunnerConfiguration' } ] }; let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(schemaId, schema); jsonRegistry.addSchemaFileAssociation('/.vscode/tasks.json', schemaId); }
src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.26250842213630676, 0.004343993496149778, 0.00016161389066837728, 0.0001731004740577191, 0.030838992446660995 ]
{ "id": 4, "code_window": [ "\t\t\t\t'problemMatcherType': {\n", "\t\t\t\t\t'oneOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 941 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; /* always keep in sync with cssTokenTypes */ export const TOKEN_SELECTOR = 'entity.name.selector'; export const TOKEN_SELECTOR_TAG = 'entity.name.tag'; export const TOKEN_PROPERTY = 'support.type.property-name'; export const TOKEN_VALUE = 'support.property-value'; export const TOKEN_AT_KEYWORD = 'keyword.control.at-rule';
src/vs/languages/sass/common/sassTokenTypes.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017408409621566534, 0.00017060586833395064, 0.0001671276259003207, 0.00017060586833395064, 0.000003478235157672316 ]
{ "id": 4, "code_window": [ "\t\t\t\t'problemMatcherType': {\n", "\t\t\t\t\t'oneOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 941 }
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS: [{ "name": "textmate/coffee-script.tmbundle", "version": "0.0.0", "license": "MIT", "repositoryURL": "https://github.com/textmate/coffee-script.tmbundle" }]
extensions/coffeescript/OSSREADME.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017100528930313885, 0.00017100528930313885, 0.00017100528930313885, 0.00017100528930313885, 0 ]
{ "id": 4, "code_window": [ "\t\t\t\t'problemMatcherType': {\n", "\t\t\t\t\t'oneOf': [\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t{\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 941 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "TaskSystemDetector.buildTaskDetected": "La tâche de génération nommée '{0}' a été détectée.", "TaskSystemDetector.noGruntProgram": "Grunt n'est pas installé sur votre système. Exécutez npm install -g grunt pour l'installer.", "TaskSystemDetector.noGulpProgram": "Gulp n'est pas installé sur votre système. Exécutez npm install -g gulp pour l'installer.", "TaskSystemDetector.noGulpTasks": "L'exécution de gulp --tasks-simple n'a listé aucune tâche. Avez-vous exécuté npm install ?", "TaskSystemDetector.noJakeProgram": "Jake n'est pas installé sur votre système. Exécutez npm install -g jake pour l'installer.", "TaskSystemDetector.noJakeTasks": "L'exécution de jake --tasks n'a listé aucune tâche. Avez-vous exécuté npm install ?", "TaskSystemDetector.noProgram": "Le programme {0} est introuvable. Message : {1}", "TaskSystemDetector.testTaskDetected": "La tâche de test nommée '{0}' a été détectée." }
i18n/fra/src/vs/workbench/parts/tasks/node/processRunnerDetector.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017653308168519288, 0.00017443581600673497, 0.00017233855032827705, 0.00017443581600673497, 0.0000020972656784579158 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t\t\t\t},\n", "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\t\t]\n", "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 955 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/task.contribution'; import 'vs/workbench/parts/tasks/browser/taskQuickOpen'; import * as nls from 'vs/nls'; import * as Env from 'vs/base/common/flags'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import Severity from 'vs/base/common/severity'; import * as Objects from 'vs/base/common/objects'; import { IStringDictionary } from 'vs/base/common/collections'; import { Action } from 'vs/base/common/actions'; import * as Dom from 'vs/base/browser/dom'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { EventEmitter, ListenerUnbind } from 'vs/base/common/eventEmitter'; import * as Builder from 'vs/base/browser/builder'; import * as Types from 'vs/base/common/types'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { match } from 'vs/base/common/glob'; import { setTimeout } from 'vs/base/common/platform'; import { TerminateResponse } from 'vs/base/common/processes'; import { Registry } from 'vs/platform/platform'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IEventService } from 'vs/platform/event/common/event'; import { IEditor } from 'vs/platform/editor/common/editor'; import { IMessageService } from 'vs/platform/message/common/message'; import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration'; import { IFileService, FileChangesEvent, FileChangeType, EventType as FileEventType } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/platform/extensions/common/extensions'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry'); import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry'; import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService'; import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables'; import { ITextFileService, EventType } from 'vs/workbench/parts/files/common/files'; import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/parts/output/common/output'; import { ITaskSystem, ITaskSummary, ITaskRunResult, TaskError, TaskErrors, TaskConfiguration, TaskDescription, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem'; import { ITaskService, TaskServiceEvents } from 'vs/workbench/parts/tasks/common/taskService'; import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates'; import { LanguageServiceTaskSystem, LanguageServiceTaskConfiguration } from 'vs/workbench/parts/tasks/common/languageServiceTaskSystem'; import * as FileConfig from 'vs/workbench/parts/tasks/node/processRunnerConfiguration'; import { ProcessRunnerSystem } from 'vs/workbench/parts/tasks/node/processRunnerSystem'; import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector'; let $ = Builder.$; class AbstractTaskAction extends Action { protected taskService: ITaskService; protected telemetryService: ITelemetryService; constructor(id:string, label:string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label); this.taskService = taskService; this.telemetryService = telemetryService; } } class BuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.build'; public static TEXT = nls.localize('BuildAction.label','Run Build Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.build(); } } class TestAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.test'; public static TEXT = nls.localize('TestAction.label','Run Test Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.runTest(); } } class RebuildAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.rebuild'; public static TEXT = nls.localize('RebuildAction.label', 'Run Rebuild Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.rebuild(); } } class CleanAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.clean'; public static TEXT = nls.localize('CleanAction.label', 'Run Clean Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.clean(); } } class ConfigureTaskRunnerAction extends Action { public static ID = 'workbench.action.tasks.configureTaskRunner'; public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', 'Configure Task Runner'); private configurationService: IConfigurationService; private fileService: IFileService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private outputService: IOutputService; private messageService: IMessageService; private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(id, label); this.configurationService = configurationService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.outputService = outputService; this.messageService = messageService; this.quickOpenService = quickOpenService; } public run(event?:any): TPromise<IEditor> { if (!this.contextService.getWorkspace()) { this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.')); return TPromise.as(undefined); } let sideBySide = !!(event && (event.ctrlKey || event.metaKey)); return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => { return success; }, (err:any) => { ; return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner')}).then(selection => { if (!selection) { return undefined; } let contentPromise: TPromise<string>; if (selection.autoDetect) { this.outputService.showOutput(TaskService.OutputChannel); this.outputService.append(TaskService.OutputChannel, nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n'); let detector = new ProcessRunnerDetector(this.fileService, this.contextService, new SystemVariables(this.editorService, this.contextService)); contentPromise = detector.detect(false, selection.id).then((value) => { let config = value.config; if (value.stderr && value.stderr.length > 0) { value.stderr.forEach((line) => { this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.')); return selection.content; } else if (config) { if (value.stdout && value.stdout.length > 0) { value.stdout.forEach(line => this.outputService.append(TaskService.OutputChannel, line + '\n')); } let content = JSON.stringify(config, null, '\t'); content = [ '{', '\t// See http://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', ].join('\n') + content.substr(1); return content; } else { return selection.content; } }); } else { contentPromise = TPromise.as(selection.content); } return contentPromise.then(content => { return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content); }); }); }).then((stat) => { if (!stat) { return undefined; } // // (2) Open editor with configuration file return this.editorService.openEditor({ resource: stat.resource, options: { forceOpen: true } }, sideBySide); }, (error) => { throw new Error(nls.localize('ConfigureTaskRunnerAction.failed', "Unable to create the 'tasks.json' file inside the '.vscode' folder. Consult the task output for details.")); }); } } class CloseMessageAction extends Action { public static ID = 'workbench.action.build.closeMessage'; public static TEXT = nls.localize('CloseMessageAction.label', 'Close'); public closeFunction: () => void; constructor() { super(CloseMessageAction.ID, CloseMessageAction.TEXT); } public run(): Promise { if (this.closeFunction) { this.closeFunction(); } return TPromise.as(null); } } class TerminateAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.terminate'; public static TEXT = nls.localize('TerminateAction.label', 'Terminate Running Task'); constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) { super(id, label, taskService, telemetryService); } public run(): Promise { return this.taskService.isActive().then((active) => { if (active) { return this.taskService.terminate().then((response) => { if (response.success) { return; } else { return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task')); } }); } }); } } class ShowLogAction extends AbstractTaskAction { public static ID = 'workbench.action.tasks.showLog'; public static TEXT = nls.localize('ShowLogAction.label', 'Show Task Log'); private outputService: IOutputService; constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService, @IOutputService outputService:IOutputService) { super(id, label, taskService, telemetryService); this.outputService = outputService; } public run(): Promise { return this.outputService.showOutput(TaskService.OutputChannel); } } class RunTaskAction extends Action { public static ID = 'workbench.action.tasks.runTask'; public static TEXT = nls.localize('RunTaskAction.label', "Run Task"); private quickOpenService: IQuickOpenService; constructor(id: string, label: string, @IQuickOpenService quickOpenService:IQuickOpenService) { super(id, label); this.quickOpenService = quickOpenService; } public run(event?:any): Promise { this.quickOpenService.show('task '); return TPromise.as(null); } } class StatusBarItem implements IStatusbarItem { private quickOpenService: IQuickOpenService; private markerService: IMarkerService; private taskService:ITaskService; private outputService: IOutputService; private intervalToken: any; private activeCount: number; private static progressChars:string = '|/-\\'; constructor(@IQuickOpenService quickOpenService:IQuickOpenService, @IMarkerService markerService:IMarkerService, @IOutputService outputService:IOutputService, @ITaskService taskService:ITaskService) { this.quickOpenService = quickOpenService; this.markerService = markerService; this.outputService = outputService; this.taskService = taskService; this.activeCount = 0; } public render(container: HTMLElement): IDisposable { let callOnDispose: IDisposable[] = [], element = document.createElement('div'), // icon = document.createElement('a'), progress = document.createElement('div'), label = document.createElement('a'), error = document.createElement('div'), warning = document.createElement('div'), info = document.createElement('div'); Dom.addClass(element, 'task-statusbar-item'); // dom.addClass(icon, 'task-statusbar-item-icon'); // element.appendChild(icon); Dom.addClass(progress, 'task-statusbar-item-progress'); element.appendChild(progress); progress.innerHTML = StatusBarItem.progressChars[0]; $(progress).hide(); Dom.addClass(label, 'task-statusbar-item-label'); element.appendChild(label); Dom.addClass(error, 'task-statusbar-item-label-error'); error.innerHTML = '0'; label.appendChild(error); Dom.addClass(warning, 'task-statusbar-item-label-warning'); warning.innerHTML = '0'; label.appendChild(warning); Dom.addClass(info, 'task-statusbar-item-label-info'); label.appendChild(info); $(info).hide(); // callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => { // this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true); // })); callOnDispose.push(Dom.addDisposableListener(label, 'click', (e:MouseEvent) => { this.quickOpenService.show('!'); })); let updateStatus = (element:HTMLDivElement, stats:number): boolean => { if (stats > 0) { element.innerHTML = stats.toString(); $(element).show(); return true; } else { $(element).hide(); return false; } }; let manyMarkers = nls.localize('manyMarkers', "99+"); let updateLabel = (stats: MarkerStatistics) => { error.innerHTML = stats.errors < 100 ? stats.errors.toString() : manyMarkers; warning.innerHTML = stats.warnings < 100 ? stats.warnings.toString() : manyMarkers; updateStatus(info, stats.infos); }; this.markerService.onMarkerChanged((changedResources) => { updateLabel(this.markerService.getStatistics()); }); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => { this.activeCount++; if (this.activeCount === 1) { let index = 1; let chars = StatusBarItem.progressChars; progress.innerHTML = chars[0]; this.intervalToken = setInterval(() => { progress.innerHTML = chars[index]; index++; if (index >= chars.length) { index = 0; } }, 50); $(progress).show(); } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data:TaskServiceEventData) => { this.activeCount--; if (this.activeCount === 0) { $(progress).hide(); clearInterval(this.intervalToken); this.intervalToken = null; } })); callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => { if (this.activeCount !== 0) { $(progress).hide(); if (this.intervalToken) { clearInterval(this.intervalToken); this.intervalToken = null; } this.activeCount = 0; } })); container.appendChild(element); return { dispose: () => { callOnDispose = dispose(callOnDispose); } }; } } interface TaskServiceEventData { error?: any; } class TaskService extends EventEmitter implements ITaskService { public serviceId = ITaskService; public static SERVICE_ID: string = 'taskService'; public static OutputChannel:string = 'Tasks'; private modeService: IModeService; private configurationService: IConfigurationService; private markerService: IMarkerService; private outputService: IOutputService; private messageService: IMessageService; private fileService: IFileService; private telemetryService: ITelemetryService; private editorService: IWorkbenchEditorService; private contextService: IWorkspaceContextService; private textFileService: ITextFileService; private eventService: IEventService; private modelService: IModelService; private extensionService: IExtensionService; private quickOpenService: IQuickOpenService; private _taskSystemPromise: TPromise<ITaskSystem>; private _taskSystem: ITaskSystem; private taskSystemListeners: ListenerUnbind[]; private clearTaskSystemPromise: boolean; private fileChangesListener: ListenerUnbind; constructor(@IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService, @IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService:IWorkbenchEditorService, @IFileService fileService:IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService:ITextFileService, @ILifecycleService lifecycleService: ILifecycleService, @IEventService eventService: IEventService, @IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService, @IQuickOpenService quickOpenService: IQuickOpenService) { super(); this.modeService = modeService; this.configurationService = configurationService; this.markerService = markerService; this.outputService = outputService; this.messageService = messageService; this.editorService = editorService; this.fileService = fileService; this.contextService = contextService; this.telemetryService = telemetryService; this.textFileService = textFileService; this.eventService = eventService; this.modelService = modelService; this.extensionService = extensionService; this.quickOpenService = quickOpenService; this.taskSystemListeners = []; this.clearTaskSystemPromise = false; this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, () => { this.emit(TaskServiceEvents.ConfigChanged); if (this._taskSystem && this._taskSystem.isActiveSync()) { this.clearTaskSystemPromise = true; } else { this._taskSystem = null; this._taskSystemPromise = null; } this.disposeTaskSystemListeners(); }); lifecycleService.addBeforeShutdownParticipant(this); } private disposeTaskSystemListeners(): void { this.taskSystemListeners.forEach(unbind => unbind()); this.taskSystemListeners = []; } private disposeFileChangesListener(): void { if (this.fileChangesListener) { this.fileChangesListener(); this.fileChangesListener = null; } } private get taskSystemPromise(): TPromise<ITaskSystem> { if (!this._taskSystemPromise) { let variables = new SystemVariables(this.editorService, this.contextService); let clearOutput = true; this._taskSystemPromise = TPromise.as(this.configurationService.getConfiguration<TaskConfiguration>('tasks')).then((config: TaskConfiguration) => { let parseErrors: string[] = config ? (<any>config).$parseErrors : null; if (parseErrors) { let isAffected = false; for (let i = 0; i < parseErrors.length; i++) { if (/tasks\.json$/.test(parseErrors[i])) { isAffected = true; break; } } if (isAffected) { this.outputService.append(TaskService.OutputChannel, nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n')); this.outputService.showOutput(TaskService.OutputChannel, true); return TPromise.wrapError({}); } } let configPromise: TPromise<TaskConfiguration>; if (config) { if (this.isRunnerConfig(config) && this.hasDetectorSupport(<FileConfig.ExternalTaskRunnerConfiguration>config)) { let fileConfig = <FileConfig.ExternalTaskRunnerConfiguration>config; configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables, fileConfig).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); let detectedConfig = value.config; if (!detectedConfig) { return config; } let result: FileConfig.ExternalTaskRunnerConfiguration = Objects.clone(fileConfig); let configuredTasks: IStringDictionary<FileConfig.TaskDescription> = Object.create(null); if (!result.tasks) { if (detectedConfig.tasks) { result.tasks = detectedConfig.tasks; } } else { result.tasks.forEach(task => configuredTasks[task.taskName] = task); detectedConfig.tasks.forEach((task) => { if (!configuredTasks[task.taskName]) { result.tasks.push(task); } }); } return result; }); } else { configPromise = TPromise.as<TaskConfiguration>(config); } } else { configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables).detect(true).then((value) => { clearOutput = this.printStderr(value.stderr); return value.config; }); } return configPromise.then((config) => { if (!config) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noConfiguration', 'No task runner configured.'), TaskErrors.NotConfigured); } let result: ITaskSystem = null; if (config.buildSystem === 'service') { result = new LanguageServiceTaskSystem(<LanguageServiceTaskConfiguration>config, this.telemetryService, this.modeService); } else if (this.isRunnerConfig(config)) { result = new ProcessRunnerSystem(<FileConfig.ExternalTaskRunnerConfiguration>config, variables, this.markerService, this.modelService, this.telemetryService, this.outputService, TaskService.OutputChannel, clearOutput); } if (result === null) { this._taskSystemPromise = null; throw new TaskError(Severity.Info, nls.localize('TaskSystem.noBuildType', "No valid task runner configured. Supported task runners are 'service' and 'program'."), TaskErrors.NoValidTaskRunner); } this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event))); this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event))); this._taskSystem = result; return result; }, (err: any) => { this.handleError(err); return Promise.wrapError(err); }); }); } return this._taskSystemPromise; } private printStderr(stderr: string[]): boolean { let result = true; if (stderr && stderr.length > 0) { stderr.forEach((line) => { result = false; this.outputService.append(TaskService.OutputChannel, line + '\n'); }); this.outputService.showOutput(TaskService.OutputChannel, true); } return result; } private isRunnerConfig(config: TaskConfiguration): boolean { return !config.buildSystem || config.buildSystem === 'program'; } private hasDetectorSupport(config: FileConfig.ExternalTaskRunnerConfiguration): boolean { if (!config.command) { return false; } return ProcessRunnerDetector.supports(config.command); } public configureAction(): Action { return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this.configurationService, this.editorService, this.fileService, this.contextService, this.outputService, this.messageService, this.quickOpenService); } public build(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.build()); } public rebuild(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.rebuild()); } public clean(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.clean()); } public runTest(): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.runTest()); } public run(taskIdentifier: string): TPromise<ITaskSummary> { return this.executeTarget(taskSystem => taskSystem.run(taskIdentifier)); } private executeTarget(fn: (taskSystem: ITaskSystem) => ITaskRunResult): TPromise<ITaskSummary> { return this.textFileService.saveAll().then((value) => { return this.taskSystemPromise. then((taskSystem) => { return taskSystem.isActive().then((active) => { if (!active) { return fn(taskSystem); } else { throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask); } }); }). then((runResult: ITaskRunResult) => { if (runResult.restartOnFileChanges) { let pattern = runResult.restartOnFileChanges; this.fileChangesListener = this.eventService.addListener(FileEventType.FILE_CHANGES, (event: FileChangesEvent) => { let needsRestart = event.changes.some((change) => { return (change.type === FileChangeType.ADDED || change.type === FileChangeType.DELETED) && !!match(pattern, change.resource.fsPath); }); if (needsRestart) { this.terminate().done(() => { // We need to give the child process a change to stop. setTimeout(() => { this.executeTarget(fn); }, 2000); }); } }); } return runResult.promise.then((value) => { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } return value; }); }, (err: any) => { this.handleError(err); }); }); } public isActive(): TPromise<boolean> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => taskSystem.isActive()); } return TPromise.as(false); } public terminate(): TPromise<TerminateResponse> { if (this._taskSystemPromise) { return this.taskSystemPromise.then(taskSystem => { return taskSystem.terminate(); }).then(response => { if (response.success) { if (this.clearTaskSystemPromise) { this._taskSystemPromise = null; this.clearTaskSystemPromise = false; } this.emit(TaskServiceEvents.Terminated, {}); this.disposeFileChangesListener(); } return response; }); } return TPromise.as( { success: true} ); } public tasks(): TPromise<TaskDescription[]> { return this.taskSystemPromise.then(taskSystem => taskSystem.tasks()); } public beforeShutdown(): boolean | TPromise<boolean> { if (this._taskSystem && this._taskSystem.isActiveSync()) { if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({ message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'), primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task") })) { return this._taskSystem.terminate().then((response) => { if (response.success) { this.emit(TaskServiceEvents.Terminated, {}); this._taskSystem = null; this.disposeFileChangesListener(); this.disposeTaskSystemListeners(); return false; // no veto } return true; // veto }, (err) => { return true; // veto }); } else { return true; // veto } } return false; // Nothing to do here } private handleError(err:any):void { let showOutput = true; if (err instanceof TaskError) { let buildError = <TaskError>err; let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask; let needsTerminate = buildError.code === TaskErrors.RunningTask; if (needsConfig || needsTerminate) { let closeAction = new CloseMessageAction(); let action = needsConfig ? this.configureAction() : new TerminateAction(TerminateAction.ID, TerminateAction.TEXT, this, this.telemetryService); closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [closeAction, action ] }); } else { this.messageService.show(buildError.severity, buildError.message); } } else if (err instanceof Error) { let error = <Error>err; this.messageService.show(Severity.Error, error.message); } else if (Types.isString(err)) { this.messageService.show(Severity.Error, <string>err); } else { this.messageService.show(Severity.Error, nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.')); } if (showOutput) { this.outputService.showOutput(TaskService.OutputChannel, true); } } } export class TaskServiceParticipant implements IWorkbenchContribution { constructor(@IInstantiationService private instantiationService: IInstantiationService) { // Force loading the language worker service this.instantiationService.getInstance(ITaskService); } public getId(): string { return 'vs.taskService'; } } let tasksCategory = nls.localize('tasksCategory', "Tasks"); let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), tasksCategory); if (Env.enableTasks) { // Task Service registerSingleton(ITaskService, TaskService); // Actions workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(BuildAction, BuildAction.ID, BuildAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TestAction, TestAction.ID, TestAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_T }), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RebuildAction, RebuildAction.ID, RebuildAction.TEXT), tasksCategory); // workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CleanAction, CleanAction.ID, CleanAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TerminateAction, TerminateAction.ID, TerminateAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowLogAction, ShowLogAction.ID, ShowLogAction.TEXT), tasksCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RunTaskAction, RunTaskAction.ID, RunTaskAction.TEXT), tasksCategory); // Register Quick Open (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler( new QuickOpenHandlerDescriptor( 'vs/workbench/parts/tasks/browser/taskQuickOpen', 'QuickOpenHandler', 'task ', nls.localize('taskCommands', "Run Task") ) ); // Status bar let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar); statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */)); // Output channel let outputChannelRegistry = <IOutputChannelRegistry>Registry.as(OutputExt.OutputChannels); outputChannelRegistry.registerChannel(TaskService.OutputChannel); (<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench)).registerWorkbenchContribution(TaskServiceParticipant); // tasks.json validation let schemaId = 'vscode://schemas/tasks'; let schema : IJSONSchema = { 'id': schemaId, 'description': 'Task definition file', 'type': 'object', 'default': { 'version': '0.1.0', 'command': 'myCommand', 'isShellCommand': false, 'args': [], 'showOutput': 'always', 'tasks': [ { 'taskName': 'build', 'showOutput': 'silent', 'isBuildCommand': true, 'problemMatcher': ['$tsc', '$lessCompile'] } ] }, 'definitions': { 'showOutputType': { 'type': 'string', 'enum': ['always', 'silent', 'never'], 'default': 'silent' }, 'patternType': { 'anyOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/pattern' }, { 'type': 'array', 'items': { '$ref': '#/definitions/pattern' } } ] }, 'pattern': { 'default': { 'regexp': '^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$', 'file': 1, 'location': 2, 'message': 3 }, 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.pattern.regexp', 'The regular expression to find an error, warning or info in the output.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.file', 'The match group index of the filename. If omitted 1 is used.') }, 'location': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.location', 'The match group index of the problem\'s location. Valid location patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). If omitted line and column is assumed.') }, 'line': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.line', 'The match group index of the problem\'s line. Defaults to 2') }, 'column': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.column', 'The match group index of the problem\'s column. Defaults to 3') }, 'endLine': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endLine', 'The match group index of the problem\'s end line. Defaults to undefined') }, 'endColumn': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.endColumn', 'The match group index of the problem\'s end column. Defaults to undefined') }, 'severity': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.severity', 'The match group index of the problem\'s severity. Defaults to undefined') }, 'code': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.code', 'The match group index of the problem\'s code. Defaults to undefined') }, 'message': { 'type': 'integer', 'description': nls.localize('JsonSchema.pattern.message', 'The match group index of the message. If omitted it defaults to 4 if location is specified. Otherwise it defaults to 5.') }, 'loop': { 'type': 'boolean', 'description': nls.localize('JsonSchema.pattern.loop', 'In a multi line matcher loop indicated whether this pattern is executed in a loop as long as it matches. Can only specified on a last pattern in a multi line pattern.') } } }, 'problemMatcherType': { 'oneOf': [ { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] }, { '$ref': '#/definitions/problemMatcher' }, { 'type': 'array', 'items': { 'anyOf': [ { '$ref': '#/definitions/problemMatcher' }, { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'] } ] } } ] }, 'watchingPattern': { 'type': 'object', 'additionalProperties': false, 'properties': { 'regexp': { 'type': 'string', 'description': nls.localize('JsonSchema.watchingPattern.regexp', 'The regular expression to detect the begin or end of a watching task.') }, 'file': { 'type': 'integer', 'description': nls.localize('JsonSchema.watchingPattern.file', 'The match group index of the filename. Can be omitted.') }, } }, 'problemMatcher': { 'type': 'object', 'additionalProperties': false, 'properties': { 'base': { 'type': 'string', 'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'], 'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.') }, 'owner': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.owner', 'The owner of the problem inside Code. Can be omitted if base is specified. Defaults to \'external\' if omitted and base is not specified.') }, 'severity': { 'type': 'string', 'enum': ['error', 'warning', 'info'], 'description': nls.localize('JsonSchema.problemMatcher.severity', 'The default severity for captures problems. Is used if the pattern doesn\'t define a match group for severity.') }, 'applyTo': { 'type': 'string', 'enum': ['allDocuments', 'openDocuments', 'closedDocuments'], 'description': nls.localize('JsonSchema.problemMatcher.applyTo', 'Controls if a problem reported on a text document is applied only to open, closed or all documents.') }, 'pattern': { '$ref': '#/definitions/patternType', 'description': nls.localize('JsonSchema.problemMatcher.pattern', 'A problem pattern or the name of a predefined problem pattern. Can be omitted if base is specified.') }, 'fileLocation': { 'oneOf': [ { 'type': 'string', 'enum': ['absolute', 'relative'] }, { 'type': 'array', 'items': { 'type': 'string' } } ], 'description': nls.localize('JsonSchema.problemMatcher.fileLocation', 'Defines how file names reported in a problem pattern should be interpreted.') }, 'watching': { 'type': 'object', 'additionalProperties': false, 'properties': { 'activeOnStart': { 'type': 'boolean', 'description': nls.localize('JsonSchema.problemMatcher.watching.activeOnStart', 'If set to true the watcher is in active mode when the task starts. This is equals of issuing a line that matches the beginPattern') }, 'beginsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.beginsPattern', 'If matched in the output the start of a watching task is signaled.') }, 'endsPattern': { 'oneOf': [ { 'type': 'string' }, { 'type': '#/definitions/watchingPattern' } ], 'description': nls.localize('JsonSchema.problemMatcher.watching.endsPattern', 'If matched in the output the end of a watching task is signaled.') } } }, 'watchedTaskBeginsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedBegin', 'A regular expression signaling that a watched tasks begins executing triggered through file watching.') }, 'watchedTaskEndsRegExp': { 'type': 'string', 'description': nls.localize('JsonSchema.problemMatcher.watchedEnd', 'A regular expression signaling that a watched tasks ends executing.') } } }, 'baseTaskRunnerConfiguration': { 'type': 'object', 'properties': { 'command': { 'type': 'string', 'description': nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.') }, 'isShellCommand': { 'type': 'boolean', 'default': true, 'description': nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'), 'items': { 'type': 'string' } }, 'options': { 'type': 'object', 'description': nls.localize('JsonSchema.options', 'Additional command options'), 'properties': { 'cwd': { 'type': 'string', 'description': nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.') }, 'env': { 'type': 'object', 'additionalProperties': { 'type': 'string' }, 'description': nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.') } }, 'additionalProperties': { 'type': ['string', 'array', 'object'] } }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.') }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'promptOnClose': { 'type': 'boolean', 'description': nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'), 'default': false }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'), 'default': true }, 'taskSelector': { 'type': 'string', 'description': nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.') }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') }, 'tasks': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'), 'items': { 'type': 'object', '$ref': '#/definitions/taskDescription' } } } }, 'taskDescription': { 'type': 'object', 'required': ['taskName'], 'additionalProperties': false, 'properties': { 'taskName': { 'type': 'string', 'description': nls.localize('JsonSchema.tasks.taskName', "The task's name") }, 'args': { 'type': 'array', 'description': nls.localize('JsonSchema.tasks.args', 'Additional arguments passed to the command when this task is invoked.'), 'items': { 'type': 'string' } }, 'suppressTaskName': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'), 'default': true }, 'showOutput': { '$ref': '#/definitions/showOutputType', 'description': nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.') }, 'echoCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'), 'default': true }, 'isWatching': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'), 'default': true }, 'isBuildCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'), 'default': true }, 'isTestCommand': { 'type': 'boolean', 'description': nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'), 'default': true }, 'problemMatcher': { '$ref': '#/definitions/problemMatcherType', 'description': nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') } }, 'defaultSnippets': [ { 'label': 'Empty task', 'body': { 'taskName': '{{taskName}}' } } ] } }, 'allOf': [ { 'type': 'object', 'required': ['version'], 'properties': { 'version': { 'type': 'string', 'enum': ['0.1.0'], 'description': nls.localize('JsonSchema.version', 'The config\'s version number') }, 'windows': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.windows', 'Windows specific build configuration') }, 'osx': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.mac', 'Mac specific build configuration') }, 'linux': { '$ref': '#/definitions/baseTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.linux', 'Linux specific build configuration') } } }, { '$ref': '#/definitions/baseTaskRunnerConfiguration' } ] }; let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(schemaId, schema); jsonRegistry.addSchemaFileAssociation('/.vscode/tasks.json', schemaId); }
src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.9934804439544678, 0.016206033527851105, 0.00015864300075918436, 0.00017171032959595323, 0.12481063604354858 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t\t\t\t},\n", "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\t\t]\n", "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 955 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "altKey": "Alt", "altKey.long": "Alt", "cmdKey": "Commande", "cmdKey.long": "Commande", "ctrlKey": "Ctrl", "ctrlKey.long": "Contrôle", "shiftKey": "Maj", "shiftKey.long": "Maj", "windowsKey": "Windows", "windowsKey.long": "Windows" }
i18n/fra/src/vs/base/common/keyCodes.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.0001746107591316104, 0.00017254338308703154, 0.0001704760070424527, 0.00017254338308703154, 0.0000020673760445788503 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t\t\t\t},\n", "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\t\t]\n", "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 955 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import {createDecorator, ServiceIdentifier} from 'vs/platform/instantiation/common/instantiation'; import {IEditorService, IEditor, IEditorInput, IEditorOptions, Position, IResourceInput, IEditorModel, ITextEditorModel} from 'vs/platform/editor/common/editor'; export enum EditorArrangement { MINIMIZE_OTHERS, EVEN_WIDTH } export var IWorkbenchEditorService = createDecorator<IWorkbenchEditorService>('editorService'); /** * The editor service allows to open editors and work on the active * editor input and models. */ export interface IWorkbenchEditorService extends IEditorService { serviceId : ServiceIdentifier<any>; /** * Returns the currently active editor or null if none. */ getActiveEditor(): IEditor; /** * Returns the currently active editor input or null if none. */ getActiveEditorInput(): IEditorInput; /** * Returns an array of visible editors. */ getVisibleEditors(): IEditor[]; /** * Returns iff the provided input is currently visible. * * @param includeDiff iff set to true, will also consider diff editors to find out if the provided * input is opened either on the left or right hand side of the diff editor. */ isVisible(input: IEditorInput, includeDiff: boolean): boolean; /** * Opens an Editor on the given input with the provided options at the given position. If the input parameter * is null, will cause the currently opened editor at the position to close. If sideBySide parameter is provided, * causes the editor service to decide in what position to open the input. */ openEditor(input: IEditorInput, options?: IEditorOptions, position?: Position): TPromise<IEditor>; openEditor(input: IEditorInput, options?: IEditorOptions, sideBySide?: boolean): TPromise<IEditor>; /** * Specific overload to open an instance of IResourceInput. */ openEditor(input: IResourceInput, position?: Position): TPromise<IEditor>; openEditor(input: IResourceInput, sideBySide?: boolean): TPromise<IEditor>; /** * Opens the set of inputs replacing any other editor that is currently open. Use #openEditor() instead to open * a single editor. */ setEditors(inputs: IEditorInput[]): TPromise<IEditor[]>; setEditors(inputs: IResourceInput[]): TPromise<IEditor[]>; /** * Closes the editor at the provided position. If position is not provided, the current active editor is closed. */ closeEditor(editor?: IEditor): TPromise<IEditor>; closeEditor(position?: Position): TPromise<IEditor>; /** * Closes all editors or only others that are not active. */ closeEditors(othersOnly?: boolean): TPromise<void>; /** * Focus the editor at the provided position. If position is not provided, the current active editor is focused. */ focusEditor(editor?: IEditor): TPromise<IEditor>; focusEditor(position?: Position): TPromise<IEditor>; /** * Activate the editor at the provided position without moving focus. */ activateEditor(editor: IEditor): void; activateEditor(position: Position): void; /** * Allows to move the editor at position 1 to position 2. */ moveEditor(from: Position, to: Position): void; /** * Allows to arrange editors according to the EditorArrangement enumeration. */ arrangeEditors(arrangement: EditorArrangement): void; /** * Resolves an input to its model representation. The optional parameter refresh allows to specify * if a cached model should be returned (false) or a new version (true). The default is returning a * cached version. */ resolveEditorModel(input: IEditorInput, refresh?: boolean): TPromise<IEditorModel>; /** * Specific overload to resolve a IResourceInput to an editor model with a text representation. */ resolveEditorModel(input: IResourceInput, refresh?: boolean): TPromise<ITextEditorModel>; /** * Allows to resolve an untyped input to a workbench typed instanceof editor input */ inputToType(input: IResourceInput): TPromise<IEditorInput>; }
src/vs/workbench/services/editor/common/editorService.ts
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.0002740436466410756, 0.00017680313612800092, 0.0001617790258023888, 0.00016873699496500194, 0.000029554592401837 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'$ref': '#/definitions/problemMatcher'\n", "\t\t\t\t\t\t\t\t\t},\n", "\t\t\t\t\t\t\t\t\t{\n", "\t\t\t\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']\n", "\t\t\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\t\t]\n", "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go']\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 955 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .progress-container { width: 100%; height: 5px; } .progress-container .progress-bit { width: 2%; height: 5px; position: absolute; left: 0; display: none; background-color: #0E70C0; } .progress-container.active .progress-bit { display: inherit; } .progress-container.discrete .progress-bit { left: 0; transition: width 100ms linear; -webkit-transition: width 100ms linear; -o-transition: width 100ms linear; -moz-transition: width 100ms linear; -ms-transition: width 100ms linear; } .progress-container.discrete.done .progress-bit { width: 100%; } .progress-container.infinite .progress-bit { animation-name: progress; animation-duration: 4s; animation-iteration-count: infinite; animation-timing-function: linear; -ms-animation-name: progress; -ms-animation-duration: 4s; -ms-animation-iteration-count: infinite; -ms-animation-timing-function: linear; -webkit-animation-name: progress; -webkit-animation-duration: 4s; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; -moz-animation-name: progress; -moz-animation-duration: 4s; -moz-animation-iteration-count: infinite; -moz-animation-timing-function: linear; } .progress-container.infinite.done .progress-bit { transition: opacity 200ms linear; -webkit-transition: opacity 200ms linear; -o-transition: opacity 200ms linear; -moz-transition: opacity 200ms linear; -ms-transition: opacity 200ms linear; } @keyframes progress { from { left: 0; width: 2%; } 50% { left: 50%; width: 5%; } to { left: 98%; width: 2%; } } @-ms-keyframes progress { from { left: 0; width: 2%; } 50% { left: 50%; width: 5%; } to { left: 98%; width: 2%; } } @-webkit-keyframes progress { from { left: 0; width: 2%; } 50% { left: 50%; width: 5%; } to { left: 98%; width: 2%; } } @-moz-keyframes progress { from { left: 0; width: 2%; } 50% { left: 50%; width: 5%; } to { left: 98%; width: 2%; } }
src/vs/base/browser/ui/progressbar/progressbar.css
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017479064990766346, 0.00017268459487240762, 0.0001712912053335458, 0.00017204269533976912, 0.0000011852966963488143 ]
{ "id": 6, "code_window": [ "\t\t\t\t\t'type': 'object',\n", "\t\t\t\t\t'additionalProperties': false,\n", "\t\t\t\t\t'properties': {\n", "\t\t\t\t\t\t'base': {\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'],\n", "\t\t\t\t\t\t\t'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.')\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t'owner': {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go'],\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 982 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as NLS from 'vs/nls'; import * as Objects from 'vs/base/common/objects'; import * as Strings from 'vs/base/common/strings'; import * as Assert from 'vs/base/common/assert'; import * as Paths from 'vs/base/common/paths'; import * as Types from 'vs/base/common/types'; import Severity from 'vs/base/common/severity'; import URI from 'vs/base/common/uri'; import { ValidationStatus, ValidationState, ILogger, Parser } from 'vs/base/common/parsers'; import { IStringDictionary } from 'vs/base/common/collections'; import { IMarkerData } from 'vs/platform/markers/common/markers'; export enum FileLocationKind { Auto, Relative, Absolute } export module FileLocationKind { export function fromString(value: string): FileLocationKind { value = value.toLowerCase(); if (value === 'absolute') { return FileLocationKind.Absolute; } else if (value === 'relative') { return FileLocationKind.Relative; } else { return undefined; } } } export interface ProblemPattern { regexp: RegExp; file?: number; message?: number; location?: number; line?: number; column?: number; endLine?: number; endColumn?: number; code?: number; severity?: number; loop?: boolean; mostSignifikant?: boolean; [key: string]: any; } export let problemPatternProperties = ['file', 'message', 'location', 'line', 'column', 'endLine', 'endColumn', 'code', 'severity', 'loop', 'mostSignifikant']; export interface WatchingPattern { regexp: RegExp; file?: number; } export interface WatchingMatcher { activeOnStart: boolean; beginsPattern: WatchingPattern; endsPattern: WatchingPattern; } export enum ApplyToKind { allDocuments, openDocuments, closedDocuments } export module ApplyToKind { export function fromString(value: string): ApplyToKind { value = value.toLowerCase(); if (value === 'alldocuments') { return ApplyToKind.allDocuments; } else if (value === 'opendocuments') { return ApplyToKind.openDocuments; } else if (value === 'closeddocuments') { return ApplyToKind.closedDocuments; } else { return undefined; } } } export interface ProblemMatcher { owner: string; applyTo: ApplyToKind; fileLocation: FileLocationKind; filePrefix?: string; pattern: ProblemPattern | ProblemPattern[]; severity?: Severity; watching?: WatchingMatcher; } export interface NamedProblemMatcher extends ProblemMatcher { name: string; } export function isNamedProblemMatcher(value: ProblemMatcher): value is NamedProblemMatcher { return Types.isString((<NamedProblemMatcher>value).name) ? true : false; } let valueMap: { [key: string]: string; } = { E: 'error', W: 'warning', I: 'info', }; interface Location { startLineNumber: number; startColumn: number; endLineNumber: number; endColumn: number; } interface ProblemData { file?: string; location?: string; line?: string; column?: string; endLine?: string; endColumn?: string; message?: string; severity?: string; code?: string; [key: string]: string; } export interface ProblemMatch { resource: URI; marker: IMarkerData; description: ProblemMatcher; } export interface HandleResult { match: ProblemMatch; continue: boolean; } export function getResource(filename: string, matcher: ProblemMatcher): URI { let kind = matcher.fileLocation; let fullPath: string; if (kind === FileLocationKind.Absolute) { fullPath = filename; } else if (kind === FileLocationKind.Relative) { fullPath = Paths.join(matcher.filePrefix, filename); } fullPath = fullPath.replace(/\\/g, '/'); if (fullPath[0] !== '/') { fullPath = '/' + fullPath; } return URI.parse('file://' + fullPath); } export interface ILineMatcher { matchLength: number; next(line: string): ProblemMatch; handle(lines: string[], start?: number): HandleResult; } export function createLineMatcher(matcher: ProblemMatcher): ILineMatcher { let pattern = matcher.pattern; if (Types.isArray(pattern)) { return new MultiLineMatcher(matcher); } else { return new SingleLineMatcher(matcher); } } class AbstractLineMatcher implements ILineMatcher { private matcher: ProblemMatcher; constructor(matcher: ProblemMatcher) { this.matcher = matcher; } public handle(lines: string[], start: number = 0): HandleResult { return { match: null, continue: false }; } public next(line: string): ProblemMatch { return null; } public get matchLength(): number { throw new Error('Subclass reponsibility'); } protected fillProblemData(data: ProblemData, pattern: ProblemPattern, matches: RegExpExecArray): void { this.fillProperty(data, 'file', pattern, matches, true); this.fillProperty(data, 'message', pattern, matches, true); this.fillProperty(data, 'code', pattern, matches, true); this.fillProperty(data, 'severity', pattern, matches, true); this.fillProperty(data, 'location', pattern, matches, true); this.fillProperty(data, 'line', pattern, matches); this.fillProperty(data, 'column', pattern, matches); this.fillProperty(data, 'endLine', pattern, matches); this.fillProperty(data, 'endColumn', pattern, matches); } private fillProperty(data: ProblemData, property: string, pattern: ProblemPattern, matches: RegExpExecArray, trim: boolean = false): void { if (Types.isUndefined(data[property]) && !Types.isUndefined(pattern[property]) && pattern[property] < matches.length) { let value = matches[pattern[property]]; if (trim) { value = Strings.trim(value); } data[property] = value; } } protected getMarkerMatch(data: ProblemData): ProblemMatch { let location = this.getLocation(data); if (data.file && location && data.message) { let marker: IMarkerData = { severity: this.getSeverity(data), startLineNumber: location.startLineNumber, startColumn: location.startColumn, endLineNumber: location.startLineNumber, endColumn: location.endColumn, message: data.message }; if (!Types.isUndefined(data.code)) { marker.code = data.code; } return { description: this.matcher, resource: this.getResource(data.file), marker: marker }; } } protected getResource(filename: string): URI { return getResource(filename, this.matcher); } private getLocation(data: ProblemData): Location { if (data.location) { return this.parseLocationInfo(data.location); } if (!data.line) { return null; } let startLine = parseInt(data.line); let startColumn = data.column ? parseInt(data.column) : undefined; let endLine = data.endLine ? parseInt(data.endLine) : undefined; let endColumn = data.endColumn ? parseInt(data.endColumn) : undefined; return this.createLocation(startLine, startColumn, endLine, endColumn); } private parseLocationInfo(value: string): Location { if (!value || !value.match(/(\d+|\d+,\d+|\d+,\d+,\d+,\d+)/)) { return null; } let parts = value.split(','); let startLine = parseInt(parts[0]); let startColumn = parts.length > 1 ? parseInt(parts[1]) : undefined; if (parts.length > 3) { return this.createLocation(startLine, startColumn, parseInt(parts[2]), parseInt(parts[3])); } else { return this.createLocation(startLine, startColumn, undefined, undefined); } } private createLocation(startLine: number, startColumn: number, endLine: number, endColumn: number): Location { if (startLine && startColumn && endLine && endColumn) { return { startLineNumber: startLine, startColumn: startColumn, endLineNumber: endLine, endColumn: endColumn }; } if (startLine && startColumn) { return { startLineNumber: startLine, startColumn: startColumn, endLineNumber: startLine, endColumn: startColumn }; } return { startLineNumber: startLine, startColumn: 1, endLineNumber: startLine, endColumn: Number.MAX_VALUE }; } private getSeverity(data: ProblemData): Severity { let result: Severity = null; if (data.severity) { let value = data.severity; if (value && value.length > 0) { if (value.length === 1 && valueMap[value[0]]) { value = valueMap[value[0]]; } result = Severity.fromValue(value); } } if (result === null || result === Severity.Ignore) { result = this.matcher.severity || Severity.Error; } return result; } } class SingleLineMatcher extends AbstractLineMatcher { private pattern: ProblemPattern; constructor(matcher: ProblemMatcher) { super(matcher); this.pattern = <ProblemPattern>matcher.pattern; } public get matchLength(): number { return 1; } public handle(lines: string[], start: number = 0): HandleResult { Assert.ok(lines.length - start === 1); let data: ProblemData = Object.create(null); let matches = this.pattern.regexp.exec(lines[start]); if (matches) { this.fillProblemData(data, this.pattern, matches); let match = this.getMarkerMatch(data); if (match) { return { match: match, continue: false }; } } return { match: null, continue: false }; } public next(line: string): ProblemMatch { return null; } } class MultiLineMatcher extends AbstractLineMatcher { private patterns: ProblemPattern[]; private data: ProblemData; constructor(matcher: ProblemMatcher) { super(matcher); this.patterns = <ProblemPattern[]>matcher.pattern; } public get matchLength(): number { return this.patterns.length; } public handle(lines: string[], start: number = 0): HandleResult { Assert.ok(lines.length - start === this.patterns.length); this.data = Object.create(null); let data = this.data; for (let i = 0; i < this.patterns.length; i++) { let pattern = this.patterns[i]; let matches = pattern.regexp.exec(lines[i + start]); if (!matches) { return { match: null, continue: false }; } else { // Only the last pattern can loop if (pattern.loop && i === this.patterns.length - 1) { data = Objects.clone(data); } this.fillProblemData(data, pattern, matches); } } let loop = this.patterns[this.patterns.length - 1].loop; if (!loop) { this.data = null; } return { match: this.getMarkerMatch(data), continue: loop }; } public next(line: string): ProblemMatch { let pattern = this.patterns[this.patterns.length - 1]; Assert.ok(pattern.loop === true && this.data !== null); let matches = pattern.regexp.exec(line); if (!matches) { this.data = null; return null; } let data = Objects.clone(this.data); this.fillProblemData(data, pattern, matches); return this.getMarkerMatch(data); } } let _defaultPatterns: { [name: string]: ProblemPattern | ProblemPattern[]; } = Object.create(null); _defaultPatterns['msCompile'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(\w{1,2}\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['gulp-tsc'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(\d+)\s+(.*)$/, file: 1, location: 2, code: 3, message: 4 }; _defaultPatterns['tsc'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(TS\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['cpp'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(C\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['csc'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(CS\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['vb'] = { regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(BC\d+)\s*:\s*(.*)$/, file: 1, location: 2, severity: 3, code: 4, message: 5 }; _defaultPatterns['lessCompile'] = { regexp: /^\s*(.*) in file (.*) line no. (\d+)$/, message: 1, file: 2, line: 3 }; _defaultPatterns['jshint'] = { regexp: /^(.*):\s+line\s+(\d+),\s+col\s+(\d+),\s(.+?)(?:\s+\((\w)(\d+)\))?$/, file: 1, line: 2, column: 3, message: 4, severity: 5, code: 6 }; _defaultPatterns['jshint-stylish'] = [ { regexp: /^(.+)$/, file: 1 }, { regexp: /^\s+line\s+(\d+)\s+col\s+(\d+)\s+(.+?)(?:\s+\((\w)(\d+)\))?$/, line: 1, column: 2, message: 3, severity: 4, code: 5, loop: true } ]; _defaultPatterns['eslint-compact'] = { regexp: /^(.+):\sline\s(\d+),\scol\s(\d+),\s(Error|Warning|Info)\s-\s(.+)\s\((.+)\)$/, file: 1, line: 2, column: 3, severity: 4, message: 5, code: 6 }; _defaultPatterns['eslint-stylish'] = [ { regexp: /^([^\s].*)$/, file: 1 }, { regexp: /^\s+(\d+):(\d+)\s+(error|warning|info)\s+(.+?)\s\s+(.*)$/, line: 1, column: 2, severity: 3, message: 4, code: 5, loop: true } ]; export function defaultPattern(name: 'msCompile'): ProblemPattern; export function defaultPattern(name: 'tsc'): ProblemPattern; export function defaultPattern(name: 'cpp'): ProblemPattern; export function defaultPattern(name: 'csc'): ProblemPattern; export function defaultPattern(name: 'vb'): ProblemPattern; export function defaultPattern(name: 'lessCompile'): ProblemPattern; export function defaultPattern(name: 'jshint'): ProblemPattern; export function defaultPattern(name: 'gulp-tsc'): ProblemPattern; export function defaultPattern(name: 'jshint-stylish'): ProblemPattern[]; export function defaultPattern(name: string): ProblemPattern | ProblemPattern[]; export function defaultPattern(name: string): ProblemPattern | ProblemPattern[] { return _defaultPatterns[name]; } export namespace Config { /** * Defines possible problem severity values */ export namespace ProblemSeverity { export const Error: string = 'error'; export const Warning: string = 'warning'; export const Info: string = 'info'; } export interface ProblemPattern { /** * The regular expression to find a problem in the console output of an * executed task. */ regexp?: string; /** * The match group index of the filename. * If omitted 1 is used. */ file?: number; /** * The match group index of the problems's location. Valid location * patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). * If omitted the line and colum properties are used. */ location?: number; /** * The match group index of the problem's line in the source file. * * Defaults to 2. */ line?: number; /** * The match group index of the problem's column in the source file. * * Defaults to 3. */ column?: number; /** * The match group index of the problem's end line in the source file. * * Defaults to undefined. No end line is captured. */ endLine?: number; /** * The match group index of the problem's end column in the source file. * * Defaults to undefined. No end column is captured. */ endColumn?: number; /** * The match group index of the problem's severity. * * Defaults to undefined. In this case the problem matcher's severity * is used. */ severity?: number; /** * The match group index of the problems's code. * * Defaults to undefined. No code is captured. */ code?: number; /** * The match group index of the message. If omitted it defaults * to 4 if location is specified. Otherwise it defaults to 5. */ message?: number; /** * Specifies if the last pattern in a multi line problem matcher should * loop as long as it does match a line consequently. Only valid on the * last problem pattern in a multi line problem matcher. */ loop?: boolean; [key: string]: any; } /** * A watching pattern */ export interface WatchingPattern { /** * The actual regular expression */ regexp?: string; /** * The match group index of the filename. If provided the expression * is matched for that file only. */ file?: number; } /** * A description to track the start and end of a watching task. */ export interface WatchingMatcher { /** * If set to true the watcher is in active mode when the task * starts. This is equals of issuing a line that matches the * beginPattern. */ activeOnStart?: boolean; /** * If matched in the output the start of a watching task is signaled. */ beginsPattern?: string | WatchingPattern; /** * If matched in the output the end of a watching task is signaled. */ endsPattern?: string | WatchingPattern; } /** * A description of a problem matcher that detects problems * in build output. */ export interface ProblemMatcher { /** * The name of a base problem matcher to use. If specified the * base problem matcher will be used as a template and properties * specified here will replace properties of the base problem * matcher */ base?: string; /** * The owner of the produced VSCode problem. This is typically * the identifier of a VSCode language service if the problems are * to be merged with the one produced by the language service * or 'external'. Defaults to 'external' if omitted. */ owner?: string; /** * Specifies to which kind of documents the problems found by this * matcher are applied. Valid values are: * * "allDocuments": problems found in all documents are applied. * "openDocuments": problems found in documents that are open * are applied. * "closedDocuments": problems found in closed documents are * applied. */ applyTo?: string; /** * The severity of the VSCode problem produced by this problem matcher. * * Valid values are: * "error": to produce errors. * "warning": to produce warnings. * "info": to produce infos. * * The value is used if a pattern doesn't specify a severity match group. * Defaults to "error" if omitted. */ severity?: string; /** * Defines how filename reported in a problem pattern * should be read. Valid values are: * - "absolute": the filename is always treated absolute. * - "relative": the filename is always treated relative to * the current working directory. This is the default. * - ["relative", "path value"]: the filename is always * treated relative to the given path value. */ fileLocation?: string | string[]; /** * The name of a predefined problem pattern, the inline definintion * of a problem pattern or an array of problem patterns to match * problems spread over multiple lines. */ pattern?: string | ProblemPattern | ProblemPattern[]; /** * A regular expression signaling that a watched tasks begins executing * triggered through file watching. */ watchedTaskBeginsRegExp?: string; /** * A regular expression signaling that a watched tasks ends executing. */ watchedTaskEndsRegExp?: string; watching?: WatchingMatcher; } export type ProblemMatcherType = string | ProblemMatcher | (string | ProblemMatcher)[]; export interface NamedProblemMatcher extends ProblemMatcher { /** * An optional name. This name can be used to refer to the * problem matchter from within a task. */ name?: string; } export function isNamedProblemMatcher(value: ProblemMatcher): value is NamedProblemMatcher { return Types.isString((<NamedProblemMatcher>value).name); } } export class ProblemMatcherParser extends Parser { private resolver: { get(name: string): ProblemMatcher; }; constructor(resolver: { get(name: string): ProblemMatcher; }, logger: ILogger, validationStatus: ValidationStatus = new ValidationStatus()) { super(logger, validationStatus); this.resolver = resolver; } public parse(json: Config.ProblemMatcher): ProblemMatcher { let result = this.createProblemMatcher(json); if (!this.checkProblemMatcherValid(json, result)) { return null; } this.addWatchingMatcher(json, result); return result; } private checkProblemMatcherValid(externalProblemMatcher: Config.ProblemMatcher, problemMatcher: ProblemMatcher): boolean { if (!problemMatcher || !problemMatcher.pattern || !problemMatcher.owner || Types.isUndefined(problemMatcher.fileLocation)) { this.status.state = ValidationState.Fatal; this.log(NLS.localize('ProblemMatcherParser.invalidMarkerDescription', 'Error: Invalid problemMatcher description. A matcher must at least define a pattern, owner and a file location. The problematic matcher is:\n{0}\n', JSON.stringify(externalProblemMatcher, null, 4))); return false; } return true; } private createProblemMatcher(description: Config.ProblemMatcher): ProblemMatcher { let result: ProblemMatcher = null; let owner = description.owner ? description.owner : 'external'; let applyTo = Types.isString(description.applyTo) ? ApplyToKind.fromString(description.applyTo) : ApplyToKind.allDocuments; if (!applyTo) { applyTo = ApplyToKind.allDocuments; } let fileLocation: FileLocationKind = undefined; let filePrefix: string = undefined; let kind: FileLocationKind; if (Types.isUndefined(description.fileLocation)) { fileLocation = FileLocationKind.Relative; filePrefix = '${cwd}'; } else if (Types.isString(description.fileLocation)) { kind = FileLocationKind.fromString(<string>description.fileLocation); if (kind) { fileLocation = kind; if (kind === FileLocationKind.Relative) { filePrefix = '${cwd}'; } } } else if (Types.isStringArray(description.fileLocation)) { let values = <string[]>description.fileLocation; if (values.length > 0) { kind = FileLocationKind.fromString(values[0]); if (values.length === 1 && kind === FileLocationKind.Absolute) { fileLocation = kind; } else if (values.length === 2 && kind === FileLocationKind.Relative && values[1]) { fileLocation = kind; filePrefix = values[1]; } } } let pattern = description.pattern ? this.createProblemPattern(description.pattern) : undefined; let severity = description.severity ? Severity.fromValue(description.severity) : undefined; if (severity === Severity.Ignore) { this.status.state = ValidationState.Info; this.log(NLS.localize('ProblemMatcherParser.unknownSeverity', 'Info: unknown severity {0}. Valid values are error, warning and info.\n', description.severity)); severity = Severity.Error; } if (Types.isString(description.base)) { let variableName = <string>description.base; if (variableName.length > 1 && variableName[0] === '$') { let base = this.resolver.get(variableName.substring(1)); if (base) { result = Objects.clone(base); if (description.owner) { result.owner = owner; } if (fileLocation) { result.fileLocation = fileLocation; } if (filePrefix) { result.filePrefix = filePrefix; } if (description.pattern) { result.pattern = pattern; } if (description.severity) { result.severity = severity; } } } } else if (fileLocation) { result = { owner: owner, applyTo: applyTo, fileLocation: fileLocation, pattern: pattern, }; if (filePrefix) { result.filePrefix = filePrefix; } if (severity) { result.severity = severity; } } if (Config.isNamedProblemMatcher(description)) { (<NamedProblemMatcher>result).name = description.name; } return result; } private createProblemPattern(value: string | Config.ProblemPattern | Config.ProblemPattern[]): ProblemPattern | ProblemPattern[] { let pattern: ProblemPattern; if (Types.isString(value)) { let variableName: string = <string>value; if (variableName.length > 1 && variableName[0] === '$') { return defaultPattern(variableName.substring(1)); } } else if (Types.isArray(value)) { let values = <Config.ProblemPattern[]>value; let result: ProblemPattern[] = []; for (let i = 0; i < values.length; i++) { pattern = this.createSingleProblemPattern(values[i], false); if (i < values.length - 1) { if (!Types.isUndefined(pattern.loop) && pattern.loop) { pattern.loop = false; this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.loopProperty.notLast', 'The loop property is only supported on the last line matcher.')); } } result.push(pattern); } this.validateProblemPattern(result); return result; } else { pattern = this.createSingleProblemPattern(<Config.ProblemPattern>value, true); if (!Types.isUndefined(pattern.loop) && pattern.loop) { pattern.loop = false; this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.loopProperty.notMultiLine', 'The loop property is only supported on multi line matchers.')); } this.validateProblemPattern([pattern]); return pattern; } return null; } private createSingleProblemPattern(value: Config.ProblemPattern, setDefaults: boolean): ProblemPattern { let result: ProblemPattern = { regexp: this.createRegularExpression(value.regexp) }; problemPatternProperties.forEach(property => { if (!Types.isUndefined(value[property])) { result[property] = value[property]; } }); if (setDefaults) { if (result.location) { result = Objects.mixin(result, { file: 1, message: 4 }, false); } else { result = Objects.mixin(result, { file: 1, line: 2, column: 3, message: 4 }, false); } } return result; } private validateProblemPattern(values: ProblemPattern[]): void { let file: boolean, message: boolean, location: boolean, line: boolean; let regexp: number = 0; values.forEach(pattern => { file = file || !!pattern.file; message = message || !!pattern.message; location = location || !!pattern.location; line = line || !!pattern.line; if (pattern.regexp) { regexp++; } }); if (regexp !== values.length) { this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.problemPattern.missingRegExp', 'The problem pattern is missing a regular expression.')); } if (!(file && message && (location || line))) { this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.problemPattern.missingProperty', 'The problem pattern is invalid. It must have at least a file, message and line or location match group.')); } } private addWatchingMatcher(external: Config.ProblemMatcher, internal: ProblemMatcher): void { let oldBegins = this.createRegularExpression(external.watchedTaskBeginsRegExp); let oldEnds = this.createRegularExpression(external.watchedTaskEndsRegExp); if (oldBegins && oldEnds) { internal.watching = { activeOnStart: false, beginsPattern: { regexp: oldBegins }, endsPattern: { regexp: oldEnds } }; return; } if (Types.isUndefinedOrNull(external.watching)) { return; } let watching = external.watching; let begins: WatchingPattern = this.createWatchingPattern(watching.beginsPattern); let ends: WatchingPattern = this.createWatchingPattern(watching.endsPattern); if (begins && ends) { internal.watching = { activeOnStart: Types.isBoolean(watching.activeOnStart) ? watching.activeOnStart : false, beginsPattern: begins, endsPattern: ends }; return; } if (begins || ends) { this.status.state = ValidationState.Error; this.log(NLS.localize('ProblemMatcherParser.problemPattern.watchingMatcher', 'A problem matcher must define both a begin pattern and an end pattern for watching.')); } } private createWatchingPattern(external: string | Config.WatchingPattern): WatchingPattern { if (Types.isUndefinedOrNull(external)) { return null; } let regexp: RegExp; let file: number; if (Types.isString(external)) { regexp = this.createRegularExpression(external); } else { regexp = this.createRegularExpression(external.regexp); if (Types.isNumber(external.file)) { file = external.file; } } if (!regexp) { return null; } return file ? { regexp, file } : { regexp }; } private createRegularExpression(value: string): RegExp { let result: RegExp = null; if (!value) { return result; } try { result = new RegExp(value); } catch (err) { this.status.state = ValidationState.Fatal; this.log(NLS.localize('ProblemMatcherParser.invalidRegexp', 'Error: The string {0} is not a valid regular expression.\n', value)); } return result; } } // let problemMatchersExtPoint = ExtensionsRegistry.registerExtensionPoint<Config.NamedProblemMatcher | Config.NamedProblemMatcher[]>('problemMatchers', { // TODO@Dirk: provide here JSON schema for extension point // }); export class ProblemMatcherRegistry { private matchers: IStringDictionary<ProblemMatcher>; constructor() { this.matchers = Object.create(null); /* problemMatchersExtPoint.setHandler((extensions, collector) => { // TODO@Dirk: validate extensions here and collect errors/warnings in `collector` extensions.forEach(extension => { let extensions = extension.value; if (Types.isArray(extensions)) { (<Config.NamedProblemMatcher[]>extensions).forEach(this.onProblemMatcher, this); } else { this.onProblemMatcher(extensions) } }); }); */ } // private onProblemMatcher(json: Config.NamedProblemMatcher): void { // let logger: ILogger = { // log: (message) => { console.warn(message); } // } // let parser = new ProblemMatcherParser(this, logger); // let result = parser.parse(json); // if (isNamedProblemMatcher(result) && parser.status.isOK()) { // this.add(result.name, result); // } // } public add(name: string, matcher: ProblemMatcher): void { this.matchers[name] = matcher; } public get(name: string): ProblemMatcher { return this.matchers[name]; } public exists(name: string): boolean { return !!this.matchers[name]; } public remove(name: string): void { delete this.matchers[name]; } } export const registry: ProblemMatcherRegistry = new ProblemMatcherRegistry(); registry.add('msCompile', { owner: 'msCompile', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('msCompile') }); registry.add('lessCompile', { owner: 'lessCompile', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('lessCompile'), severity: Severity.Error }); registry.add('tsc', { owner: 'typescript', applyTo: ApplyToKind.closedDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('tsc') }); let matcher = { owner: 'typescript', applyTo: ApplyToKind.closedDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('tsc'), watching: { activeOnStart: true, beginsPattern: { regexp: /^\s*(?:message TS6032:|\d{1,2}:\d{1,2}:\d{1,2}(?: AM| PM)? -) File change detected\. Starting incremental compilation\.\.\./ }, endsPattern: { regexp: /^\s*(?:message TS6042:|\d{1,2}:\d{1,2}:\d{1,2}(?: AM| PM)? -) Compilation complete\. Watching for file changes\./ } } }; (<any>matcher).tscWatch = true; registry.add('tsc-watch', matcher); registry.add('gulp-tsc', { owner: 'typescript', applyTo: ApplyToKind.closedDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('gulp-tsc') }); registry.add('jshint', { owner: 'jshint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('jshint') }); registry.add('jshint-stylish', { owner: 'jshint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('jshint-stylish') }); registry.add('eslint-compact', { owner: 'eslint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '${cwd}', pattern: defaultPattern('eslint-compact') }); registry.add('eslint-stylish', { owner: 'eslint', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Absolute, pattern: defaultPattern('eslint-stylish') });
src/vs/platform/markers/common/problemMatcher.ts
1
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.006226628087460995, 0.000410371896577999, 0.0001617299858480692, 0.00017422718519810587, 0.000826460134703666 ]
{ "id": 6, "code_window": [ "\t\t\t\t\t'type': 'object',\n", "\t\t\t\t\t'additionalProperties': false,\n", "\t\t\t\t\t'properties': {\n", "\t\t\t\t\t\t'base': {\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'],\n", "\t\t\t\t\t\t\t'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.')\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t'owner': {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go'],\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 982 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "cmdCreate": "Créer jsconfig.json", "hintCreate": "Créez un fichier jsconfig.json pour améliorer les fonctionnalités IntelliSense et la navigation au sein du code dans l'ensemble de l'espace de travail.", "hintCreate.tooltip": "Créez un fichier jsconfig.json pour améliorer les fonctionnalités IntelliSense et la navigation au sein du code dans l'ensemble de l'espace de travail.", "hintExclude": "Pour accroître les performances, excluez les dossiers contenant de nombreux fichiers, par exemple : {0}", "hintExclude.generic": "Pour accroître les performances, excluez les dossiers contenant de nombreux fichiers.", "hintExclude.tooltip": "Pour améliorer les performances, excluez les dossiers contenant de nombreux fichiers.", "ignore.cmdCreate": "Ignorer", "large.label": "Configurer les exclusions", "open": "Configurer les exclusions" }
i18n/fra/extensions/typescript/out/utils/projectStatus.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017628884233999997, 0.0001750773226376623, 0.00017386578838340938, 0.0001750773226376623, 0.0000012115269782952964 ]
{ "id": 6, "code_window": [ "\t\t\t\t\t'type': 'object',\n", "\t\t\t\t\t'additionalProperties': false,\n", "\t\t\t\t\t'properties': {\n", "\t\t\t\t\t\t'base': {\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'],\n", "\t\t\t\t\t\t\t'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.')\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t'owner': {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go'],\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 982 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "QuickOutlineAction.label": "Vai al simbolo...", "_constructor": "costruttori ({0})", "call": "chiamate ({0})", "class": "classi ({0})", "function": "funzioni ({0})", "interface": "interfacce ({0})", "method": "metodi ({0})", "modules": "moduli ({0})", "property": "proprietà ({0})", "quickOutlineActionInput": "Digitare il nome di un identificatore a cui passare", "symbols": "simboli ({0})", "variable": "variabili ({0})", "variable2": "variabili ({0})" }
i18n/ita/src/vs/editor/contrib/quickOpen/browser/quickOutline.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017426478734705597, 0.00017215590924024582, 0.0001682292204350233, 0.00017397374904248863, 0.0000027791361389972735 ]
{ "id": 6, "code_window": [ "\t\t\t\t\t'type': 'object',\n", "\t\t\t\t\t'additionalProperties': false,\n", "\t\t\t\t\t'properties': {\n", "\t\t\t\t\t\t'base': {\n", "\t\t\t\t\t\t\t'type': 'string',\n", "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'],\n", "\t\t\t\t\t\t\t'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.')\n", "\t\t\t\t\t\t},\n", "\t\t\t\t\t\t'owner': {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\t'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish', '$go'],\n" ], "file_path": "src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 982 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "corrupt.commands": "執行命令時發生未預期的例外狀況。" }
i18n/cht/src/vs/editor/common/controller/cursor.i18n.json
0
https://github.com/microsoft/vscode/commit/39e2584228bee78d7f40bb28f4fc8a6acf24e499
[ 0.00017281492182519287, 0.00017281492182519287, 0.00017281492182519287, 0.00017281492182519287, 0 ]
{ "id": 0, "code_window": [ " const buttonOptions: google.payments.api.ButtonOptions = {\n", " onClick: onGooglePaymentButtonClick,\n", " buttonColor: 'black',\n", " buttonType: 'short',\n", " };\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "types/googlepay/googlepay-tests.ts", "type": "replace", "edit_start_line_idx": 80 }
const allowedCardNetworks = new Array<google.payments.api.CardNetwork>( 'AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA', 'INTERAC' ); const allowedPaymentMethods = new Array<google.payments.api.PaymentMethodSpecification>({ type: 'CARD', parameters: { allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], allowedCardNetworks, billingAddressRequired: true, billingAddressParameters: { format: 'MIN' } }, tokenizationSpecification: { type: 'PAYMENT_GATEWAY', parameters: { gateway: 'example', gatewayMerchantId: 'abc123' } } }); // $ExpectError allowedPaymentMethods[0].tokenizationSpecification = { type: 'DIRECT', parameters: { } }; allowedPaymentMethods[0].tokenizationSpecification = { type: 'DIRECT', parameters: { protocolVersion: 'ECv2', publicKey: 'BOdoXP1aiNp.....kh3JUhiSZKHYF2Y=', } }; const getGooglePaymentsClient = (env?: google.payments.api.Environment) => { return new google.payments.api.PaymentsClient({ environment: env, paymentDataCallbacks: { onPaymentAuthorized: (paymentData) => ({ transactionState: 'SUCCESS' }), onPaymentDataChanged: (paymentData) => ({}) } }); }; function onGooglePayLoaded() { const client = getGooglePaymentsClient(); client.isReadyToPay({ apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [{ type: 'CARD', parameters: { allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], allowedCardNetworks, }, }] }).then(response => { if (response.result) { addGooglePayButton(); prefetchGooglePaymentData(); } }).catch(err => { console.error(err); }); } function addGooglePayButton() { const buttonOptions: google.payments.api.ButtonOptions = { onClick: onGooglePaymentButtonClick, buttonColor: 'black', buttonType: 'short', }; const client = getGooglePaymentsClient(); const button = client.createButton(buttonOptions); document.appendChild(document.createElement('div').appendChild(button)); } function getGooglePaymentDataConfiguration(): google.payments.api.PaymentDataRequest { return { apiVersion: 2, apiVersionMinor: 0, merchantInfo: { merchantId: '01234567890123456789', softwareInfo: { id: 'my.softwareInfo.test', version: '1.0.0' } }, transactionInfo: { totalPriceStatus: 'FINAL', totalPrice: '123.45', currencyCode: 'USD', countryCode: 'US', transactionId: '0123456789', displayItems: [{ label: 'Subtotal', type: 'SUBTOTAL', price: '11.00' }, { label: 'Shipping', type: 'LINE_ITEM', price: '0', status: 'PENDING' }], totalPriceLabel: 'Total', checkoutOption: 'COMPLETE_IMMEDIATE_PURCHASE' }, allowedPaymentMethods, shippingAddressRequired: true }; } function prefetchGooglePaymentData() { const client = getGooglePaymentsClient(); client.prefetchPaymentData(getGooglePaymentDataConfiguration()); } function onGooglePaymentButtonClick() { const request = getGooglePaymentDataConfiguration(); const client = getGooglePaymentsClient(); client.loadPaymentData(request) .then(data => console.log(data)) .catch(err => console.error(err)); }
types/googlepay/googlepay-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.9978864789009094, 0.14474762976169586, 0.00016499354387633502, 0.0011290102265775204, 0.3477686643600464 ]
{ "id": 0, "code_window": [ " const buttonOptions: google.payments.api.ButtonOptions = {\n", " onClick: onGooglePaymentButtonClick,\n", " buttonColor: 'black',\n", " buttonType: 'short',\n", " };\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "types/googlepay/googlepay-tests.ts", "type": "replace", "edit_start_line_idx": 80 }
import Squire = require('squirejs'); // Default Configuration var injector = new Squire(); // Different Context injector = new Squire('other-requirejs-context'); // require(Array dependencies, Function callback, Function errback) injector.require(['a'], function(A: any) {}, function(err: any) {}); // mock(String name | Object(name: mock), Object mock) injector.mock("a", {}); injector.mock({a: {}}); // store(String name | Array names) injector.store('a'); injector.store(['a', 'b']); // clean(Optional (String name | Array names)) injector.clean('a'); injector.clean(['a', 'b']); injector.clean(); // remove() injector.remove(); // run() injector.run(['a'], function test(a: any) {})(function done() {}); // Squire.Helpers.returns(Any what) Squire.Helpers.returns({}); // Squire.Helpers.constructs(Any what) Squire.Helpers.constructs({});
types/squirejs/squirejs-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.00017655464762356132, 0.00017476319044362754, 0.00017232408572454005, 0.00017508701421320438, 0.0000016644961533529568 ]
{ "id": 0, "code_window": [ " const buttonOptions: google.payments.api.ButtonOptions = {\n", " onClick: onGooglePaymentButtonClick,\n", " buttonColor: 'black',\n", " buttonType: 'short',\n", " };\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "types/googlepay/googlepay-tests.ts", "type": "replace", "edit_start_line_idx": 80 }
export function UrlParser(urlString: string, namedUrl?: string): UrlParserResult; export interface UrlParserResult { host: string; hostname: string; namedParams: { [key: string]: string; }; namedParamsKeys: string[]; namedParamsValues: string[]; pathNames: string[]; port: string; pathname: string; protocol: string; search: string; queryParams: { [key: string]: string; }; queryParamsKeys: string[]; queryParamsValues: string[]; }
types/url-params-parser/url_parser.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.0001779788435669616, 0.00017461863171774894, 0.0001714596728561446, 0.00017441737873014063, 0.0000026652421638573287 ]
{ "id": 0, "code_window": [ " const buttonOptions: google.payments.api.ButtonOptions = {\n", " onClick: onGooglePaymentButtonClick,\n", " buttonColor: 'black',\n", " buttonType: 'short',\n", " };\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "types/googlepay/googlepay-tests.ts", "type": "replace", "edit_start_line_idx": 80 }
// Type definitions for telebot 1.2 // Project: https://github.com/mullwar/telebot // Definitions by: Simone Mariotti <https://github.com/mariotsi> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> export = telebot; declare namespace telebot { interface config { token: string; // Required. Telegram Bot API token. polling?: { // Optional. Use polling. interval?: number; // Optional. How often check updates (in ms). timeout?: number; // Optional. Update polling timeout (0 - short polling). limit?: number; // Optional. Limits the number of updates to be retrieved. retryTimeout?: number; // Optional. Reconnecting timeout (in ms). proxy?: string; // Optional. An HTTP proxy to be used. }; webhook?: { // Optional. Use webhook instead of polling. key?: string; // Optional. Private key for server. cert?: string; // Optional. key. url?: string; // HTTPS url to send updates to. host?: string; // Webhook server host. port?: number; // Server port. maxConnections?: number; // Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery }; allowedUpdates?: string[]; // Optional. List the types of updates you want your bot to receive. Specify an empty list to receive all updates. usePlugins?: string[]; // Optional. Use build-in plugins from pluginFolder. pluginFolder?: string; // Optional. Plugin folder location relative to telebot package. pluginConfig?: any; } interface module { id: string; defaultConfig: any; plugin(...args: any[]): void; } type genericCb = (...args: any[]) => any; class AnswerList { constructor(id: string, opt?: any); add(type: string, set?: any): any; results(): string; addArticle(set?: any): any; addPhoto(set?: any): any; addVideo(set?: any): any; addGif(set?: any): any; addVideoGif(set?: any): any; addSticker(set?: any): any; addVoice(set?: any): any; addDocument(set?: any): any; addLocation(set?: any): any; addVenue(set?: any): any; addGame(set?: any): any; // Cached methods cachedPhoto(set?: any): any; cachedGif(set?: any): any; cachedVideoGif(set?: any): any; cachedSticker(set?: any): any; cachedDocument(set?: any): any; cachedVideo(set?: any): any; cachedVoice(set?: any): any; cachedAudio(set?: any): any; } } declare class telebot { constructor(config: string | telebot.config); plug(module: telebot.module): void; use(module: telebot.module): void; start(...args: any[]): void; connect(...args: any[]): void; stop(message: string): void; getUpdates( offset: number, limit: number, timeout: number, allowed_updates: string | string[] ): void; receiveUpdates(updateList: any[]): Promise<any>; request(url: string, form: any, data: any): Promise<any>; mod(names: string | string[], fn: telebot.genericCb): any; modRun(name: string, data: any): any; removeMod(name: string, fn: telebot.genericCb): boolean; on( types: string | string[] | RegExp, fn: telebot.genericCb, opt?: any ): boolean; event( types: string | string[], data: any, self?: any ): Promise<any>; cleanEvent(type: string): boolean; removeEvent(type: string, fn: telebot.genericCb): boolean; destroyEvent(type: string): boolean; properties(form: any, opt: any): any; static addMethods(...methods: Array<telebot.genericCb | any>): any; // methods.js keyboard(buttons: any[][], opt?: any): any; button(type: string, text?: string): any; inlineKeyboard(inlineButtons: any[][]): any; inlineQueryKeyboard(config: any[][]): any; inlineButton(text: string, opt?: any): any; answerList(id: string, opt?: any): telebot.AnswerList; // Telegram API getMe(): any; answerQuery(...param: any[]): boolean; sendMessage( chat_id: number | string, text: string, opt?: { parseMode?: string; replyToMessage?: number; replyMarkup?: any; notification?: boolean; webPreview?: boolean; } ): any; forwardMessage( chat_id: number | string, from_chat_id: number | string, message_id: number, opt?: { notification?: boolean } ): any; deleteMessage( chat_id: number | string, from_message_id: number ): boolean; sendPhoto( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { caption?: string; fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendAudio( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { title?: string; performer?: string; duration?: number; caption?: string; fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendDocument( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { caption?: string; fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendSticker( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendVideo( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { duration?: number; width?: number; height?: number; caption?: string; fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendVideoNote( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { duration?: number; fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendVoice( chat_id: number | string, file: string | Buffer | NodeJS.ReadableStream | any, opt?: { duration?: number; caption?: string; fileName?: string; serverDownload?: boolean; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendLocation( chat_id: number | string, coords: [number, number], opt?: { replyToMessage?: number; replyMarkup?: any; notification?: boolean } ): any; sendVenue( chat_id: number | string, coords: [number, number], title: string, address: string, opt?: { foursquareId?: string; replyToMessage?: number; replyMarkup?: any; notification?: boolean; } ): any; sendContact( chat_id: number | string, number: string, firstName: string, lastName?: string, opt?: { replyToMessage?: number; replyMarkup?: any; notification?: boolean } ): any; sendAction(chat_id: number | string, action: string): boolean; sendGame( chat_id: number | string, game_short_name: string, opt?: { replyToMessage?: number; replyMarkup?: any; notification?: boolean } ): any; setGameScore( user_id: number, score: number, opt?: { force?: boolean; disableEditMessage?: boolean; chatId?: number; messageId?: number; inlineMessageId?: string; } ): boolean | Error | any; getGameHighScores( user_id: number, opt?: { chatId?: number; messageId?: number; inlineMessageId?: string } ): any[]; getUserProfilePhotos( user_id: number, opt?: { offset?: number; limit?: number } ): any; getFile(file_id: string): any; sendInvoice( chat_id: number | string, invoiceDetails: { title: string; description: string; payload: string; providerToken: string; startParameter: string; currency: string; prices: any[]; photo?: { url?: string; width?: number; height?: number }; need?: { name?: boolean; phoneNumber?: boolean; email?: boolean; shippingAddress?: boolean; }; isFlexible?: boolean; notification?: boolean; replyToMessage?: number; replyMarkup?: any; } ): any; getChat(chat_id: number | string): any; leaveChat(chat_id: number | string): boolean; getChatAdministrators(chat_id: number | string): any[] | any; getChatMembersCount(chat_id: number | string): number; getChatMember(chat_id: number | string, user_id: number): any; kickChatMember(chat_id: number | string, user_id: number): boolean; unbanChatMember(chat_id: number | string, user_id: number): boolean; editMessageText( config: { chatId: number | string; messageId: number; inlineMsgId?: number; }|{ chatId?: number | string; messageId?: number; inlineMsgId: number; }, text: string ): any | boolean; editMessageCaption( config: { chatId: number | string; messageId: number; inlineMsgId?: number; }|{ chatId?: number | string; messageId?: number; inlineMsgId: number; }, caption: string ): any | boolean; editMessageReplyMarkup( config: { chatId: number | string; messageId: number; inlineMsgId?: number; }|{ chatId?: number | string; messageId?: number; inlineMsgId: number; }, replyMarkup: any ): any | boolean; answerCallbackQuery( callback_query_id: string, opt?: { text?: string; url?: string; showAlert?: boolean; cacheTime?: number; } ): boolean; answerShippingQuery( shipping_query_id: string, ok: boolean, opt?: { shippingOptions?: any[]; errorMessage?: string } ): boolean; answerPreCheckoutQuery( pre_checkout_query_id: string, ok: boolean, opt?: { errorMessage?: string } ): boolean; setWebhook( url: string, certificate?: any, allowed_updates?: string[], max_connections?: number ): boolean; getWebhookInfo(): any; deleteWebhook(): boolean; }
types/telebot/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.0001771117385942489, 0.00017197108536493033, 0.0001655741361901164, 0.00017185069737024605, 0.000002639319291120046 ]
{ "id": 3, "code_window": [ " /**\n", " * Supported methods for presenting the Google Pay button.\n", " *\n", " * Options:\n", " *\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " * A translated button label may appear if a language specified in the\n", " * viewer's browser matches an [available\n", " * language](https://developers.google.com/pay/api/web/guides/brand-guidelines#payment-buttons-assets).\n", " *\n", " *\n" ], "file_path": "types/googlepay/index.d.ts", "type": "add", "edit_start_line_idx": 1247 }
const allowedCardNetworks = new Array<google.payments.api.CardNetwork>( 'AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA', 'INTERAC' ); const allowedPaymentMethods = new Array<google.payments.api.PaymentMethodSpecification>({ type: 'CARD', parameters: { allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], allowedCardNetworks, billingAddressRequired: true, billingAddressParameters: { format: 'MIN' } }, tokenizationSpecification: { type: 'PAYMENT_GATEWAY', parameters: { gateway: 'example', gatewayMerchantId: 'abc123' } } }); // $ExpectError allowedPaymentMethods[0].tokenizationSpecification = { type: 'DIRECT', parameters: { } }; allowedPaymentMethods[0].tokenizationSpecification = { type: 'DIRECT', parameters: { protocolVersion: 'ECv2', publicKey: 'BOdoXP1aiNp.....kh3JUhiSZKHYF2Y=', } }; const getGooglePaymentsClient = (env?: google.payments.api.Environment) => { return new google.payments.api.PaymentsClient({ environment: env, paymentDataCallbacks: { onPaymentAuthorized: (paymentData) => ({ transactionState: 'SUCCESS' }), onPaymentDataChanged: (paymentData) => ({}) } }); }; function onGooglePayLoaded() { const client = getGooglePaymentsClient(); client.isReadyToPay({ apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [{ type: 'CARD', parameters: { allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], allowedCardNetworks, }, }] }).then(response => { if (response.result) { addGooglePayButton(); prefetchGooglePaymentData(); } }).catch(err => { console.error(err); }); } function addGooglePayButton() { const buttonOptions: google.payments.api.ButtonOptions = { onClick: onGooglePaymentButtonClick, buttonColor: 'black', buttonType: 'short', }; const client = getGooglePaymentsClient(); const button = client.createButton(buttonOptions); document.appendChild(document.createElement('div').appendChild(button)); } function getGooglePaymentDataConfiguration(): google.payments.api.PaymentDataRequest { return { apiVersion: 2, apiVersionMinor: 0, merchantInfo: { merchantId: '01234567890123456789', softwareInfo: { id: 'my.softwareInfo.test', version: '1.0.0' } }, transactionInfo: { totalPriceStatus: 'FINAL', totalPrice: '123.45', currencyCode: 'USD', countryCode: 'US', transactionId: '0123456789', displayItems: [{ label: 'Subtotal', type: 'SUBTOTAL', price: '11.00' }, { label: 'Shipping', type: 'LINE_ITEM', price: '0', status: 'PENDING' }], totalPriceLabel: 'Total', checkoutOption: 'COMPLETE_IMMEDIATE_PURCHASE' }, allowedPaymentMethods, shippingAddressRequired: true }; } function prefetchGooglePaymentData() { const client = getGooglePaymentsClient(); client.prefetchPaymentData(getGooglePaymentDataConfiguration()); } function onGooglePaymentButtonClick() { const request = getGooglePaymentDataConfiguration(); const client = getGooglePaymentsClient(); client.loadPaymentData(request) .then(data => console.log(data)) .catch(err => console.error(err)); }
types/googlepay/googlepay-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.0004134719492867589, 0.00023740543110761791, 0.00016722007421776652, 0.00020552607020363212, 0.00008420279482379556 ]
{ "id": 3, "code_window": [ " /**\n", " * Supported methods for presenting the Google Pay button.\n", " *\n", " * Options:\n", " *\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " * A translated button label may appear if a language specified in the\n", " * viewer's browser matches an [available\n", " * language](https://developers.google.com/pay/api/web/guides/brand-guidelines#payment-buttons-assets).\n", " *\n", " *\n" ], "file_path": "types/googlepay/index.d.ts", "type": "add", "edit_start_line_idx": 1247 }
{ "extends": "dtslint/dt.json" }
types/lodash.findkey/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.00016999214130919427, 0.00016999214130919427, 0.00016999214130919427, 0.00016999214130919427, 0 ]
{ "id": 3, "code_window": [ " /**\n", " * Supported methods for presenting the Google Pay button.\n", " *\n", " * Options:\n", " *\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " * A translated button label may appear if a language specified in the\n", " * viewer's browser matches an [available\n", " * language](https://developers.google.com/pay/api/web/guides/brand-guidelines#payment-buttons-assets).\n", " *\n", " *\n" ], "file_path": "types/googlepay/index.d.ts", "type": "add", "edit_start_line_idx": 1247 }
import Vue from 'vue'; import { VueEditor } from 'vue2-editor'; new Vue({ el: '#app', data: { phone: "", bindProps: { defaultCountry: "", disabledFetchingCountry: false, disabled: false, disabledFormatting: false, placeholder: "Enter a phone number", required: false, enabledCountryCode: false, enabledFlags: true, preferredCountries: ["AU", "BR"], onlyCountries: [], ignoredCountries: [], autocomplete: "off", name: "telephone", maxLen: 25, wrapperClasses: "", inputClasses: "", dropdownOptions: { disabledDialCode: false }, inputOptions: { showDialCode: false } } }, components: { VueEditor, }, template: `<vue-editor v-model="content"></vue-editor>` });
types/vue2-editor/vue2-editor-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.0001725287875160575, 0.00016899056208785623, 0.00016698379477020353, 0.00016822482575662434, 0.0000021214145817793906 ]
{ "id": 3, "code_window": [ " /**\n", " * Supported methods for presenting the Google Pay button.\n", " *\n", " * Options:\n", " *\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " * A translated button label may appear if a language specified in the\n", " * viewer's browser matches an [available\n", " * language](https://developers.google.com/pay/api/web/guides/brand-guidelines#payment-buttons-assets).\n", " *\n", " *\n" ], "file_path": "types/googlepay/index.d.ts", "type": "add", "edit_start_line_idx": 1247 }
// Type definitions for react-imgix 9.0 // Project: https://github.com/imgix/react-imgix // Definitions by: Michael Haglund <https://github.com/hagmic> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as React from 'react'; type ImgixParamType = string | number | boolean; interface AdjustmentParams { bri?: ImgixParamType; con?: ImgixParamType; exp?: ImgixParamType; gam?: ImgixParamType; high?: ImgixParamType; hue?: ImgixParamType; invert?: ImgixParamType; sat?: ImgixParamType; shad?: ImgixParamType; sharp?: ImgixParamType; usm?: ImgixParamType; usmrad?: ImgixParamType; vib?: ImgixParamType; } interface AutomaticParams { auto?: ImgixParamType; } interface BlendingParams { 'blend-align'?: ImgixParamType; 'blend-alpha'?: ImgixParamType; 'blend-crop'?: ImgixParamType; 'blend-fit'?: ImgixParamType; 'blend-mode'?: ImgixParamType; 'blend-pad'?: ImgixParamType; 'blend-size'?: ImgixParamType; 'blend-x'?: ImgixParamType; 'blend-y'?: ImgixParamType; 'blend'?: ImgixParamType; } interface BorderAndPaddingParams { 'border-radius-inner'?: ImgixParamType; 'border-radius'?: ImgixParamType; border?: ImgixParamType; pad?: ImgixParamType; } interface ColorPaletteParams { colors?: ImgixParamType; palette?: ImgixParamType; prefix?: ImgixParamType; } interface FaceDetectionParams { faceindex?: ImgixParamType; facepad?: ImgixParamType; faces?: ImgixParamType; } interface FillParams { bg?: ImgixParamType; 'fill-color'?: ImgixParamType; fill?: ImgixParamType; } interface FocalPointCropParams { 'fp-debug'?: ImgixParamType; 'fp-x'?: ImgixParamType; 'fp-y'?: ImgixParamType; 'fp-z'?: ImgixParamType; } interface FormatParams { ch?: ImgixParamType; chromasub?: ImgixParamType; colorquant?: ImgixParamType; cs?: ImgixParamType; dl?: ImgixParamType; dpi?: ImgixParamType; fm?: ImgixParamType; lossless?: ImgixParamType; q?: ImgixParamType; } interface MaskImageParams { 'corner-radius'?: ImgixParamType; mask?: ImgixParamType; } interface NoiseReductionParams { nr?: ImgixParamType; nrs?: ImgixParamType; } interface PDFParams { page?: ImgixParamType; } interface PixelDensityParams { dpr?: ImgixParamType; } interface RotationParams { flip?: ImgixParamType; orient?: ImgixParamType; rot?: ImgixParamType; } interface SizeParams { ar?: ImgixParamType; crop?: ImgixParamType; fit?: ImgixParamType; h?: ImgixParamType; 'max-h'?: ImgixParamType; 'max-w'?: ImgixParamType; 'min-h'?: ImgixParamType; 'min-w'?: ImgixParamType; rect?: ImgixParamType; w?: ImgixParamType; } interface StylizeParams { blur?: ImgixParamType; 'duotone-alpha'?: ImgixParamType; duotone?: ImgixParamType; htn?: ImgixParamType; monochrome?: ImgixParamType; px?: ImgixParamType; sepia?: ImgixParamType; } interface TextParams { 'txt-align'?: ImgixParamType; 'txt-clip'?: ImgixParamType; 'txt-color'?: ImgixParamType; 'txt-fit'?: ImgixParamType; 'txt-font'?: ImgixParamType; 'txt-lig'?: ImgixParamType; 'txt-line-color'?: ImgixParamType; 'txt-line'?: ImgixParamType; 'txt-pad'?: ImgixParamType; 'txt-shad'?: ImgixParamType; 'txt-size'?: ImgixParamType; 'txt-width'?: ImgixParamType; txt?: ImgixParamType; } interface TrimParams { 'trim-color'?: ImgixParamType; 'trim-md'?: ImgixParamType; 'trim-sd'?: ImgixParamType; 'trim-tol'?: ImgixParamType; trim?: ImgixParamType; } interface TypesettingEndpointParams { 'txt-lead'?: ImgixParamType; 'txt-track'?: ImgixParamType; '~text'?: ImgixParamType; } interface WatermarkParams { 'mark-align'?: ImgixParamType; 'mark-alpha'?: ImgixParamType; 'mark-base'?: ImgixParamType; 'mark-fit'?: ImgixParamType; 'mark-h'?: ImgixParamType; 'mark-pad'?: ImgixParamType; 'mark-scale'?: ImgixParamType; 'mark-w'?: ImgixParamType; 'mark-x'?: ImgixParamType; 'mark-y'?: ImgixParamType; mark?: ImgixParamType; } type ImigixParams = & AdjustmentParams & AutomaticParams & BlendingParams & BorderAndPaddingParams & ColorPaletteParams & FaceDetectionParams & FillParams & FocalPointCropParams & FormatParams & MaskImageParams & NoiseReductionParams & PDFParams & PixelDensityParams & RotationParams & SizeParams & StylizeParams & TextParams & TrimParams & TypesettingEndpointParams & WatermarkParams ; interface AttributeConfig { src?: string; srcSet?: string; sizes?: string; } type ImgixHTMLAttributes = React.ImgHTMLAttributes<HTMLImageElement> | React.SourceHTMLAttributes<HTMLSourceElement> | Record<string, string>; interface CommonProps { className?: string; onMounted?: (ref?: React.RefObject<HTMLPictureElement | HTMLImageElement | HTMLSourceElement>) => void; htmlAttributes?: ImgixHTMLAttributes; } export interface SharedImigixAndSourceProps extends CommonProps { src: string; disableQualityByDPR?: boolean; disableSrcSet?: boolean; disableLibraryParam?: boolean; imgixParams?: ImigixParams; sizes?: string; width?: number; height?: number; attributeConfig?: AttributeConfig; } export class Picture extends React.Component<React.PropsWithChildren<CommonProps>> {} export class Source extends React.Component<SharedImigixAndSourceProps> {} export function buildURL(src: string, imgixParams?: ImigixParams, options?: SharedImigixAndSourceProps): string; type Warnings = 'fallbackImage' | 'sizesAttribute' | 'invalidARFormat'; export namespace PublicConfigAPI { function disableWarning(name: Warnings): void; function enableWarning(name: Warnings): void; } export interface BackgroundProps { src: string; imgixParams?: ImigixParams; className?: string; disableLibraryParam?: boolean; htmlAttributes?: ImgixHTMLAttributes; } export const Background: React.FunctionComponent<React.PropsWithChildren<BackgroundProps>>; declare class Imgix extends React.Component<SharedImigixAndSourceProps> {} export default Imgix;
types/react-imgix/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e3aa081074c711797fedab41ce129432c5d209b4
[ 0.0004205315199214965, 0.00018921685114037246, 0.0001655865926295519, 0.00017009006114676595, 0.00006367994501488283 ]
{ "id": 0, "code_window": [ " \"@storybook/ui\": \"6.0.0-alpha.1\",\n", " \"airbnb-js-shims\": \"^2.2.1\",\n", " \"ansi-to-html\": \"^0.6.11\",\n", " \"autoprefixer\": \"^9.7.2\",\n", " \"babel-merge\": \"^3.0.0\",\n", " \"babel-plugin-add-react-displayname\": \"^0.0.5\",\n", " \"babel-plugin-emotion\": \"^10.0.20\",\n", " \"babel-plugin-macros\": \"^2.8.0\",\n", " \"babel-preset-minify\": \"^0.5.0 || 0.6.0-alpha.5\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/core/package.json", "type": "replace", "edit_start_line_idx": 50 }
import merge from 'babel-merge'; import { includePaths, excludePaths } from '../config/utils'; export default options => ({ test: /\.(mjs|jsx?)$/, use: [ { loader: 'babel-loader', options: { ...options, ...merge(options, { presets: [ ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }], '@babel/preset-typescript', '@babel/preset-react', ], plugins: [ ['@babel/plugin-proposal-class-properties', { loose: true }], '@babel/plugin-proposal-export-default-from', '@babel/plugin-syntax-dynamic-import', ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }], 'babel-plugin-macros', ], }), }, }, ], include: includePaths, exclude: excludePaths, });
lib/core/src/server/manager/babel-loader-manager.js
1
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00019163329852744937, 0.00017668938380666077, 0.00016494886949658394, 0.00017508771270513535, 0.000010288741577824112 ]
{ "id": 0, "code_window": [ " \"@storybook/ui\": \"6.0.0-alpha.1\",\n", " \"airbnb-js-shims\": \"^2.2.1\",\n", " \"ansi-to-html\": \"^0.6.11\",\n", " \"autoprefixer\": \"^9.7.2\",\n", " \"babel-merge\": \"^3.0.0\",\n", " \"babel-plugin-add-react-displayname\": \"^0.0.5\",\n", " \"babel-plugin-emotion\": \"^10.0.20\",\n", " \"babel-plugin-macros\": \"^2.8.0\",\n", " \"babel-preset-minify\": \"^0.5.0 || 0.6.0-alpha.5\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/core/package.json", "type": "replace", "edit_start_line_idx": 50 }
package OpenSourceProjects_Storybook.patches.buildTypes import jetbrains.buildServer.configs.kotlin.v2017_2.* import jetbrains.buildServer.configs.kotlin.v2017_2.ui.* /* This patch script was generated by TeamCity on settings change in UI. To apply the patch, change the buildType with uuid = '8cc5f747-4ca7-4f0d-940d-b0c422f501a6-riot' (id = 'OpenSourceProjects_Storybook_Riot') accordingly, and delete the patch script. */ changeBuildType("8cc5f747-4ca7-4f0d-940d-b0c422f501a6-riot") { check(paused == false) { "Unexpected paused: '$paused'" } paused = true }
.teamcity/OpenSourceProjects_Storybook/patches/buildTypes/8cc5f747-4ca7-4f0d-940d-b0c422f501a6-riot.kts
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.0001685421448200941, 0.00016850880638230592, 0.00016847546794451773, 0.00016850880638230592, 3.333843778818846e-8 ]
{ "id": 0, "code_window": [ " \"@storybook/ui\": \"6.0.0-alpha.1\",\n", " \"airbnb-js-shims\": \"^2.2.1\",\n", " \"ansi-to-html\": \"^0.6.11\",\n", " \"autoprefixer\": \"^9.7.2\",\n", " \"babel-merge\": \"^3.0.0\",\n", " \"babel-plugin-add-react-displayname\": \"^0.0.5\",\n", " \"babel-plugin-emotion\": \"^10.0.20\",\n", " \"babel-plugin-macros\": \"^2.8.0\",\n", " \"babel-preset-minify\": \"^0.5.0 || 0.6.0-alpha.5\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/core/package.json", "type": "replace", "edit_start_line_idx": 50 }
/* eslint-disable */ import React from 'react'; import Button from './Button'; import { storiesOf } from '@storybook/react'; storiesOf('Button', module) .addParameters({ component: Button, foo: 1 }) .addParameters({ bar: 2 }) .add('with kind parameters', () => <Button label="The Button" />);
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/parameters.input.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00017522535927128047, 0.00017248393851332366, 0.0001697425323072821, 0.00017248393851332366, 0.0000027414134819991887 ]
{ "id": 0, "code_window": [ " \"@storybook/ui\": \"6.0.0-alpha.1\",\n", " \"airbnb-js-shims\": \"^2.2.1\",\n", " \"ansi-to-html\": \"^0.6.11\",\n", " \"autoprefixer\": \"^9.7.2\",\n", " \"babel-merge\": \"^3.0.0\",\n", " \"babel-plugin-add-react-displayname\": \"^0.0.5\",\n", " \"babel-plugin-emotion\": \"^10.0.20\",\n", " \"babel-plugin-macros\": \"^2.8.0\",\n", " \"babel-preset-minify\": \"^0.5.0 || 0.6.0-alpha.5\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/core/package.json", "type": "replace", "edit_start_line_idx": 50 }
{ "presets": ["@babel/preset-react"], "plugins": ["@babel/plugin-external-helpers"] }
lib/cli/test/fixtures/react/.babelrc
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00017882254905998707, 0.00017882254905998707, 0.00017882254905998707, 0.00017882254905998707, 0 ]
{ "id": 1, "code_window": [ "import merge from 'babel-merge';\n", "import { includePaths, excludePaths } from '../config/utils';\n", "\n" ], "labels": [ "replace", "replace", "keep" ], "after_edit": [ "import { includePaths } from '../config/utils';\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 0 }
{ "name": "@storybook/core", "version": "6.0.0-alpha.1", "description": "Storybook framework-agnostic API", "keywords": [ "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/lib/core", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "lib/core" }, "license": "MIT", "files": [ "dist/**/*", "dll/**/*", "README.md", "*.js", "*.d.ts" ], "main": "dist/client/index.js", "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/plugin-proposal-export-default-from": "^7.8.3", "@babel/plugin-proposal-object-rest-spread": "^7.8.3", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-transform-react-constant-elements": "^7.2.0", "@babel/preset-env": "^7.4.5", "@babel/preset-react": "^7.8.3", "@babel/preset-typescript": "^7.8.3", "@storybook/addons": "6.0.0-alpha.1", "@storybook/channel-postmessage": "6.0.0-alpha.1", "@storybook/client-api": "6.0.0-alpha.1", "@storybook/client-logger": "6.0.0-alpha.1", "@storybook/core-events": "6.0.0-alpha.1", "@storybook/csf": "0.0.1", "@storybook/node-logger": "6.0.0-alpha.1", "@storybook/router": "6.0.0-alpha.1", "@storybook/theming": "6.0.0-alpha.1", "@storybook/ui": "6.0.0-alpha.1", "airbnb-js-shims": "^2.2.1", "ansi-to-html": "^0.6.11", "autoprefixer": "^9.7.2", "babel-merge": "^3.0.0", "babel-plugin-add-react-displayname": "^0.0.5", "babel-plugin-emotion": "^10.0.20", "babel-plugin-macros": "^2.8.0", "babel-preset-minify": "^0.5.0 || 0.6.0-alpha.5", "boxen": "^4.1.0", "case-sensitive-paths-webpack-plugin": "^2.2.0", "chalk": "^3.0.0", "cli-table3": "0.5.1", "commander": "^4.0.1", "core-js": "^3.0.1", "corejs-upgrade-webpack-plugin": "^3.0.1", "css-loader": "^3.0.0", "detect-port": "^1.3.0", "dotenv-webpack": "^1.7.0", "ejs": "^2.7.4", "express": "^4.17.0", "file-loader": "^5.0.2", "file-system-cache": "^1.0.5", "find-cache-dir": "^3.0.0", "find-up": "^4.1.0", "fs-extra": "^8.0.1", "glob-base": "^0.3.0", "global": "^4.3.2", "html-webpack-plugin": "^4.0.0-beta.2", "inquirer": "^7.0.0", "interpret": "^2.0.0", "ip": "^1.1.5", "json5": "^2.1.1", "lazy-universal-dotenv": "^3.0.1", "micromatch": "^4.0.2", "node-fetch": "^2.6.0", "open": "^7.0.0", "pnp-webpack-plugin": "1.5.0", "postcss-flexbugs-fixes": "^4.1.0", "postcss-loader": "^3.0.0", "pretty-hrtime": "^1.0.3", "qs": "^6.6.0", "raw-loader": "^3.1.0", "react-dev-utils": "^10.0.0", "regenerator-runtime": "^0.13.3", "resolve": "^1.11.0", "resolve-from": "^5.0.0", "semver": "^6.0.0", "serve-favicon": "^2.5.0", "shelljs": "^0.8.3", "style-loader": "^1.0.0", "terser-webpack-plugin": "^2.1.2", "ts-dedent": "^1.1.0", "unfetch": "^4.1.0", "url-loader": "^2.0.1", "util-deprecate": "^1.0.2", "webpack": "^4.33.0", "webpack-dev-middleware": "^3.7.0", "webpack-hot-middleware": "^2.25.0", "webpack-virtual-modules": "^0.2.0" }, "devDependencies": { "mock-fs": "^4.8.0" }, "peerDependencies": { "@babel/core": "*", "babel-loader": "^7.0.0 || ^8.0.0", "react": "*", "react-dom": "*" }, "publishConfig": { "access": "public" }, "gitHead": "4b9d901add9452525135caae98ae5f78dd8da9ff" }
lib/core/package.json
1
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00030804952257312834, 0.0001901662180898711, 0.00016533542657271028, 0.00016924009833019227, 0.000040989674744196236 ]
{ "id": 1, "code_window": [ "import merge from 'babel-merge';\n", "import { includePaths, excludePaths } from '../config/utils';\n", "\n" ], "labels": [ "replace", "replace", "keep" ], "after_edit": [ "import { includePaths } from '../config/utils';\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 0 }
import React, { FunctionComponent } from 'react'; import { Subheading } from './Subheading'; import { DocsStoryProps } from './shared'; import { Anchor } from './Anchor'; import { Description } from './Description'; import { Story } from './Story'; import { Preview } from './Preview'; export const DocsStory: FunctionComponent<DocsStoryProps> = ({ id, name, expanded = true, withToolbar = false, parameters, }) => ( <Anchor storyId={id}> {expanded && <Subheading>{name}</Subheading>} {expanded && parameters && parameters.docs && parameters.docs.storyDescription && ( <Description markdown={parameters.docs.storyDescription} /> )} <Preview withToolbar={withToolbar}> <Story id={id} /> </Preview> </Anchor> );
addons/docs/src/blocks/DocsStory.tsx
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.0001720203727018088, 0.00016981501539703459, 0.0001680988643784076, 0.00016932579455897212, 0.0000016378962754970416 ]
{ "id": 1, "code_window": [ "import merge from 'babel-merge';\n", "import { includePaths, excludePaths } from '../config/utils';\n", "\n" ], "labels": [ "replace", "replace", "keep" ], "after_edit": [ "import { includePaths } from '../config/utils';\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 0 }
import { configure } from '@storybook/react'; // automatically import all files ending in *.stories.js const req = require.context('../stories', true, /\.stories\.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
lib/cli/test/fixtures/react_babel_config_js/.storybook/config.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.000163975651958026, 0.000163975651958026, 0.000163975651958026, 0.000163975651958026, 0 ]
{ "id": 1, "code_window": [ "import merge from 'babel-merge';\n", "import { includePaths, excludePaths } from '../config/utils';\n", "\n" ], "labels": [ "replace", "replace", "keep" ], "after_edit": [ "import { includePaths } from '../config/utils';\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 0 }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>BNDL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> </dict> </plist>
lib/cli/test/fixtures/react_native/ios/react_native-tvOSTests/Info.plist
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00016837590374052525, 0.00016766977205406874, 0.0001667597534833476, 0.00016787364438641816, 6.753566026418412e-7 ]
{ "id": 2, "code_window": [ "\n", "export default options => ({\n", " test: /\\.(mjs|jsx?)$/,\n", " use: [\n", " {\n", " loader: 'babel-loader',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export default () => ({\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 3 }
import merge from 'babel-merge'; import { includePaths, excludePaths } from '../config/utils'; export default options => ({ test: /\.(mjs|jsx?)$/, use: [ { loader: 'babel-loader', options: { ...options, ...merge(options, { presets: [ ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }], '@babel/preset-typescript', '@babel/preset-react', ], plugins: [ ['@babel/plugin-proposal-class-properties', { loose: true }], '@babel/plugin-proposal-export-default-from', '@babel/plugin-syntax-dynamic-import', ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }], 'babel-plugin-macros', ], }), }, }, ], include: includePaths, exclude: excludePaths, });
lib/core/src/server/manager/babel-loader-manager.js
1
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.9883725047111511, 0.49050119519233704, 0.00017953927454072982, 0.4867263734340668, 0.4903499484062195 ]
{ "id": 2, "code_window": [ "\n", "export default options => ({\n", " test: /\\.(mjs|jsx?)$/,\n", " use: [\n", " {\n", " loader: 'babel-loader',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export default () => ({\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 3 }
#!/usr/bin/env node process.env.NODE_ENV = process.env.NODE_ENV || 'production'; require('../dist/server/build');
app/svelte/bin/build.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.0001694269012659788, 0.0001694269012659788, 0.0001694269012659788, 0.0001694269012659788, 0 ]
{ "id": 2, "code_window": [ "\n", "export default options => ({\n", " test: /\\.(mjs|jsx?)$/,\n", " use: [\n", " {\n", " loader: 'babel-loader',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export default () => ({\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 3 }
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; import { logger } from '@storybook/node-logger'; import { Options } from 'ts-loader'; export default function(tsLoaderOptions: Partial<Options>) { if (tsLoaderOptions && tsLoaderOptions.configFile) { return new ForkTsCheckerWebpackPlugin({ tsconfig: tsLoaderOptions.configFile, async: false, }); } logger.info('=> Using default options for ForkTsCheckerWebpackPlugin'); return new ForkTsCheckerWebpackPlugin(); }
app/angular/src/server/create-fork-ts-checker-plugin.ts
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.0010291076032444835, 0.0006156470626592636, 0.00020218652207404375, 0.0006156470626592636, 0.00041346054058521986 ]
{ "id": 2, "code_window": [ "\n", "export default options => ({\n", " test: /\\.(mjs|jsx?)$/,\n", " use: [\n", " {\n", " loader: 'babel-loader',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export default () => ({\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 3 }
import recast from 'recast'; import { isExportStory } from '@storybook/csf'; function exportMdx(root, options) { // eslint-disable-next-line no-underscore-dangle const path = root.__paths[0]; // FIXME: insert the title as markdown after all of the imports return path.node.program.body .map(n => { const { code } = recast.prettyPrint(n, options); if (n.type === 'JSXElement') { return `${code}\n`; } return code; }) .join('\n'); } function parseIncludeExclude(prop) { const { code } = recast.prettyPrint(prop, {}); // eslint-disable-next-line no-eval return eval(code); } /** * Convert a component's module story file into an MDX file * * For example: * * ``` * input { Button } from './Button'; * export default { * title: 'Button' * } * export const story = () => <Button label="The Button" />; * ``` * * Becomes: * * ``` * import { Meta, Story } from '@storybook/addon-docs/blocks'; * input { Button } from './Button'; * * <Meta title='Button' /> * * <Story name='story'> * <Button label="The Button" /> * </Story> * ``` */ export default function transformer(file, api) { const j = api.jscodeshift; const root = j(file.source); // FIXME: save out all the storyFn.story = { ... } const storyKeyToStory = {}; // save out includeStories / excludeStories const meta = {}; function makeAttr(key, val) { return j.jsxAttribute( j.jsxIdentifier(key), val.type === 'Literal' ? val : j.jsxExpressionContainer(val) ); } function getStoryContents(node) { return node.type === 'ArrowFunctionExpression' && node.body.type === 'JSXElement' ? node.body : j.jsxExpressionContainer(node); } function getName(storyKey) { const story = storyKeyToStory[storyKey]; if (story) { const name = story.properties.find(prop => prop.key.name === 'name'); if (name && name.value.type === 'Literal') { return name.value.value; } } return storyKey; } function getStoryAttrs(storyKey) { const attrs = []; const story = storyKeyToStory[storyKey]; if (story) { story.properties.forEach(prop => { const { key, value } = prop; if (key.name !== 'name') { attrs.push(makeAttr(key.name, value)); } }); } return attrs; } // 1. If the program does not have `export default { title: '....' }, skip it const defaultExportWithTitle = root .find(j.ExportDefaultDeclaration) .filter(def => def.node.declaration.properties.map(p => p.key.name).includes('title')); if (defaultExportWithTitle.size() === 0) { return root.toSource(); } // 2a. Add imports from '@storybook/addon-docs/blocks' root .find(j.ImportDeclaration) .at(-1) .insertAfter(j.emptyStatement()) .insertAfter( j.importDeclaration( [j.importSpecifier(j.identifier('Meta')), j.importSpecifier(j.identifier('Story'))], j.literal('@storybook/addon-docs/blocks') ) ); // 2b. Remove react import which is implicit root .find(j.ImportDeclaration) .filter(decl => decl.node.source.value === 'react') .remove(); // 3. Save out all the excluded stories defaultExportWithTitle.forEach(exp => { exp.node.declaration.properties.forEach(p => { if (['includeStories', 'excludeStories'].includes(p.key.name)) { meta[p.key.name] = parseIncludeExclude(p.value); } }); }); // 4. Collect all the story exports in storyKeyToStory[key] = null; const namedExports = root.find(j.ExportNamedDeclaration); namedExports.forEach(exp => { const storyKey = exp.node.declaration.declarations[0].id.name; if (isExportStory(storyKey, meta)) { storyKeyToStory[storyKey] = null; } }); // 5. Collect all the storyKey.story in storyKeyToStory and also remove them const storyAssignments = root.find(j.AssignmentExpression).filter(exp => { const { left } = exp.node; return ( left.type === 'MemberExpression' && left.object.type === 'Identifier' && left.object.name in storyKeyToStory && left.property.type === 'Identifier' && left.property.name === 'story' ); }); storyAssignments.forEach(exp => { const { left, right } = exp.node; storyKeyToStory[left.object.name] = right; }); storyAssignments.remove(); // 6. Convert the default export to <Meta /> defaultExportWithTitle.replaceWith(exp => { const jsxId = j.jsxIdentifier('Meta'); const attrs = []; exp.node.declaration.properties.forEach(prop => { const { key, value } = prop; if (!['includeStories', 'excludeStories'].includes(key.name)) { attrs.push(makeAttr(key.name, value)); } }); const opening = j.jsxOpeningElement(jsxId, attrs); opening.selfClosing = true; return j.jsxElement(opening); }); // 7. Convert all the named exports to <Story>...</Story> namedExports.replaceWith(exp => { const storyKey = exp.node.declaration.declarations[0].id.name; if (!isExportStory(storyKey, meta)) { return exp.node; } const jsxId = j.jsxIdentifier('Story'); const name = getName(storyKey); const attributes = [makeAttr('name', j.literal(name)), ...getStoryAttrs(storyKey)]; const opening = j.jsxOpeningElement(jsxId, attributes); const closing = j.jsxClosingElement(jsxId); const children = [getStoryContents(exp.node.declaration.declarations[0].init)]; return j.jsxElement(opening, closing, children); }); return exportMdx(root, { quote: 'single', trailingComma: 'true', tabWidth: 2 }); }
lib/codemod/src/transforms/csf-to-mdx.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.007586396764963865, 0.0006718606455251575, 0.00016516288451384753, 0.00017336853488814086, 0.0016267112223431468 ]
{ "id": 3, "code_window": [ " {\n", " loader: 'babel-loader',\n", " options: {\n", " ...options,\n", " ...merge(options, {\n", " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n", " }),\n", " },\n", " },\n", " ],\n", " include: includePaths,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 9 }
{ "name": "@storybook/core", "version": "6.0.0-alpha.1", "description": "Storybook framework-agnostic API", "keywords": [ "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/lib/core", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "lib/core" }, "license": "MIT", "files": [ "dist/**/*", "dll/**/*", "README.md", "*.js", "*.d.ts" ], "main": "dist/client/index.js", "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/plugin-proposal-export-default-from": "^7.8.3", "@babel/plugin-proposal-object-rest-spread": "^7.8.3", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-transform-react-constant-elements": "^7.2.0", "@babel/preset-env": "^7.4.5", "@babel/preset-react": "^7.8.3", "@babel/preset-typescript": "^7.8.3", "@storybook/addons": "6.0.0-alpha.1", "@storybook/channel-postmessage": "6.0.0-alpha.1", "@storybook/client-api": "6.0.0-alpha.1", "@storybook/client-logger": "6.0.0-alpha.1", "@storybook/core-events": "6.0.0-alpha.1", "@storybook/csf": "0.0.1", "@storybook/node-logger": "6.0.0-alpha.1", "@storybook/router": "6.0.0-alpha.1", "@storybook/theming": "6.0.0-alpha.1", "@storybook/ui": "6.0.0-alpha.1", "airbnb-js-shims": "^2.2.1", "ansi-to-html": "^0.6.11", "autoprefixer": "^9.7.2", "babel-merge": "^3.0.0", "babel-plugin-add-react-displayname": "^0.0.5", "babel-plugin-emotion": "^10.0.20", "babel-plugin-macros": "^2.8.0", "babel-preset-minify": "^0.5.0 || 0.6.0-alpha.5", "boxen": "^4.1.0", "case-sensitive-paths-webpack-plugin": "^2.2.0", "chalk": "^3.0.0", "cli-table3": "0.5.1", "commander": "^4.0.1", "core-js": "^3.0.1", "corejs-upgrade-webpack-plugin": "^3.0.1", "css-loader": "^3.0.0", "detect-port": "^1.3.0", "dotenv-webpack": "^1.7.0", "ejs": "^2.7.4", "express": "^4.17.0", "file-loader": "^5.0.2", "file-system-cache": "^1.0.5", "find-cache-dir": "^3.0.0", "find-up": "^4.1.0", "fs-extra": "^8.0.1", "glob-base": "^0.3.0", "global": "^4.3.2", "html-webpack-plugin": "^4.0.0-beta.2", "inquirer": "^7.0.0", "interpret": "^2.0.0", "ip": "^1.1.5", "json5": "^2.1.1", "lazy-universal-dotenv": "^3.0.1", "micromatch": "^4.0.2", "node-fetch": "^2.6.0", "open": "^7.0.0", "pnp-webpack-plugin": "1.5.0", "postcss-flexbugs-fixes": "^4.1.0", "postcss-loader": "^3.0.0", "pretty-hrtime": "^1.0.3", "qs": "^6.6.0", "raw-loader": "^3.1.0", "react-dev-utils": "^10.0.0", "regenerator-runtime": "^0.13.3", "resolve": "^1.11.0", "resolve-from": "^5.0.0", "semver": "^6.0.0", "serve-favicon": "^2.5.0", "shelljs": "^0.8.3", "style-loader": "^1.0.0", "terser-webpack-plugin": "^2.1.2", "ts-dedent": "^1.1.0", "unfetch": "^4.1.0", "url-loader": "^2.0.1", "util-deprecate": "^1.0.2", "webpack": "^4.33.0", "webpack-dev-middleware": "^3.7.0", "webpack-hot-middleware": "^2.25.0", "webpack-virtual-modules": "^0.2.0" }, "devDependencies": { "mock-fs": "^4.8.0" }, "peerDependencies": { "@babel/core": "*", "babel-loader": "^7.0.0 || ^8.0.0", "react": "*", "react-dom": "*" }, "publishConfig": { "access": "public" }, "gitHead": "4b9d901add9452525135caae98ae5f78dd8da9ff" }
lib/core/package.json
1
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.0005082420539110899, 0.0001978894288185984, 0.00016348528151866049, 0.00016909718397073448, 0.00009005598985822871 ]
{ "id": 3, "code_window": [ " {\n", " loader: 'babel-loader',\n", " options: {\n", " ...options,\n", " ...merge(options, {\n", " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n", " }),\n", " },\n", " },\n", " ],\n", " include: includePaths,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 9 }
module.exports = { settings: { react: { pragma: 'createElement', }, }, };
examples/rax-kitchen-sink/.eslintrc.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00016251839406322688, 0.00016251839406322688, 0.00016251839406322688, 0.00016251839406322688, 0 ]
{ "id": 3, "code_window": [ " {\n", " loader: 'babel-loader',\n", " options: {\n", " ...options,\n", " ...merge(options, {\n", " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n", " }),\n", " },\n", " },\n", " ],\n", " include: includePaths,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 9 }
module.exports = { stories: ['../stories/**/*.stories.(js|mdx)'], addons: ['@storybook/addon-docs'], };
lib/cli/generators/HTML/template-mdx/.storybook/main.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00016145632253028452, 0.00016145632253028452, 0.00016145632253028452, 0.00016145632253028452, 0 ]
{ "id": 3, "code_window": [ " {\n", " loader: 'babel-loader',\n", " options: {\n", " ...options,\n", " ...merge(options, {\n", " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n", " }),\n", " },\n", " },\n", " ],\n", " include: includePaths,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " presets: [\n", " ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],\n", " '@babel/preset-typescript',\n", " '@babel/preset-react',\n", " ],\n", " plugins: [\n", " ['@babel/plugin-proposal-class-properties', { loose: true }],\n", " '@babel/plugin-proposal-export-default-from',\n", " '@babel/plugin-syntax-dynamic-import',\n", " ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],\n", " 'babel-plugin-macros',\n", " ],\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 9 }
import { Parser } from 'acorn'; // @ts-ignore import jsx from 'acorn-jsx'; import { isNil } from 'lodash'; import estree from 'estree'; // @ts-ignore import * as acornWalk from 'acorn-walk'; import { InspectionType, InspectionLiteral, InspectionElement, InspectionFunction, InspectionClass, InspectionObject, InspectionUnknown, InspectionIdentifier, InspectionArray, InspectionInferedType, } from './types'; interface ParsingResult<T> { inferedType: T; ast: any; } const ACORN_WALK_VISITORS = { ...acornWalk.base, JSXElement: () => {}, }; const acornParser = Parser.extend(jsx()); // Cannot use "estree.Identifier" type because this function also support "JSXIdentifier". function extractIdentifierName(identifierNode: any) { return !isNil(identifierNode) ? identifierNode.name : null; } function filterAncestors(ancestors: estree.Node[]): estree.Node[] { return ancestors.filter(x => x.type === 'ObjectExpression' || x.type === 'ArrayExpression'); } function calculateNodeDepth(node: estree.Expression): number { const depths: number[] = []; acornWalk.ancestor( node, { ObjectExpression(_: any, ancestors: estree.Node[]) { depths.push(filterAncestors(ancestors).length); }, ArrayExpression(_: any, ancestors: estree.Node[]) { depths.push(filterAncestors(ancestors).length); }, }, ACORN_WALK_VISITORS ); return Math.max(...depths); } function parseIdentifier(identifierNode: estree.Identifier): ParsingResult<InspectionIdentifier> { return { inferedType: { type: InspectionType.IDENTIFIER, identifier: extractIdentifierName(identifierNode), }, ast: identifierNode, }; } function parseLiteral(literalNode: estree.Literal): ParsingResult<InspectionLiteral> { return { inferedType: { type: InspectionType.LITERAL }, ast: literalNode, }; } function parseFunction( funcNode: estree.FunctionExpression | estree.ArrowFunctionExpression ): ParsingResult<InspectionFunction | InspectionElement> { let innerJsxElementNode; // If there is at least a JSXElement in the body of the function, then it's a React component. acornWalk.simple( funcNode.body, { JSXElement(node: any) { innerJsxElementNode = node; }, }, ACORN_WALK_VISITORS ); const isJsx = !isNil(innerJsxElementNode); const inferedType: InspectionFunction | InspectionElement = { type: isJsx ? InspectionType.ELEMENT : InspectionType.FUNCTION, params: funcNode.params, hasParams: funcNode.params.length !== 0, }; const identifierName = extractIdentifierName((funcNode as estree.FunctionExpression).id); if (!isNil(identifierName)) { inferedType.identifier = identifierName; } return { inferedType, ast: funcNode, }; } function parseClass( classNode: estree.ClassExpression ): ParsingResult<InspectionClass | InspectionElement> { let innerJsxElementNode; // If there is at least a JSXElement in the body of the class, then it's a React component. acornWalk.simple( classNode.body, { JSXElement(node: any) { innerJsxElementNode = node; }, }, ACORN_WALK_VISITORS ); const inferedType: any = { type: !isNil(innerJsxElementNode) ? InspectionType.ELEMENT : InspectionType.CLASS, identifier: extractIdentifierName(classNode.id), }; return { inferedType, ast: classNode, }; } function parseJsxElement(jsxElementNode: any): ParsingResult<InspectionElement> { const inferedType: InspectionElement = { type: InspectionType.ELEMENT, }; const identifierName = extractIdentifierName(jsxElementNode.openingElement.name); if (!isNil(identifierName)) { inferedType.identifier = identifierName; } return { inferedType, ast: jsxElementNode, }; } function parseCall(callNode: estree.CallExpression): ParsingResult<InspectionObject> { const identifierNode = callNode.callee.type === 'MemberExpression' ? callNode.callee.property : callNode.callee; const identifierName = extractIdentifierName(identifierNode); if (identifierName === 'shape') { return parseObject(callNode.arguments[0] as estree.ObjectExpression); } return null; } function parseObject(objectNode: estree.ObjectExpression): ParsingResult<InspectionObject> { return { inferedType: { type: InspectionType.OBJECT, depth: calculateNodeDepth(objectNode) }, ast: objectNode, }; } function parseArray(arrayNode: estree.ArrayExpression): ParsingResult<InspectionArray> { return { inferedType: { type: InspectionType.ARRAY, depth: calculateNodeDepth(arrayNode) }, ast: arrayNode, }; } // Cannot set "expression" type to "estree.Expression" because the type doesn't include JSX. function parseExpression(expression: any): ParsingResult<InspectionInferedType> { switch (expression.type) { case 'Identifier': return parseIdentifier(expression); case 'Literal': return parseLiteral(expression); case 'FunctionExpression': case 'ArrowFunctionExpression': return parseFunction(expression); case 'ClassExpression': return parseClass(expression); case 'JSXElement': return parseJsxElement(expression); case 'CallExpression': return parseCall(expression); case 'ObjectExpression': return parseObject(expression); case 'ArrayExpression': return parseArray(expression); default: return null; } } export function parse(value: string): ParsingResult<InspectionInferedType> { const ast = (acornParser.parse(`(${value})`) as unknown) as estree.Program; let parsingResult: ParsingResult<InspectionUnknown> = { inferedType: { type: InspectionType.UNKNOWN }, ast, }; if (!isNil(ast.body[0])) { const rootNode = ast.body[0]; switch (rootNode.type) { case 'ExpressionStatement': { const expressionResult = parseExpression(rootNode.expression); if (!isNil(expressionResult)) { parsingResult = expressionResult as any; } break; } default: break; } } return parsingResult; }
addons/docs/src/frameworks/react/lib/inspection/acornParser.ts
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00017048187146428972, 0.00016587931895628572, 0.00015983935736585408, 0.0001659689878579229, 0.0000027116743694932666 ]
{ "id": 4, "code_window": [ " },\n", " ],\n", " include: includePaths,\n", " exclude: excludePaths,\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " exclude: /node_module|dist/,\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 28 }
{ "name": "@storybook/core", "version": "6.0.0-alpha.1", "description": "Storybook framework-agnostic API", "keywords": [ "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/lib/core", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "lib/core" }, "license": "MIT", "files": [ "dist/**/*", "dll/**/*", "README.md", "*.js", "*.d.ts" ], "main": "dist/client/index.js", "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/plugin-proposal-export-default-from": "^7.8.3", "@babel/plugin-proposal-object-rest-spread": "^7.8.3", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-transform-react-constant-elements": "^7.2.0", "@babel/preset-env": "^7.4.5", "@babel/preset-react": "^7.8.3", "@babel/preset-typescript": "^7.8.3", "@storybook/addons": "6.0.0-alpha.1", "@storybook/channel-postmessage": "6.0.0-alpha.1", "@storybook/client-api": "6.0.0-alpha.1", "@storybook/client-logger": "6.0.0-alpha.1", "@storybook/core-events": "6.0.0-alpha.1", "@storybook/csf": "0.0.1", "@storybook/node-logger": "6.0.0-alpha.1", "@storybook/router": "6.0.0-alpha.1", "@storybook/theming": "6.0.0-alpha.1", "@storybook/ui": "6.0.0-alpha.1", "airbnb-js-shims": "^2.2.1", "ansi-to-html": "^0.6.11", "autoprefixer": "^9.7.2", "babel-merge": "^3.0.0", "babel-plugin-add-react-displayname": "^0.0.5", "babel-plugin-emotion": "^10.0.20", "babel-plugin-macros": "^2.8.0", "babel-preset-minify": "^0.5.0 || 0.6.0-alpha.5", "boxen": "^4.1.0", "case-sensitive-paths-webpack-plugin": "^2.2.0", "chalk": "^3.0.0", "cli-table3": "0.5.1", "commander": "^4.0.1", "core-js": "^3.0.1", "corejs-upgrade-webpack-plugin": "^3.0.1", "css-loader": "^3.0.0", "detect-port": "^1.3.0", "dotenv-webpack": "^1.7.0", "ejs": "^2.7.4", "express": "^4.17.0", "file-loader": "^5.0.2", "file-system-cache": "^1.0.5", "find-cache-dir": "^3.0.0", "find-up": "^4.1.0", "fs-extra": "^8.0.1", "glob-base": "^0.3.0", "global": "^4.3.2", "html-webpack-plugin": "^4.0.0-beta.2", "inquirer": "^7.0.0", "interpret": "^2.0.0", "ip": "^1.1.5", "json5": "^2.1.1", "lazy-universal-dotenv": "^3.0.1", "micromatch": "^4.0.2", "node-fetch": "^2.6.0", "open": "^7.0.0", "pnp-webpack-plugin": "1.5.0", "postcss-flexbugs-fixes": "^4.1.0", "postcss-loader": "^3.0.0", "pretty-hrtime": "^1.0.3", "qs": "^6.6.0", "raw-loader": "^3.1.0", "react-dev-utils": "^10.0.0", "regenerator-runtime": "^0.13.3", "resolve": "^1.11.0", "resolve-from": "^5.0.0", "semver": "^6.0.0", "serve-favicon": "^2.5.0", "shelljs": "^0.8.3", "style-loader": "^1.0.0", "terser-webpack-plugin": "^2.1.2", "ts-dedent": "^1.1.0", "unfetch": "^4.1.0", "url-loader": "^2.0.1", "util-deprecate": "^1.0.2", "webpack": "^4.33.0", "webpack-dev-middleware": "^3.7.0", "webpack-hot-middleware": "^2.25.0", "webpack-virtual-modules": "^0.2.0" }, "devDependencies": { "mock-fs": "^4.8.0" }, "peerDependencies": { "@babel/core": "*", "babel-loader": "^7.0.0 || ^8.0.0", "react": "*", "react-dom": "*" }, "publishConfig": { "access": "public" }, "gitHead": "4b9d901add9452525135caae98ae5f78dd8da9ff" }
lib/core/package.json
1
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00017531643970869482, 0.0001682574802543968, 0.00016510211571585387, 0.00016770549700595438, 0.0000025322781311842846 ]
{ "id": 4, "code_window": [ " },\n", " ],\n", " include: includePaths,\n", " exclude: excludePaths,\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " exclude: /node_module|dist/,\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 28 }
{ "extends": "../../tsconfig.json", "compilerOptions": { "rootDir": "./src", "types": [ "jest", "react-syntax-highlighter" ] }, "include": [ "src/**/*" ], "exclude": [ "src/**/__tests__/**/*", "src/**/*.stories.*" ] }
lib/components/tsconfig.json
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00019928858091589063, 0.00018310672021470964, 0.00016692487406544387, 0.00018310672021470964, 0.00001618185342522338 ]
{ "id": 4, "code_window": [ " },\n", " ],\n", " include: includePaths,\n", " exclude: excludePaths,\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " exclude: /node_module|dist/,\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 28 }
{ "name": "@storybook/angular", "version": "6.0.0-alpha.1", "description": "Storybook for Angular: Develop Angular Components in isolation with Hot Reloading.", "keywords": [ "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/app/angular", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "app/angular" }, "license": "MIT", "files": [ "bin/**/*", "dist/**/*", "README.md", "*.js", "*.d.ts" ], "main": "dist/client/index.js", "types": "dist/client/index.d.ts", "bin": { "build-storybook": "./bin/build.js", "start-storybook": "./bin/index.js", "storybook-server": "./bin/index.js" }, "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addons": "6.0.0-alpha.1", "@storybook/core": "6.0.0-alpha.1", "@storybook/node-logger": "6.0.0-alpha.1", "@types/webpack-env": "^1.15.0", "core-js": "^3.0.1", "fork-ts-checker-webpack-plugin": "^3.0.1", "global": "^4.3.2", "regenerator-runtime": "^0.13.3", "sass-loader": "^8.0.0", "strip-json-comments": "^3.0.1", "ts-loader": "^6.0.1", "tsconfig-paths-webpack-plugin": "^3.2.0" }, "devDependencies": { "@types/autoprefixer": "^9.4.0", "webpack": "^4.33.0" }, "peerDependencies": { "@angular-devkit/build-angular": ">=0.8.9", "@angular-devkit/core": "^0.6.1 || >=7.0.0", "@angular/common": ">=6.0.0", "@angular/compiler": ">=6.0.0", "@angular/core": ">=6.0.0", "@angular/forms": ">=6.0.0", "@angular/platform-browser": ">=6.0.0", "@angular/platform-browser-dynamic": ">=6.0.0", "autoprefixer": "^8.1.0", "babel-loader": "^7.0.0 || ^8.0.0", "rxjs": "^6.0.0", "typescript": "^3.4.0", "webpack": "^4.32.0", "zone.js": "^0.8.29 || ^0.9.0 || ^0.10.0" }, "engines": { "node": ">=8.0.0" }, "publishConfig": { "access": "public" }, "gitHead": "4b9d901add9452525135caae98ae5f78dd8da9ff" }
app/angular/package.json
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.00017077864322345704, 0.00016717182006686926, 0.00016432923439424485, 0.00016678441897965968, 0.000001879011847449874 ]
{ "id": 4, "code_window": [ " },\n", " ],\n", " include: includePaths,\n", " exclude: excludePaths,\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " exclude: /node_module|dist/,\n" ], "file_path": "lib/core/src/server/manager/babel-loader-manager.js", "type": "replace", "edit_start_line_idx": 28 }
export default { title: 'Story', }; export const startCase = () => 'foo'; export const camelCase = () => 'foo'; camelCase.story = { name: 'camelCase', };
lib/cli/story.js
0
https://github.com/storybookjs/storybook/commit/55f7f8ea0ab402b5ec21ae87c17d3158f04d69b2
[ 0.000174833505298011, 0.00017368377302773297, 0.00017253404075745493, 0.00017368377302773297, 0.0000011497322702780366 ]
{ "id": 0, "code_window": [ " return [\n", " eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 53 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.9891959428787231, 0.015858720988035202, 0.00016337682609446347, 0.0002342563821002841, 0.1164146140217781 ]
{ "id": 0, "code_window": [ " return [\n", " eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 53 }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsRemoteDebuggingPipe.h" #include <cstring> #if defined(_WIN32) #include <io.h> #include <windows.h> #else #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #endif #include "mozilla/StaticPtr.h" #include "nsISupportsPrimitives.h" #include "nsThreadUtils.h" namespace mozilla { NS_IMPL_ISUPPORTS(nsRemoteDebuggingPipe, nsIRemoteDebuggingPipe) namespace { StaticRefPtr<nsRemoteDebuggingPipe> gPipe; const size_t kWritePacketSize = 1 << 16; #if defined(_WIN32) HANDLE readHandle; HANDLE writeHandle; #else const int readFD = 3; const int writeFD = 4; #endif size_t ReadBytes(void* buffer, size_t size, bool exact_size) { size_t bytesRead = 0; while (bytesRead < size) { #if defined(_WIN32) DWORD sizeRead = 0; bool hadError = !ReadFile(readHandle, static_cast<char*>(buffer) + bytesRead, size - bytesRead, &sizeRead, nullptr); #else int sizeRead = read(readFD, static_cast<char*>(buffer) + bytesRead, size - bytesRead); if (sizeRead < 0 && errno == EINTR) continue; bool hadError = sizeRead <= 0; #endif if (hadError) { return 0; } bytesRead += sizeRead; if (!exact_size) break; } return bytesRead; } void WriteBytes(const char* bytes, size_t size) { size_t totalWritten = 0; while (totalWritten < size) { size_t length = size - totalWritten; if (length > kWritePacketSize) length = kWritePacketSize; #if defined(_WIN32) DWORD bytesWritten = 0; bool hadError = !WriteFile(writeHandle, bytes + totalWritten, static_cast<DWORD>(length), &bytesWritten, nullptr); #else int bytesWritten = write(writeFD, bytes + totalWritten, length); if (bytesWritten < 0 && errno == EINTR) continue; bool hadError = bytesWritten <= 0; #endif if (hadError) return; totalWritten += bytesWritten; } } } // namespace // static already_AddRefed<nsIRemoteDebuggingPipe> nsRemoteDebuggingPipe::GetSingleton() { if (!gPipe) { gPipe = new nsRemoteDebuggingPipe(); } return do_AddRef(gPipe); } nsRemoteDebuggingPipe::nsRemoteDebuggingPipe() = default; nsRemoteDebuggingPipe::~nsRemoteDebuggingPipe() = default; nsresult nsRemoteDebuggingPipe::Init(nsIRemoteDebuggingPipeClient* aClient) { MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Remote debugging pipe must be used on the Main thread."); if (mClient) { return NS_ERROR_FAILURE; } mClient = aClient; MOZ_ALWAYS_SUCCEEDS(NS_NewNamedThread("Pipe Reader", getter_AddRefs(mReaderThread))); MOZ_ALWAYS_SUCCEEDS(NS_NewNamedThread("Pipe Writer", getter_AddRefs(mWriterThread))); #if defined(_WIN32) CHAR pipeReadStr[20]; CHAR pipeWriteStr[20]; GetEnvironmentVariableA("PW_PIPE_READ", pipeReadStr, 20); GetEnvironmentVariableA("PW_PIPE_WRITE", pipeWriteStr, 20); readHandle = reinterpret_cast<HANDLE>(atoi(pipeReadStr)); writeHandle = reinterpret_cast<HANDLE>(atoi(pipeWriteStr)); #endif MOZ_ALWAYS_SUCCEEDS(mReaderThread->Dispatch(NewRunnableMethod( "nsRemoteDebuggingPipe::ReaderLoop", this, &nsRemoteDebuggingPipe::ReaderLoop), nsIThread::DISPATCH_NORMAL)); return NS_OK; } nsresult nsRemoteDebuggingPipe::Stop() { MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Remote debugging pipe must be used on the Main thread."); if (!mClient) { return NS_ERROR_FAILURE; } m_terminated = true; mClient = nullptr; // Cancel pending synchronous read. #if defined(_WIN32) CancelIoEx(readHandle, nullptr); CloseHandle(readHandle); CloseHandle(writeHandle); #else shutdown(readFD, SHUT_RDWR); shutdown(writeFD, SHUT_RDWR); #endif mReaderThread->Shutdown(); mReaderThread = nullptr; mWriterThread->Shutdown(); mWriterThread = nullptr; return NS_OK; } void nsRemoteDebuggingPipe::ReaderLoop() { const size_t bufSize = 256 * 1024; std::vector<char> buffer; buffer.resize(bufSize); std::vector<char> line; while (!m_terminated) { size_t size = ReadBytes(buffer.data(), bufSize, false); if (!size) { nsCOMPtr<nsIRunnable> runnable = NewRunnableMethod<>( "nsRemoteDebuggingPipe::Disconnected", this, &nsRemoteDebuggingPipe::Disconnected); NS_DispatchToMainThread(runnable.forget()); break; } size_t start = 0; size_t end = line.size(); line.insert(line.end(), buffer.begin(), buffer.begin() + size); while (true) { for (; end < line.size(); ++end) { if (line[end] == '\0') { break; } } if (end == line.size()) { break; } if (end > start) { nsCString message; message.Append(line.data() + start, end - start); nsCOMPtr<nsIRunnable> runnable = NewRunnableMethod<nsCString>( "nsRemoteDebuggingPipe::ReceiveMessage", this, &nsRemoteDebuggingPipe::ReceiveMessage, std::move(message)); NS_DispatchToMainThread(runnable.forget()); } ++end; start = end; } if (start != 0 && start < line.size()) { memmove(line.data(), line.data() + start, line.size() - start); } line.resize(line.size() - start); } } void nsRemoteDebuggingPipe::ReceiveMessage(const nsCString& aMessage) { MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Remote debugging pipe must be used on the Main thread."); if (mClient) { NS_ConvertUTF8toUTF16 utf16(aMessage); mClient->ReceiveMessage(utf16); } } void nsRemoteDebuggingPipe::Disconnected() { MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Remote debugging pipe must be used on the Main thread."); if (mClient) mClient->Disconnected(); } nsresult nsRemoteDebuggingPipe::SendMessage(const nsAString& aMessage) { MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Remote debugging pipe must be used on the Main thread."); if (!mClient) { return NS_ERROR_FAILURE; } NS_ConvertUTF16toUTF8 utf8(aMessage); nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableFunction( "nsRemoteDebuggingPipe::SendMessage", [message = std::move(utf8)] { const nsCString& flat = PromiseFlatCString(message); WriteBytes(flat.Data(), flat.Length()); WriteBytes("\0", 1); }); MOZ_ALWAYS_SUCCEEDS(mWriterThread->Dispatch(runnable.forget(), nsIThread::DISPATCH_NORMAL)); return NS_OK; } } // namespace mozilla
browser_patches/firefox-beta/juggler/pipe/nsRemoteDebuggingPipe.cpp
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001752275275066495, 0.00017061214020941406, 0.0001645363518036902, 0.00017079572717193514, 0.000002639922740854672 ]
{ "id": 0, "code_window": [ " return [\n", " eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 53 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { contextTest as it } from './config/browserTest'; it('should load svg favicon with prefer-color-scheme', async ({page, server, browserName, channel, headless, asset}) => { it.skip(headless && browserName !== 'firefox', 'headless browsers, except firefox, do not request favicons'); it.skip(!headless && browserName === 'webkit' && !channel, 'headed webkit does not have a favicon feature'); // Browsers aggresively cache favicons, so force bust with the // `d` parameter to make iterating on this test more predictable and isolated. const favicon = `/favicon.svg?d=${Date.now()}`; server.setRoute(favicon, (req, res) => { server.serveFile(req, res, asset('media-query-prefers-color-scheme.svg')); }); server.setRoute('/page.html', (_, res) => { res.end(` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="icon" type="image/svg+xml" href="${favicon}"> <title>SVG Favicon Test</title> </head> <body> favicons </body> </html> `); }); await Promise.all([ server.waitForRequest(favicon), page.goto(server.PREFIX + '/page.html'), ]); // Add artificial delay since, just because we saw the request for the favicon, // it does not mean the browser has processed it. There's not a great way to // hook into something like "favicon is fully displayed" event, so hopefully // 500ms is enough, but not too much! await page.waitForTimeout(500); // Text still being around ensures we haven't actually lost our browser to a crash. await page.waitForSelector('text=favicons'); });
tests/favicon.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001773599797161296, 0.00017352217400912195, 0.00017046350694727153, 0.000173161766724661, 0.0000021364198801165912 ]
{ "id": 0, "code_window": [ " return [\n", " eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)),\n", " eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)),\n", " eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 53 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { BrowserContextOptions } from '../../../..'; import { LanguageGenerator, LanguageGeneratorOptions, sanitizeDeviceOptions, toSignalMap } from './language'; import { ActionInContext } from './codeGenerator'; import { Action, actionTitle } from './recorderActions'; import { escapeWithQuotes, MouseClickOptions, toModifiers } from './utils'; import deviceDescriptors from '../../deviceDescriptors'; export class JavaScriptLanguageGenerator implements LanguageGenerator { id: string; fileName: string; highlighter = 'javascript'; private _isTest: boolean; constructor(isTest: boolean) { this.id = isTest ? 'test' : 'javascript'; this.fileName = isTest ? 'Playwright Test' : 'JavaScript'; this._isTest = isTest; } generateAction(actionInContext: ActionInContext): string { const { action, pageAlias } = actionInContext; const formatter = new JavaScriptFormatter(2); formatter.newLine(); formatter.add('// ' + actionTitle(action)); if (action.name === 'openPage') { if (this._isTest) return ''; formatter.add(`const ${pageAlias} = await context.newPage();`); if (action.url && action.url !== 'about:blank' && action.url !== 'chrome://newtab/') formatter.add(`await ${pageAlias}.goto(${quote(action.url)});`); return formatter.format(); } const subject = actionInContext.isMainFrame ? pageAlias : (actionInContext.frameName ? `${pageAlias}.frame(${formatObject({ name: actionInContext.frameName })})` : `${pageAlias}.frame(${formatObject({ url: actionInContext.frameUrl })})`); const signals = toSignalMap(action); if (signals.dialog) { formatter.add(` ${pageAlias}.once('dialog', dialog => { console.log(\`Dialog message: $\{dialog.message()}\`); dialog.dismiss().catch(() => {}); });`); } const emitPromiseAll = signals.waitForNavigation || signals.popup || signals.download; if (emitPromiseAll) { // Generate either await Promise.all([]) or // const [popup1] = await Promise.all([]). let leftHandSide = ''; if (signals.popup) leftHandSide = `const [${signals.popup.popupAlias}] = `; else if (signals.download) leftHandSide = `const [download] = `; formatter.add(`${leftHandSide}await Promise.all([`); } // Popup signals. if (signals.popup) formatter.add(`${pageAlias}.waitForEvent('popup'),`); // Navigation signal. if (signals.waitForNavigation) formatter.add(`${pageAlias}.waitForNavigation(/*{ url: ${quote(signals.waitForNavigation.url)} }*/),`); // Download signals. if (signals.download) formatter.add(`${pageAlias}.waitForEvent('download'),`); const prefix = (signals.popup || signals.waitForNavigation || signals.download) ? '' : 'await '; const actionCall = this._generateActionCall(action); const suffix = (signals.waitForNavigation || emitPromiseAll) ? '' : ';'; formatter.add(`${prefix}${subject}.${actionCall}${suffix}`); if (emitPromiseAll) { formatter.add(`]);`); } else if (signals.assertNavigation) { if (this._isTest) formatter.add(` await expect(${pageAlias}).toHaveURL(${quote(signals.assertNavigation.url)});`); else formatter.add(` // assert.equal(${pageAlias}.url(), ${quote(signals.assertNavigation.url)});`); } return formatter.format(); } private _generateActionCall(action: Action): string { switch (action.name) { case 'openPage': throw Error('Not reached'); case 'closePage': return 'close()'; case 'click': { let method = 'click'; if (action.clickCount === 2) method = 'dblclick'; const modifiers = toModifiers(action.modifiers); const options: MouseClickOptions = {}; if (action.button !== 'left') options.button = action.button; if (modifiers.length) options.modifiers = modifiers; if (action.clickCount > 2) options.clickCount = action.clickCount; const optionsString = formatOptions(options); return `${method}(${quote(action.selector)}${optionsString})`; } case 'check': return `check(${quote(action.selector)})`; case 'uncheck': return `uncheck(${quote(action.selector)})`; case 'fill': return `fill(${quote(action.selector)}, ${quote(action.text)})`; case 'setInputFiles': return `setInputFiles(${quote(action.selector)}, ${formatObject(action.files.length === 1 ? action.files[0] : action.files)})`; case 'press': { const modifiers = toModifiers(action.modifiers); const shortcut = [...modifiers, action.key].join('+'); return `press(${quote(action.selector)}, ${quote(shortcut)})`; } case 'navigate': return `goto(${quote(action.url)})`; case 'select': return `selectOption(${quote(action.selector)}, ${formatObject(action.options.length > 1 ? action.options : action.options[0])})`; } } generateHeader(options: LanguageGeneratorOptions): string { if (this._isTest) return this.generateTestHeader(options); return this.generateStandaloneHeader(options); } generateFooter(saveStorage: string | undefined): string { if (this._isTest) return this.generateTestFooter(saveStorage); return this.generateStandaloneFooter(saveStorage); } generateTestHeader(options: LanguageGeneratorOptions): string { const formatter = new JavaScriptFormatter(); const useText = formatContextOptions(options.contextOptions, options.deviceName); formatter.add(` const { test, expect${options.deviceName ? ', devices' : ''} } = require('@playwright/test'); ${useText ? '\ntest.use(' + useText + ');\n' : ''} test('test', async ({ page }) => {`); return formatter.format(); } generateTestFooter(saveStorage: string | undefined): string { return `\n});`; } generateStandaloneHeader(options: LanguageGeneratorOptions): string { const formatter = new JavaScriptFormatter(); formatter.add(` const { ${options.browserName}${options.deviceName ? ', devices' : ''} } = require('playwright'); (async () => { const browser = await ${options.browserName}.launch(${formatObjectOrVoid(options.launchOptions)}); const context = await browser.newContext(${formatContextOptions(options.contextOptions, options.deviceName)});`); return formatter.format(); } generateStandaloneFooter(saveStorage: string | undefined): string { const storageStateLine = saveStorage ? `\n await context.storageState({ path: ${quote(saveStorage)} });` : ''; return `\n // ---------------------${storageStateLine} await context.close(); await browser.close(); })();`; } } function formatOptions(value: any): string { const keys = Object.keys(value); if (!keys.length) return ''; return ', ' + formatObject(value); } function formatObject(value: any, indent = ' '): string { if (typeof value === 'string') return quote(value); if (Array.isArray(value)) return `[${value.map(o => formatObject(o)).join(', ')}]`; if (typeof value === 'object') { const keys = Object.keys(value); if (!keys.length) return '{}'; const tokens: string[] = []; for (const key of keys) tokens.push(`${key}: ${formatObject(value[key])}`); return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`; } return String(value); } function formatObjectOrVoid(value: any, indent = ' '): string { const result = formatObject(value, indent); return result === '{}' ? '' : result; } function formatContextOptions(options: BrowserContextOptions, deviceName: string | undefined): string { const device = deviceName && deviceDescriptors[deviceName]; if (!device) return formatObjectOrVoid(options); // Filter out all the properties from the device descriptor. let serializedObject = formatObjectOrVoid(sanitizeDeviceOptions(device, options)); // When there are no additional context options, we still want to spread the device inside. if (!serializedObject) serializedObject = '{\n}'; const lines = serializedObject.split('\n'); lines.splice(1, 0, `...devices[${quote(deviceName!)}],`); return lines.join('\n'); } export class JavaScriptFormatter { private _baseIndent: string; private _baseOffset: string; private _lines: string[] = []; constructor(offset = 0) { this._baseIndent = ' '.repeat(2); this._baseOffset = ' '.repeat(offset); } prepend(text: string) { this._lines = text.trim().split('\n').map(line => line.trim()).concat(this._lines); } add(text: string) { this._lines.push(...text.trim().split('\n').map(line => line.trim())); } newLine() { this._lines.push(''); } format(): string { let spaces = ''; let previousLine = ''; return this._lines.map((line: string) => { if (line === '') return line; if (line.startsWith('}') || line.startsWith(']')) spaces = spaces.substring(this._baseIndent.length); const extraSpaces = /^(for|while|if|try).*\(.*\)$/.test(previousLine) ? this._baseIndent : ''; previousLine = line; const callCarryOver = line.startsWith('.set'); line = spaces + extraSpaces + (callCarryOver ? this._baseIndent : '') + line; if (line.endsWith('{') || line.endsWith('[')) spaces += this._baseIndent; return this._baseOffset + line; }).join('\n'); } } function quote(text: string) { return escapeWithQuotes(text, '\''); }
src/server/supplements/recorder/javascript.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00035660501453094184, 0.00017830046999733895, 0.00016190942551475018, 0.0001729425130179152, 0.00003387511242181063 ]
{ "id": 1, "code_window": [ " this._page._frameManager.requestReceivedResponse(response);\n", " }\n", "\n", " _onDataReceived(event: Protocol.Network.dataReceivedPayload) {\n", " const request = this._requestIdToRequest.get(event.requestId);\n", " if (request)\n", " request.request.responseSize.encodedBodySize += event.encodedDataLength;\n", " }\n", "\n", " _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) {\n", " this._responseExtraInfoTracker.loadingFinished(event);\n", "\n", " let request = this._requestIdToRequest.get(event.requestId);\n", " if (!request)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 353 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as frames from './frames'; import * as types from './types'; import { assert } from '../utils/utils'; import { ManualPromise } from '../utils/async'; import { SdkObject } from './instrumentation'; import { NameValue } from '../common/types'; export function filterCookies(cookies: types.NetworkCookie[], urls: string[]): types.NetworkCookie[] { const parsedURLs = urls.map(s => new URL(s)); // Chromiums's cookies are missing sameSite when it is 'None' return cookies.filter(c => { // Firefox and WebKit can return cookies with empty values. if (!c.value) return false; if (!parsedURLs.length) return true; for (const parsedURL of parsedURLs) { let domain = c.domain; if (!domain.startsWith('.')) domain = '.' + domain; if (!('.' + parsedURL.hostname).endsWith(domain)) continue; if (!parsedURL.pathname.startsWith(c.path)) continue; if (parsedURL.protocol !== 'https:' && c.secure) continue; return true; } return false; }); } export function rewriteCookies(cookies: types.SetNetworkCookieParam[]): types.SetNetworkCookieParam[] { return cookies.map(c => { assert(c.name, 'Cookie should have a name'); assert(c.value, 'Cookie should have a value'); assert(c.url || (c.domain && c.path), 'Cookie should have a url or a domain/path pair'); assert(!(c.url && c.domain), 'Cookie should have either url or domain'); assert(!(c.url && c.path), 'Cookie should have either url or path'); const copy = {...c}; if (copy.url) { assert(copy.url !== 'about:blank', `Blank page can not have cookie "${c.name}"`); assert(!copy.url.startsWith('data:'), `Data URL page can not have cookie "${c.name}"`); const url = new URL(copy.url); copy.domain = url.hostname; copy.path = url.pathname.substring(0, url.pathname.lastIndexOf('/') + 1); copy.secure = url.protocol === 'https:'; } return copy; }); } export function parsedURL(url: string): URL | null { try { return new URL(url); } catch (e) { return null; } } export function stripFragmentFromUrl(url: string): string { if (!url.includes('#')) return url; return url.substring(0, url.indexOf('#')); } type ResponseSize = { encodedBodySize: number; transferSize: number; }; export class Request extends SdkObject { private _response: Response | null = null; private _redirectedFrom: Request | null; _redirectedTo: Request | null = null; readonly _documentId?: string; readonly _isFavicon: boolean; _failureText: string | null = null; private _url: string; private _resourceType: string; private _method: string; private _postData: Buffer | null; readonly _headers: types.HeadersArray; private _headersMap = new Map<string, string>(); private _frame: frames.Frame; private _waitForResponsePromise = new ManualPromise<Response | null>(); _responseEndTiming = -1; readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0 }; constructor(frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined, url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) { super(frame, 'request'); assert(!url.startsWith('data:'), 'Data urls should not fire requests'); this._frame = frame; this._redirectedFrom = redirectedFrom; if (redirectedFrom) redirectedFrom._redirectedTo = this; this._documentId = documentId; this._url = stripFragmentFromUrl(url); this._resourceType = resourceType; this._method = method; this._postData = postData; this._headers = headers; for (const { name, value } of this._headers) this._headersMap.set(name.toLowerCase(), value); this._isFavicon = url.endsWith('/favicon.ico') || !!redirectedFrom?._isFavicon; } _setFailureText(failureText: string) { this._failureText = failureText; this._waitForResponsePromise.resolve(null); } url(): string { return this._url; } resourceType(): string { return this._resourceType; } method(): string { return this._method; } postDataBuffer(): Buffer | null { return this._postData; } headers(): types.HeadersArray { return this._headers; } headerValue(name: string): string | undefined { return this._headersMap.get(name); } async rawHeaders(): Promise<NameValue[]> { return this._headers; } response(): PromiseLike<Response | null> { return this._waitForResponsePromise; } _existingResponse(): Response | null { return this._response; } _setResponse(response: Response) { this._response = response; this._waitForResponsePromise.resolve(response); } _finalRequest(): Request { return this._redirectedTo ? this._redirectedTo._finalRequest() : this; } frame(): frames.Frame { return this._frame; } isNavigationRequest(): boolean { return !!this._documentId; } redirectedFrom(): Request | null { return this._redirectedFrom; } failure(): { errorText: string } | null { if (this._failureText === null) return null; return { errorText: this._failureText }; } bodySize(): number { return this.postDataBuffer()?.length || 0; } } export class Route extends SdkObject { private readonly _request: Request; private readonly _delegate: RouteDelegate; private _handled = false; private _response: InterceptedResponse | null = null; constructor(request: Request, delegate: RouteDelegate) { super(request.frame(), 'route'); this._request = request; this._delegate = delegate; } request(): Request { return this._request; } async abort(errorCode: string = 'failed') { assert(!this._handled, 'Route is already handled!'); this._handled = true; await this._delegate.abort(errorCode); } async fulfill(overrides: { status?: number, headers?: types.HeadersArray, body?: string, isBase64?: boolean, useInterceptedResponseBody?: boolean, fetchResponseUid?: string }) { assert(!this._handled, 'Route is already handled!'); this._handled = true; let body = overrides.body; let isBase64 = overrides.isBase64 || false; if (body === undefined) { if (overrides.fetchResponseUid) { const context = this._request.frame()._page._browserContext; const buffer = context.fetchResponses.get(overrides.fetchResponseUid); assert(buffer, 'Fetch response has been disposed'); body = buffer.toString('utf8'); isBase64 = false; } else if (this._response && overrides.useInterceptedResponseBody) { body = (await this._delegate.responseBody()).toString('utf8'); isBase64 = false; } else { body = ''; isBase64 = false; } } await this._delegate.fulfill({ status: overrides.status || 200, headers: overrides.headers || [], body, isBase64, }); } async continue(overrides: types.NormalizedContinueOverrides = {}): Promise<InterceptedResponse|null> { assert(!this._handled, 'Route is already handled!'); assert(!this._response, 'Cannot call continue after response interception!'); if (overrides.url) { const newUrl = new URL(overrides.url); const oldUrl = new URL(this._request.url()); if (oldUrl.protocol !== newUrl.protocol) throw new Error('New URL must have same protocol as overridden URL'); } this._response = await this._delegate.continue(this._request, overrides); return this._response; } async responseBody(): Promise<Buffer> { assert(!this._handled, 'Route is already handled!'); return this._delegate.responseBody(); } } export type RouteHandler = (route: Route, request: Request) => void; type GetResponseBodyCallback = () => Promise<Buffer>; export type ResourceTiming = { startTime: number; domainLookupStart: number; domainLookupEnd: number; connectStart: number; secureConnectionStart: number; connectEnd: number; requestStart: number; responseStart: number; }; export type ResourceSizes = { requestBodySize: number, requestHeadersSize: number, responseBodySize: number, responseHeadersSize: number, }; export type RemoteAddr = { ipAddress: string; port: number; }; export type SecurityDetails = { protocol?: string; subjectName?: string; issuer?: string; validFrom?: number; validTo?: number; }; export class Response extends SdkObject { private _request: Request; private _contentPromise: Promise<Buffer> | null = null; _finishedPromise = new ManualPromise<void>(); private _status: number; private _statusText: string; private _url: string; private _headers: types.HeadersArray; private _headersMap = new Map<string, string>(); private _getResponseBodyCallback: GetResponseBodyCallback; private _timing: ResourceTiming; private _serverAddrPromise = new ManualPromise<RemoteAddr | undefined>(); private _securityDetailsPromise = new ManualPromise<SecurityDetails | undefined>(); private _rawRequestHeadersPromise: ManualPromise<types.HeadersArray> | undefined; private _rawResponseHeadersPromise: ManualPromise<types.HeadersArray> | undefined; private _httpVersion: string | undefined; constructor(request: Request, status: number, statusText: string, headers: types.HeadersArray, timing: ResourceTiming, getResponseBodyCallback: GetResponseBodyCallback, httpVersion?: string) { super(request.frame(), 'response'); this._request = request; this._timing = timing; this._status = status; this._statusText = statusText; this._url = request.url(); this._headers = headers; for (const { name, value } of this._headers) this._headersMap.set(name.toLowerCase(), value); this._getResponseBodyCallback = getResponseBodyCallback; this._request._setResponse(this); this._httpVersion = httpVersion; } _serverAddrFinished(addr?: RemoteAddr) { this._serverAddrPromise.resolve(addr); } _securityDetailsFinished(securityDetails?: SecurityDetails) { this._securityDetailsPromise.resolve(securityDetails); } _requestFinished(responseEndTiming: number) { this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart); this._finishedPromise.resolve(); } _setHttpVersion(httpVersion: string) { this._httpVersion = httpVersion; } url(): string { return this._url; } status(): number { return this._status; } statusText(): string { return this._statusText; } headers(): types.HeadersArray { return this._headers; } headerValue(name: string): string | undefined { return this._headersMap.get(name); } async rawRequestHeaders(): Promise<NameValue[]> { return this._rawRequestHeadersPromise || Promise.resolve(this._request._headers); } async rawResponseHeaders(): Promise<NameValue[]> { return this._rawResponseHeadersPromise || Promise.resolve(this._headers); } setWillReceiveExtraHeaders() { this._rawRequestHeadersPromise = new ManualPromise(); this._rawResponseHeadersPromise = new ManualPromise(); } setRawRequestHeaders(headers: types.HeadersArray) { if (!this._rawRequestHeadersPromise) this._rawRequestHeadersPromise = new ManualPromise(); this._rawRequestHeadersPromise!.resolve(headers); } setRawResponseHeaders(headers: types.HeadersArray) { if (!this._rawResponseHeadersPromise) this._rawResponseHeadersPromise = new ManualPromise(); this._rawResponseHeadersPromise!.resolve(headers); } timing(): ResourceTiming { return this._timing; } async serverAddr(): Promise<RemoteAddr|null> { return await this._serverAddrPromise || null; } async securityDetails(): Promise<SecurityDetails|null> { return await this._securityDetailsPromise || null; } body(): Promise<Buffer> { if (!this._contentPromise) { this._contentPromise = this._finishedPromise.then(async () => { if (this._status >= 300 && this._status <= 399) throw new Error('Response body is unavailable for redirect responses'); return this._getResponseBodyCallback(); }); } return this._contentPromise; } request(): Request { return this._request; } frame(): frames.Frame { return this._request.frame(); } httpVersion(): string { if (!this._httpVersion) return 'HTTP/1.1'; if (this._httpVersion === 'http/1.1') return 'HTTP/1.1'; return this._httpVersion; } private async _requestHeadersSize(): Promise<number> { let headersSize = 4; // 4 = 2 spaces + 2 line breaks (GET /path \r\n) headersSize += this._request.method().length; headersSize += (new URL(this.url())).pathname.length; headersSize += 8; // httpVersion const headers = this._rawRequestHeadersPromise ? await this._rawRequestHeadersPromise : this._request._headers; for (const header of headers) headersSize += header.name.length + header.value.length + 4; // 4 = ': ' + '\r\n' return headersSize; } private async _responseHeadersSize(): Promise<number> { let headersSize = 4; // 4 = 2 spaces + 2 line breaks (HTTP/1.1 200 Ok\r\n) headersSize += 8; // httpVersion; headersSize += 3; // statusCode; headersSize += this.statusText().length; const headers = await this._bestEffortResponseHeaders(); for (const header of headers) headersSize += header.name.length + header.value.length + 4; // 4 = ': ' + '\r\n' headersSize += 2; // '\r\n' return headersSize; } private async _bestEffortResponseHeaders(): Promise<types.HeadersArray> { return this._rawResponseHeadersPromise ? await this._rawResponseHeadersPromise : this._headers; } async sizes(): Promise<ResourceSizes> { await this._finishedPromise; const requestHeadersSize = await this._requestHeadersSize(); const responseHeadersSize = await this._responseHeadersSize(); let { encodedBodySize } = this._request.responseSize; if (!encodedBodySize) { const headers = await this._bestEffortResponseHeaders(); const contentLength = headers.find(h => h.name.toLowerCase() === 'content-length')?.value; encodedBodySize = contentLength ? +contentLength : 0; } return { requestBodySize: this._request.bodySize(), requestHeadersSize, responseBodySize: encodedBodySize, responseHeadersSize, }; } } export class InterceptedResponse extends SdkObject { private readonly _request: Request; private readonly _status: number; private readonly _statusText: string; private readonly _headers: types.HeadersArray; constructor(request: Request, status: number, statusText: string, headers: types.HeadersArray) { super(request.frame(), 'interceptedResponse'); this._request = request._finalRequest(); this._status = status; this._statusText = statusText; this._headers = headers; } status(): number { return this._status; } statusText(): string { return this._statusText; } headers(): types.HeadersArray { return this._headers; } request(): Request { return this._request; } } export class WebSocket extends SdkObject { private _url: string; static Events = { Close: 'close', SocketError: 'socketerror', FrameReceived: 'framereceived', FrameSent: 'framesent', }; constructor(parent: SdkObject, url: string) { super(parent, 'ws'); this._url = url; } url(): string { return this._url; } frameSent(opcode: number, data: string) { this.emit(WebSocket.Events.FrameSent, { opcode, data }); } frameReceived(opcode: number, data: string) { this.emit(WebSocket.Events.FrameReceived, { opcode, data }); } error(errorMessage: string) { this.emit(WebSocket.Events.SocketError, errorMessage); } closed() { this.emit(WebSocket.Events.Close); } } export interface RouteDelegate { abort(errorCode: string): Promise<void>; fulfill(response: types.NormalizedFulfillResponse): Promise<void>; continue(request: Request, overrides: types.NormalizedContinueOverrides): Promise<InterceptedResponse|null>; responseBody(): Promise<Buffer>; } // List taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml with extra 306 and 418 codes. export const STATUS_TEXTS: { [status: string]: string } = { '100': 'Continue', '101': 'Switching Protocols', '102': 'Processing', '103': 'Early Hints', '200': 'OK', '201': 'Created', '202': 'Accepted', '203': 'Non-Authoritative Information', '204': 'No Content', '205': 'Reset Content', '206': 'Partial Content', '207': 'Multi-Status', '208': 'Already Reported', '226': 'IM Used', '300': 'Multiple Choices', '301': 'Moved Permanently', '302': 'Found', '303': 'See Other', '304': 'Not Modified', '305': 'Use Proxy', '306': 'Switch Proxy', '307': 'Temporary Redirect', '308': 'Permanent Redirect', '400': 'Bad Request', '401': 'Unauthorized', '402': 'Payment Required', '403': 'Forbidden', '404': 'Not Found', '405': 'Method Not Allowed', '406': 'Not Acceptable', '407': 'Proxy Authentication Required', '408': 'Request Timeout', '409': 'Conflict', '410': 'Gone', '411': 'Length Required', '412': 'Precondition Failed', '413': 'Payload Too Large', '414': 'URI Too Long', '415': 'Unsupported Media Type', '416': 'Range Not Satisfiable', '417': 'Expectation Failed', '418': 'I\'m a teapot', '421': 'Misdirected Request', '422': 'Unprocessable Entity', '423': 'Locked', '424': 'Failed Dependency', '425': 'Too Early', '426': 'Upgrade Required', '428': 'Precondition Required', '429': 'Too Many Requests', '431': 'Request Header Fields Too Large', '451': 'Unavailable For Legal Reasons', '500': 'Internal Server Error', '501': 'Not Implemented', '502': 'Bad Gateway', '503': 'Service Unavailable', '504': 'Gateway Timeout', '505': 'HTTP Version Not Supported', '506': 'Variant Also Negotiates', '507': 'Insufficient Storage', '508': 'Loop Detected', '510': 'Not Extended', '511': 'Network Authentication Required', }; export function singleHeader(name: string, value: string): types.HeadersArray { return [{ name, value }]; } export function mergeHeaders(headers: (types.HeadersArray | undefined | null)[]): types.HeadersArray { const lowerCaseToValue = new Map<string, string>(); const lowerCaseToOriginalCase = new Map<string, string>(); for (const h of headers) { if (!h) continue; for (const { name, value } of h) { const lower = name.toLowerCase(); lowerCaseToOriginalCase.set(lower, name); lowerCaseToValue.set(lower, value); } } const result: types.HeadersArray = []; for (const [lower, value] of lowerCaseToValue) result.push({ name: lowerCaseToOriginalCase.get(lower)!, value }); return result; }
src/server/network.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.004608353599905968, 0.000454063672805205, 0.00016175203199964017, 0.00017122604185715318, 0.0007856822339817882 ]
{ "id": 1, "code_window": [ " this._page._frameManager.requestReceivedResponse(response);\n", " }\n", "\n", " _onDataReceived(event: Protocol.Network.dataReceivedPayload) {\n", " const request = this._requestIdToRequest.get(event.requestId);\n", " if (request)\n", " request.request.responseSize.encodedBodySize += event.encodedDataLength;\n", " }\n", "\n", " _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) {\n", " this._responseExtraInfoTracker.loadingFinished(event);\n", "\n", " let request = this._requestIdToRequest.get(event.requestId);\n", " if (!request)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 353 }
#!/bin/bash set -e set +x trap "cd $(pwd -P)" EXIT if [[ ! -z "${FF_CHECKOUT_PATH}" ]]; then cd "${FF_CHECKOUT_PATH}" echo "WARNING: checkout path from FF_CHECKOUT_PATH env: ${FF_CHECKOUT_PATH}" else cd "$(dirname "$0")" cd "../firefox/checkout" fi OBJ_FOLDER="obj-build-playwright" if [[ -d $OBJ_FOLDER ]]; then rm -rf $OBJ_FOLDER fi
browser_patches/firefox-beta/clean.sh
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001714786485536024, 0.00017060509708244354, 0.00016973154561128467, 0.00017060509708244354, 8.735514711588621e-7 ]
{ "id": 1, "code_window": [ " this._page._frameManager.requestReceivedResponse(response);\n", " }\n", "\n", " _onDataReceived(event: Protocol.Network.dataReceivedPayload) {\n", " const request = this._requestIdToRequest.get(event.requestId);\n", " if (request)\n", " request.request.responseSize.encodedBodySize += event.encodedDataLength;\n", " }\n", "\n", " _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) {\n", " this._responseExtraInfoTracker.loadingFinished(event);\n", "\n", " let request = this._requestIdToRequest.get(event.requestId);\n", " if (!request)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 353 }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import http from 'http'; import zlib from 'zlib'; import { pipeline } from 'stream'; import { contextTest as it, expect } from './config/browserTest'; import { suppressCertificateWarning } from './config/utils'; it.skip(({ mode }) => mode !== 'default'); let prevAgent: http.Agent; it.beforeAll(() => { prevAgent = http.globalAgent; http.globalAgent = new http.Agent({ // @ts-expect-error lookup: (hostname, options, callback) => { if (hostname === 'localhost' || hostname.endsWith('playwright.dev')) callback(null, '127.0.0.1', 4); else throw new Error(`Failed to resolve hostname: ${hostname}`); } }); }); it.afterAll(() => { http.globalAgent = prevAgent; }); it('should work', async ({context, server}) => { // @ts-expect-error const response = await context._fetch(server.PREFIX + '/simple.json'); expect(response.url()).toBe(server.PREFIX + '/simple.json'); expect(response.status()).toBe(200); expect(response.statusText()).toBe('OK'); expect(response.ok()).toBeTruthy(); expect(response.url()).toBe(server.PREFIX + '/simple.json'); expect(response.headers()['content-type']).toBe('application/json; charset=utf-8'); expect(response.headersArray()).toContainEqual(['Content-Type', 'application/json; charset=utf-8']); expect(await response.text()).toBe('{"foo": "bar"}\n'); }); it('should throw on network error', async ({context, server}) => { server.setRoute('/test', (req, res) => { req.socket.destroy(); }); let error; // @ts-expect-error await context._fetch(server.PREFIX + '/test').catch(e => error = e); expect(error.message).toContain('socket hang up'); }); it('should throw on network error after redirect', async ({context, server}) => { server.setRedirect('/redirect', '/test'); server.setRoute('/test', (req, res) => { req.socket.destroy(); }); let error; // @ts-expect-error await context._fetch(server.PREFIX + '/redirect').catch(e => error = e); expect(error.message).toContain('socket hang up'); }); it('should throw on network error when sending body', async ({context, server}) => { server.setRoute('/test', (req, res) => { res.writeHead(200, { 'content-length': 4096, 'content-type': 'text/html', }); res.write('<title>A'); res.uncork(); req.socket.destroy(); }); let error; // @ts-expect-error await context._fetch(server.PREFIX + '/test').catch(e => error = e); expect(error.message).toContain('Error: aborted'); }); it('should throw on network error when sending body after redirect', async ({context, server}) => { server.setRedirect('/redirect', '/test'); server.setRoute('/test', (req, res) => { res.writeHead(200, { 'content-length': 4096, 'content-type': 'text/html', }); res.write('<title>A'); res.uncork(); req.socket.destroy(); }); let error; // @ts-expect-error await context._fetch(server.PREFIX + '/redirect').catch(e => error = e); expect(error.message).toContain('Error: aborted'); }); it('should add session cookies to request', async ({context, server}) => { await context.addCookies([{ name: 'username', value: 'John Doe', domain: '.my.playwright.dev', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax', }]); const [req] = await Promise.all([ server.waitForRequest('/simple.json'), // @ts-expect-error context._fetch(`http://www.my.playwright.dev:${server.PORT}/simple.json`), ]); expect(req.headers.cookie).toEqual('username=John Doe'); }); it('should not add context cookie if cookie header passed as a parameter', async ({context, server}) => { await context.addCookies([{ name: 'username', value: 'John Doe', domain: '.my.playwright.dev', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax', }]); const [req] = await Promise.all([ server.waitForRequest('/empty.html'), // @ts-expect-error context._fetch(`http://www.my.playwright.dev:${server.PORT}/empty.html`, { headers: { 'Cookie': 'foo=bar' } }), ]); expect(req.headers.cookie).toEqual('foo=bar'); }); it('should follow redirects', async ({context, server}) => { server.setRedirect('/redirect1', '/redirect2'); server.setRedirect('/redirect2', '/simple.json'); await context.addCookies([{ name: 'username', value: 'John Doe', domain: '.my.playwright.dev', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax', }]); const [req, response] = await Promise.all([ server.waitForRequest('/simple.json'), // @ts-expect-error context._fetch(`http://www.my.playwright.dev:${server.PORT}/redirect1`), ]); expect(req.headers.cookie).toEqual('username=John Doe'); expect(response.url()).toBe(`http://www.my.playwright.dev:${server.PORT}/simple.json`); expect(await response.json()).toEqual({foo: 'bar'}); }); it('should add cookies from Set-Cookie header', async ({context, page, server}) => { server.setRoute('/setcookie.html', (req, res) => { res.setHeader('Set-Cookie', ['session=value', 'foo=bar; max-age=3600']); res.end(); }); // @ts-expect-error await context._fetch(server.PREFIX + '/setcookie.html'); const cookies = await context.cookies(); expect(new Set(cookies.map(c => ({ name: c.name, value: c.value })))).toEqual(new Set([ { name: 'session', value: 'value' }, { name: 'foo', value: 'bar' }, ])); await page.goto(server.EMPTY_PAGE); expect((await page.evaluate(() => document.cookie)).split(';').map(s => s.trim()).sort()).toEqual(['foo=bar', 'session=value']); }); it('should not lose body while handling Set-Cookie header', async ({context, page, server}) => { server.setRoute('/setcookie.html', (req, res) => { res.setHeader('Set-Cookie', ['session=value', 'foo=bar; max-age=3600']); res.end('text content'); }); // @ts-expect-error const response = await context._fetch(server.PREFIX + '/setcookie.html'); expect(await response.text()).toBe('text content'); }); it('should handle cookies on redirects', async ({context, server, browserName, isWindows}) => { server.setRoute('/redirect1', (req, res) => { res.setHeader('Set-Cookie', 'r1=v1;SameSite=Lax'); res.writeHead(301, { location: '/a/b/redirect2' }); res.end(); }); server.setRoute('/a/b/redirect2', (req, res) => { res.setHeader('Set-Cookie', 'r2=v2;SameSite=Lax'); res.writeHead(302, { location: '/title.html' }); res.end(); }); { const [req1, req2, req3] = await Promise.all([ server.waitForRequest('/redirect1'), server.waitForRequest('/a/b/redirect2'), server.waitForRequest('/title.html'), // @ts-expect-error context._fetch(`${server.PREFIX}/redirect1`), ]); expect(req1.headers.cookie).toBeFalsy(); expect(req2.headers.cookie).toBe('r1=v1'); expect(req3.headers.cookie).toBe('r1=v1'); } { const [req1, req2, req3] = await Promise.all([ server.waitForRequest('/redirect1'), server.waitForRequest('/a/b/redirect2'), server.waitForRequest('/title.html'), // @ts-expect-error context._fetch(`${server.PREFIX}/redirect1`), ]); expect(req1.headers.cookie).toBe('r1=v1'); expect(req2.headers.cookie.split(';').map(s => s.trim()).sort()).toEqual(['r1=v1', 'r2=v2']); expect(req3.headers.cookie).toBe('r1=v1'); } const cookies = await context.cookies(); expect(new Set(cookies)).toEqual(new Set([ { 'sameSite': (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', 'name': 'r2', 'value': 'v2', 'domain': 'localhost', 'path': '/a/b', 'expires': -1, 'httpOnly': false, 'secure': false }, { 'sameSite': (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', 'name': 'r1', 'value': 'v1', 'domain': 'localhost', 'path': '/', 'expires': -1, 'httpOnly': false, 'secure': false } ])); }); it('should return raw headers', async ({context, page, server}) => { server.setRoute('/headers', (req, res) => { // Headers array is only supported since Node v14.14.0 so we write directly to the socket. // res.writeHead(200, ['name-a', 'v1','name-b', 'v4','Name-a', 'v2', 'name-A', 'v3']); const conn = res.connection; conn.write('HTTP/1.1 200 OK\r\n'); conn.write('Name-A: v1\r\n'); conn.write('name-b: v4\r\n'); conn.write('Name-a: v2\r\n'); conn.write('name-A: v3\r\n'); conn.write('\r\n'); conn.uncork(); conn.end(); }); // @ts-expect-error const response = await context._fetch(`${server.PREFIX}/headers`); expect(response.status()).toBe(200); const headers = response.headersArray().filter(([name, value]) => name.toLowerCase().includes('name-')); expect(headers).toEqual([['Name-A', 'v1'], ['name-b', 'v4'], ['Name-a', 'v2'], ['name-A', 'v3']]); // Last value wins, this matches Response.headers() expect(response.headers()['name-a']).toBe('v3'); expect(response.headers()['name-b']).toBe('v4'); }); it('should work with context level proxy', async ({browserOptions, browserType, contextOptions, server, proxyServer}) => { server.setRoute('/target.html', async (req, res) => { res.end('<title>Served by the proxy</title>'); }); const browser = await browserType.launch({ ...browserOptions, proxy: { server: 'http://per-context' } }); try { proxyServer.forwardTo(server.PORT); const context = await browser.newContext({ ...contextOptions, proxy: { server: `localhost:${proxyServer.PORT}` } }); const [request, response] = await Promise.all([ server.waitForRequest('/target.html'), // @ts-expect-error context._fetch(`http://non-existent.com/target.html`) ]); expect(response.status()).toBe(200); expect(request.url).toBe('/target.html'); } finally { await browser.close(); } }); it('should pass proxy credentials', async ({browserType, browserOptions, server, proxyServer}) => { proxyServer.forwardTo(server.PORT); let auth; proxyServer.setAuthHandler(req => { auth = req.headers['proxy-authorization']; return !!auth; }); const browser = await browserType.launch({ ...browserOptions, proxy: { server: `localhost:${proxyServer.PORT}`, username: 'user', password: 'secret' } }); const context = await browser.newContext(); // @ts-expect-error const response = await context._fetch('http://non-existent.com/simple.json'); expect(proxyServer.connectHosts).toContain('non-existent.com:80'); expect(auth).toBe('Basic ' + Buffer.from('user:secret').toString('base64')); expect(await response.json()).toEqual({foo: 'bar'}); await browser.close(); }); it('should work with http credentials', async ({context, server}) => { server.setAuth('/empty.html', 'user', 'pass'); const [request, response] = await Promise.all([ server.waitForRequest('/empty.html'), // @ts-expect-error context._fetch(server.EMPTY_PAGE, { headers: { 'authorization': 'Basic ' + Buffer.from('user:pass').toString('base64') } }) ]); expect(response.status()).toBe(200); expect(request.url).toBe('/empty.html'); }); it('should work with setHTTPCredentials', async ({context, browser, server}) => { server.setAuth('/empty.html', 'user', 'pass'); // @ts-expect-error const response1 = await context._fetch(server.EMPTY_PAGE); expect(response1.status()).toBe(401); await context.setHTTPCredentials({ username: 'user', password: 'pass' }); // @ts-expect-error const response2 = await context._fetch(server.EMPTY_PAGE); expect(response2.status()).toBe(200); }); it('should return error with wrong credentials', async ({context, browser, server}) => { server.setAuth('/empty.html', 'user', 'pass'); await context.setHTTPCredentials({ username: 'user', password: 'wrong' }); // @ts-expect-error const response2 = await context._fetch(server.EMPTY_PAGE); expect(response2.status()).toBe(401); }); it('should support post data', async ({context, server}) => { const [request, response] = await Promise.all([ server.waitForRequest('/simple.json'), // @ts-expect-error context._fetch(`${server.PREFIX}/simple.json`, { method: 'POST', postData: 'My request' }) ]); expect(request.method).toBe('POST'); expect((await request.postBody).toString()).toBe('My request'); expect(response.status()).toBe(200); expect(request.url).toBe('/simple.json'); }); it('should add default headers', async ({context, server, page}) => { const [request] = await Promise.all([ server.waitForRequest('/empty.html'), // @ts-expect-error context._fetch(server.EMPTY_PAGE) ]); expect(request.headers['accept']).toBe('*/*'); const userAgent = await page.evaluate(() => navigator.userAgent); expect(request.headers['user-agent']).toBe(userAgent); expect(request.headers['accept-encoding']).toBe('gzip,deflate,br'); }); it('should add default headers to redirects', async ({context, server, page}) => { server.setRedirect('/redirect', '/empty.html'); const [request] = await Promise.all([ server.waitForRequest('/empty.html'), // @ts-expect-error context._fetch(`${server.PREFIX}/redirect`) ]); expect(request.headers['accept']).toBe('*/*'); const userAgent = await page.evaluate(() => navigator.userAgent); expect(request.headers['user-agent']).toBe(userAgent); expect(request.headers['accept-encoding']).toBe('gzip,deflate,br'); }); it('should allow to override default headers', async ({context, server, page}) => { const [request] = await Promise.all([ server.waitForRequest('/empty.html'), // @ts-expect-error context._fetch(server.EMPTY_PAGE, { headers: { 'User-Agent': 'Playwright', 'Accept': 'text/html', 'Accept-Encoding': 'br' } }) ]); expect(request.headers['accept']).toBe('text/html'); expect(request.headers['user-agent']).toBe('Playwright'); expect(request.headers['accept-encoding']).toBe('br'); }); it('should propagate custom headers with redirects', async ({context, server}) => { server.setRedirect('/a/redirect1', '/b/c/redirect2'); server.setRedirect('/b/c/redirect2', '/simple.json'); const [req1, req2, req3] = await Promise.all([ server.waitForRequest('/a/redirect1'), server.waitForRequest('/b/c/redirect2'), server.waitForRequest('/simple.json'), // @ts-expect-error context._fetch(`${server.PREFIX}/a/redirect1`, {headers: {'foo': 'bar'}}), ]); expect(req1.headers['foo']).toBe('bar'); expect(req2.headers['foo']).toBe('bar'); expect(req3.headers['foo']).toBe('bar'); }); it('should propagate extra http headers with redirects', async ({context, server}) => { server.setRedirect('/a/redirect1', '/b/c/redirect2'); server.setRedirect('/b/c/redirect2', '/simple.json'); await context.setExtraHTTPHeaders({ 'My-Secret': 'Value' }); const [req1, req2, req3] = await Promise.all([ server.waitForRequest('/a/redirect1'), server.waitForRequest('/b/c/redirect2'), server.waitForRequest('/simple.json'), // @ts-expect-error context._fetch(`${server.PREFIX}/a/redirect1`), ]); expect(req1.headers['my-secret']).toBe('Value'); expect(req2.headers['my-secret']).toBe('Value'); expect(req3.headers['my-secret']).toBe('Value'); }); it('should throw on invalid header value', async ({context, server}) => { // @ts-expect-error const error = await context._fetch(`${server.PREFIX}/a/redirect1`, { headers: { 'foo': 'недопустимое значение', } }).catch(e => e); expect(error.message).toContain('Invalid character in header content'); }); it('should throw on non-http(s) protocol', async ({context}) => { // @ts-expect-error const error1 = await context._fetch(`data:text/plain,test`).catch(e => e); expect(error1.message).toContain('Protocol "data:" not supported'); // @ts-expect-error const error2 = await context._fetch(`file:///tmp/foo`).catch(e => e); expect(error2.message).toContain('Protocol "file:" not supported'); }); it('should support https', async ({context, httpsServer}) => { const oldValue = process.env['NODE_TLS_REJECT_UNAUTHORIZED']; // https://stackoverflow.com/a/21961005/552185 process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; suppressCertificateWarning(); try { // @ts-expect-error const response = await context._fetch(httpsServer.EMPTY_PAGE); expect(response.status()).toBe(200); } finally { process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = oldValue; } }); it('should support ignoreHTTPSErrors', async ({contextFactory, contextOptions, httpsServer}) => { const context = await contextFactory({ ...contextOptions, ignoreHTTPSErrors: true }); // @ts-expect-error const response = await context._fetch(httpsServer.EMPTY_PAGE); expect(response.status()).toBe(200); }); it('should resolve url relative to baseURL', async function({server, contextFactory, contextOptions}) { const context = await contextFactory({ ...contextOptions, baseURL: server.PREFIX, }); // @ts-expect-error const response = await context._fetch('/empty.html'); expect(response.url()).toBe(server.EMPTY_PAGE); }); it('should support gzip compression', async function({context, server}) { server.setRoute('/compressed', (req, res) => { res.writeHead(200, { 'Content-Encoding': 'gzip', 'Content-Type': 'text/plain', }); const gzip = zlib.createGzip(); pipeline(gzip, res, err => { if (err) console.log(`Server error: ${err}`); }); gzip.write('Hello, world!'); gzip.end(); }); // @ts-expect-error const response = await context._fetch(server.PREFIX + '/compressed'); expect(await response.text()).toBe('Hello, world!'); }); it('should throw informatibe error on corrupted gzip body', async function({context, server}) { server.setRoute('/corrupted', (req, res) => { res.writeHead(200, { 'Content-Encoding': 'gzip', 'Content-Type': 'text/plain', }); res.write('Hello, world!'); res.end(); }); // @ts-expect-error const error = await context._fetch(server.PREFIX + '/corrupted').catch(e => e); expect(error.message).toContain(`failed to decompress 'gzip' encoding`); }); it('should support brotli compression', async function({context, server}) { server.setRoute('/compressed', (req, res) => { res.writeHead(200, { 'Content-Encoding': 'br', 'Content-Type': 'text/plain', }); const brotli = zlib.createBrotliCompress(); pipeline(brotli, res, err => { if (err) console.log(`Server error: ${err}`); }); brotli.write('Hello, world!'); brotli.end(); }); // @ts-expect-error const response = await context._fetch(server.PREFIX + '/compressed'); expect(await response.text()).toBe('Hello, world!'); }); it('should throw informatibe error on corrupted brotli body', async function({context, server}) { server.setRoute('/corrupted', (req, res) => { res.writeHead(200, { 'Content-Encoding': 'br', 'Content-Type': 'text/plain', }); res.write('Hello, world!'); res.end(); }); // @ts-expect-error const error = await context._fetch(server.PREFIX + '/corrupted').catch(e => e); expect(error.message).toContain(`failed to decompress 'br' encoding`); }); it('should support deflate compression', async function({context, server}) { server.setRoute('/compressed', (req, res) => { res.writeHead(200, { 'Content-Encoding': 'deflate', 'Content-Type': 'text/plain', }); const deflate = zlib.createDeflate(); pipeline(deflate, res, err => { if (err) console.log(`Server error: ${err}`); }); deflate.write('Hello, world!'); deflate.end(); }); // @ts-expect-error const response = await context._fetch(server.PREFIX + '/compressed'); expect(await response.text()).toBe('Hello, world!'); }); it('should throw informatibe error on corrupted deflate body', async function({context, server}) { server.setRoute('/corrupted', (req, res) => { res.writeHead(200, { 'Content-Encoding': 'deflate', 'Content-Type': 'text/plain', }); res.write('Hello, world!'); res.end(); }); // @ts-expect-error const error = await context._fetch(server.PREFIX + '/corrupted').catch(e => e); expect(error.message).toContain(`failed to decompress 'deflate' encoding`); }); it('should support timeout option', async function({context, server}) { server.setRoute('/slow', (req, res) => { res.writeHead(200, { 'content-length': 4096, 'content-type': 'text/html', }); }); // @ts-expect-error const error = await context._fetch(server.PREFIX + '/slow', { timeout: 10 }).catch(e => e); expect(error.message).toContain(`Request timed out after 10ms`); }); it('should respect timeout after redirects', async function({context, server}) { server.setRedirect('/redirect', '/slow'); server.setRoute('/slow', (req, res) => { res.writeHead(200, { 'content-length': 4096, 'content-type': 'text/html', }); }); context.setDefaultTimeout(100); // @ts-expect-error const error = await context._fetch(server.PREFIX + '/redirect').catch(e => e); expect(error.message).toContain(`Request timed out after 100ms`); }); it('should dispose', async function({context, server}) { // @ts-expect-error const response = await context._fetch(server.PREFIX + '/simple.json'); expect(await response.json()).toEqual({ foo: 'bar' }); await response.dispose(); const error = await response.body().catch(e => e); expect(error.message).toContain('Response has been disposed'); }); it('should dispose when context closes', async function({context, server}) { // @ts-expect-error const response = await context._fetch(server.PREFIX + '/simple.json'); expect(await response.json()).toEqual({ foo: 'bar' }); await context.close(); const error = await response.body().catch(e => e); expect(error.message).toContain('Target page, context or browser has been closed'); }); it('should throw on invalid first argument', async function({context, server}) { // @ts-expect-error const error = await context._fetch({}).catch(e => e); expect(error.message).toContain('First argument must be either URL string or Request'); });
tests/browsercontext-fetch.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0025414193514734507, 0.00036365821142680943, 0.00016321036673616618, 0.00017218213179148734, 0.000490957114379853 ]
{ "id": 1, "code_window": [ " this._page._frameManager.requestReceivedResponse(response);\n", " }\n", "\n", " _onDataReceived(event: Protocol.Network.dataReceivedPayload) {\n", " const request = this._requestIdToRequest.get(event.requestId);\n", " if (request)\n", " request.request.responseSize.encodedBodySize += event.encodedDataLength;\n", " }\n", "\n", " _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) {\n", " this._responseExtraInfoTracker.loadingFinished(event);\n", "\n", " let request = this._requestIdToRequest.get(event.requestId);\n", " if (!request)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 353 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import playwright from './index.js'; export const test = playwright.test; export const expect = playwright.expect; export default playwright.test;
tests/playwright-test/entry/index.mjs
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017765210941433907, 0.00017403818492311984, 0.00016929543926380575, 0.00017516706429887563, 0.000003503733978504897 ]
{ "id": 2, "code_window": [ " const response = request.request._existingResponse();\n", " if (response) {\n", " request.request.responseSize.transferSize = event.encodedDataLength;\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", " this._requestIdToRequest.delete(request._requestId);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request.request.responseSize.encodedBodySize = event.encodedDataLength - request.request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 375 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.9982030391693115, 0.03165523335337639, 0.00016485074593219906, 0.00042065640445798635, 0.16506479680538177 ]
{ "id": 2, "code_window": [ " const response = request.request._existingResponse();\n", " if (response) {\n", " request.request.responseSize.transferSize = event.encodedDataLength;\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", " this._requestIdToRequest.delete(request._requestId);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request.request.responseSize.encodedBodySize = event.encodedDataLength - request.request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 375 }
import num from './es6module.js'; window.__es6injected = num;
tests/assets/es6/es6import.js
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001733984099701047, 0.0001733984099701047, 0.0001733984099701047, 0.0001733984099701047, 0 ]
{ "id": 2, "code_window": [ " const response = request.request._existingResponse();\n", " if (response) {\n", " request.request.responseSize.transferSize = event.encodedDataLength;\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", " this._requestIdToRequest.delete(request._requestId);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request.request.responseSize.encodedBodySize = event.encodedDataLength - request.request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 375 }
{ "info" : { "author" : "xcode", "version" : 1 } }
browser_patches/webkit/embedder/Playwright/Images.xcassets/Contents.json
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017380727513227612, 0.00017380727513227612, 0.00017380727513227612, 0.00017380727513227612, 0 ]
{ "id": 2, "code_window": [ " const response = request.request._existingResponse();\n", " if (response) {\n", " request.request.responseSize.transferSize = event.encodedDataLength;\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", " this._requestIdToRequest.delete(request._requestId);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request.request.responseSize.encodedBodySize = event.encodedDataLength - request.request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 375 }
# Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile
src/server/android/driver/app/proguard-rules.pro
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017178467533085495, 0.00016951473662629724, 0.00016506496467627585, 0.00017169459897559136, 0.000003146685685351258 ]
{ "id": 3, "code_window": [ " if (response && requestExtraInfo)\n", " response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\\n'));\n", " const responseExtraInfo = info.responseReceivedExtraInfo[index];\n", " if (response && responseExtraInfo)\n", " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if (response && responseExtraInfo) {\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 679 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import fs from 'fs'; import zlib from 'zlib'; import { test as it, expect } from './pageTest'; it('should set bodySize and headersSize', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForEvent('request'), page.evaluate(() => fetch('./get', { method: 'POST', body: '12345' }).then(r => r.text())), ]); const sizes = await request.sizes(); expect(sizes.requestBodySize).toBe(5); expect(sizes.requestHeadersSize).toBeGreaterThanOrEqual(250); }); it('should set bodySize to 0 if there was no body', async ({ page, server, browserName, platform }) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForEvent('request'), page.evaluate(() => fetch('./get').then(r => r.text())), ]); const sizes = await request.sizes(); expect(sizes.requestBodySize).toBe(0); expect(sizes.requestHeadersSize).toBeGreaterThanOrEqual(200); }); it('should set bodySize, headersSize, and transferSize', async ({ page, server }) => { server.setRoute('/get', (req, res) => { // In Firefox, |fetch| will be hanging until it receives |Content-Type| header // from server. res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.end('abc134'); }); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForEvent('response'), page.evaluate(async () => fetch('./get').then(r => r.text())), server.waitForRequest('/get'), ]); const sizes = await response.request().sizes(); expect(sizes.responseBodySize).toBe(6); expect(sizes.responseHeadersSize).toBeGreaterThanOrEqual(100); }); it('should set bodySize to 0 when there was no response body', async ({ page, server }) => { const response = await page.goto(server.EMPTY_PAGE); const sizes = await response.request().sizes(); expect(sizes.responseBodySize).toBe(0); expect(sizes.responseHeadersSize).toBeGreaterThanOrEqual(150); }); it('should have the correct responseBodySize', async ({ page, server, asset, browserName }) => { const response = await page.goto(server.PREFIX + '/simplezip.json'); const sizes = await response.request().sizes(); expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size); }); it('should have the correct responseBodySize for chunked request', async ({ page, server, asset }) => { it.fixme(); const content = fs.readFileSync(asset('simplezip.json')); const AMOUNT_OF_CHUNKS = 10; const CHUNK_SIZE = Math.ceil(content.length / AMOUNT_OF_CHUNKS); server.setRoute('/chunked-simplezip.json', (req, resp) => { resp.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked' }); for (let start = 0; start < content.length; start += CHUNK_SIZE) { const end = Math.min(start + CHUNK_SIZE, content.length); resp.write(content.slice(start, end)); } resp.end(); }); const response = await page.goto(server.PREFIX + '/chunked-simplezip.json'); const sizes = await response.request().sizes(); expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size); }); it('should have the correct responseBodySize with gzip compression', async ({ page, server, asset }, testInfo) => { server.enableGzip('/simplezip.json'); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForEvent('response'), page.evaluate(() => fetch('./simplezip.json').then(r => r.text())) ]); const sizes = await response.request().sizes(); const chunks: Buffer[] = []; const gzip = fs.createReadStream(asset('simplezip.json')).pipe(zlib.createGzip()); const done = new Promise(resolve => gzip.on('end', resolve)); gzip.on('data', o => chunks.push(o)); await done; expect(sizes.responseBodySize).toBe(Buffer.concat(chunks).length); }); it('should handle redirects', async ({ page, server }) => { server.setRedirect('/foo', '/bar'); server.setRoute('/bar', (req, resp) => resp.end('bar')); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForEvent('response'), page.evaluate(async () => fetch('/foo', { method: 'POST', body: '12345', }).then(r => r.text())), ]); expect((await response.request().sizes()).requestBodySize).toBe(5); const newRequest = response.request().redirectedTo(); expect((await newRequest.sizes()).responseBodySize).toBe(3); }); it('should throw for failed requests', async ({ page, server }) => { server.setRoute('/one-style.css', (req, res) => { res.setHeader('Content-Type', 'text/css'); res.connection.destroy(); }); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForEvent('requestfailed'), page.goto(server.PREFIX + '/one-style.html') ]); await expect(request.sizes()).rejects.toThrow('Unable to fetch sizes for failed request'); }); for (const statusCode of [200, 401, 404, 500]) { it(`should work with ${statusCode} status code`, async ({ page, server }) => { server.setRoute('/foo', (req, resp) => { resp.writeHead(statusCode, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': '3', }); resp.end('bar'); }); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForEvent('response'), page.evaluate(async () => fetch('/foo', { method: 'POST', body: '12345', }).then(r => r.text())), ]); expect(response.status()).toBe(statusCode); const sizes = await response.request().sizes(); expect(sizes.requestBodySize).toBe(5); expect(sizes.responseBodySize).toBe(3); }); }
tests/page/page-network-sizes.spec.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0018400931730866432, 0.00028310352354310453, 0.00016134274483192712, 0.00017006168491207063, 0.00039300366188399494 ]
{ "id": 3, "code_window": [ " if (response && requestExtraInfo)\n", " response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\\n'));\n", " const responseExtraInfo = info.responseReceivedExtraInfo[index];\n", " if (response && responseExtraInfo)\n", " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if (response && responseExtraInfo) {\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 679 }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const {t, checkScheme} = ChromeUtils.import('chrome://juggler/content/protocol/PrimitiveTypes.js'); // Protocol-specific types. const browserTypes = {}; browserTypes.TargetInfo = { type: t.Enum(['page']), targetId: t.String, browserContextId: t.Optional(t.String), // PageId of parent tab, if any. openerId: t.Optional(t.String), }; browserTypes.CookieOptions = { name: t.String, value: t.String, url: t.Optional(t.String), domain: t.Optional(t.String), path: t.Optional(t.String), secure: t.Optional(t.Boolean), httpOnly: t.Optional(t.Boolean), sameSite: t.Optional(t.Enum(['Strict', 'Lax', 'None'])), expires: t.Optional(t.Number), }; browserTypes.Cookie = { name: t.String, domain: t.String, path: t.String, value: t.String, expires: t.Number, size: t.Number, httpOnly: t.Boolean, secure: t.Boolean, session: t.Boolean, sameSite: t.Enum(['Strict', 'Lax', 'None']), }; browserTypes.Geolocation = { latitude: t.Number, longitude: t.Number, accuracy: t.Optional(t.Number), }; browserTypes.DownloadOptions = { behavior: t.Optional(t.Enum(['saveToDisk', 'cancel'])), downloadsDir: t.Optional(t.String), }; const pageTypes = {}; pageTypes.DOMPoint = { x: t.Number, y: t.Number, }; pageTypes.Rect = { x: t.Number, y: t.Number, width: t.Number, height: t.Number, }; pageTypes.Size = { width: t.Number, height: t.Number, }; pageTypes.Viewport = { viewportSize: pageTypes.Size, deviceScaleFactor: t.Optional(t.Number), }; pageTypes.DOMQuad = { p1: pageTypes.DOMPoint, p2: pageTypes.DOMPoint, p3: pageTypes.DOMPoint, p4: pageTypes.DOMPoint, }; pageTypes.TouchPoint = { x: t.Number, y: t.Number, radiusX: t.Optional(t.Number), radiusY: t.Optional(t.Number), rotationAngle: t.Optional(t.Number), force: t.Optional(t.Number), }; pageTypes.Clip = { x: t.Number, y: t.Number, width: t.Number, height: t.Number, }; const runtimeTypes = {}; runtimeTypes.RemoteObject = { type: t.Optional(t.Enum(['object', 'function', 'undefined', 'string', 'number', 'boolean', 'symbol', 'bigint'])), subtype: t.Optional(t.Enum(['array', 'null', 'node', 'regexp', 'date', 'map', 'set', 'weakmap', 'weakset', 'error', 'proxy', 'promise', 'typedarray'])), objectId: t.Optional(t.String), unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])), value: t.Any }; runtimeTypes.ObjectProperty = { name: t.String, value: runtimeTypes.RemoteObject, }; runtimeTypes.ScriptLocation = { columnNumber: t.Number, lineNumber: t.Number, url: t.String, }; runtimeTypes.ExceptionDetails = { text: t.Optional(t.String), stack: t.Optional(t.String), value: t.Optional(t.Any), }; runtimeTypes.CallFunctionArgument = { objectId: t.Optional(t.String), unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])), value: t.Any, }; runtimeTypes.AuxData = { frameId: t.Optional(t.String), name: t.Optional(t.String), }; const axTypes = {}; axTypes.AXTree = { role: t.String, name: t.String, children: t.Optional(t.Array(t.Recursive(axTypes, 'AXTree'))), selected: t.Optional(t.Boolean), focused: t.Optional(t.Boolean), pressed: t.Optional(t.Boolean), focusable: t.Optional(t.Boolean), haspopup: t.Optional(t.Boolean), required: t.Optional(t.Boolean), invalid: t.Optional(t.Boolean), modal: t.Optional(t.Boolean), editable: t.Optional(t.Boolean), busy: t.Optional(t.Boolean), multiline: t.Optional(t.Boolean), readonly: t.Optional(t.Boolean), checked: t.Optional(t.Enum(['mixed', true])), expanded: t.Optional(t.Boolean), disabled: t.Optional(t.Boolean), multiselectable: t.Optional(t.Boolean), value: t.Optional(t.String), description: t.Optional(t.String), roledescription: t.Optional(t.String), valuetext: t.Optional(t.String), orientation: t.Optional(t.String), autocomplete: t.Optional(t.String), keyshortcuts: t.Optional(t.String), level: t.Optional(t.Number), tag: t.Optional(t.String), foundObject: t.Optional(t.Boolean), } const networkTypes = {}; networkTypes.HTTPHeader = { name: t.String, value: t.String, }; networkTypes.HTTPCredentials = { username: t.String, password: t.String, }; networkTypes.SecurityDetails = { protocol: t.String, subjectName: t.String, issuer: t.String, validFrom: t.Number, validTo: t.Number, }; networkTypes.ResourceTiming = { startTime: t.Number, domainLookupStart: t.Number, domainLookupEnd: t.Number, connectStart: t.Number, secureConnectionStart: t.Number, connectEnd: t.Number, requestStart: t.Number, responseStart: t.Number, }; networkTypes.InterceptedResponse = { status: t.Number, statusText: t.String, headers: t.Array(networkTypes.HTTPHeader), }; const Browser = { targets: ['browser'], types: browserTypes, events: { 'attachedToTarget': { sessionId: t.String, targetInfo: browserTypes.TargetInfo, }, 'detachedFromTarget': { sessionId: t.String, targetId: t.String, }, 'downloadCreated': { uuid: t.String, browserContextId: t.Optional(t.String), pageTargetId: t.String, url: t.String, suggestedFileName: t.String, }, 'downloadFinished': { uuid: t.String, canceled: t.Optional(t.Boolean), error: t.Optional(t.String), }, 'videoRecordingFinished': { screencastId: t.String, }, }, methods: { 'enable': { params: { attachToDefaultContext: t.Boolean, }, }, 'createBrowserContext': { params: { removeOnDetach: t.Optional(t.Boolean), }, returns: { browserContextId: t.String, }, }, 'removeBrowserContext': { params: { browserContextId: t.String, }, }, 'newPage': { params: { browserContextId: t.Optional(t.String), }, returns: { targetId: t.String, } }, 'close': {}, 'getInfo': { returns: { userAgent: t.String, version: t.String, }, }, 'setExtraHTTPHeaders': { params: { browserContextId: t.Optional(t.String), headers: t.Array(networkTypes.HTTPHeader), }, }, 'setBrowserProxy': { params: { type: t.Enum(['http', 'https', 'socks', 'socks4']), bypass: t.Array(t.String), host: t.String, port: t.Number, username: t.Optional(t.String), password: t.Optional(t.String), }, }, 'setContextProxy': { params: { browserContextId: t.Optional(t.String), type: t.Enum(['http', 'https', 'socks', 'socks4']), bypass: t.Array(t.String), host: t.String, port: t.Number, username: t.Optional(t.String), password: t.Optional(t.String), }, }, 'setHTTPCredentials': { params: { browserContextId: t.Optional(t.String), credentials: t.Nullable(networkTypes.HTTPCredentials), }, }, 'setRequestInterception': { params: { browserContextId: t.Optional(t.String), enabled: t.Boolean, }, }, 'setGeolocationOverride': { params: { browserContextId: t.Optional(t.String), geolocation: t.Nullable(browserTypes.Geolocation), } }, 'setUserAgentOverride': { params: { browserContextId: t.Optional(t.String), userAgent: t.Nullable(t.String), } }, 'setPlatformOverride': { params: { browserContextId: t.Optional(t.String), platform: t.Nullable(t.String), } }, 'setBypassCSP': { params: { browserContextId: t.Optional(t.String), bypassCSP: t.Nullable(t.Boolean), } }, 'setIgnoreHTTPSErrors': { params: { browserContextId: t.Optional(t.String), ignoreHTTPSErrors: t.Nullable(t.Boolean), } }, 'setJavaScriptDisabled': { params: { browserContextId: t.Optional(t.String), javaScriptDisabled: t.Boolean, } }, 'setLocaleOverride': { params: { browserContextId: t.Optional(t.String), locale: t.Nullable(t.String), } }, 'setTimezoneOverride': { params: { browserContextId: t.Optional(t.String), timezoneId: t.Nullable(t.String), } }, 'setDownloadOptions': { params: { browserContextId: t.Optional(t.String), downloadOptions: t.Nullable(browserTypes.DownloadOptions), } }, 'setTouchOverride': { params: { browserContextId: t.Optional(t.String), hasTouch: t.Nullable(t.Boolean), } }, 'setDefaultViewport': { params: { browserContextId: t.Optional(t.String), viewport: t.Nullable(pageTypes.Viewport), } }, 'setScrollbarsHidden': { params: { browserContextId: t.Optional(t.String), hidden: t.Boolean, } }, 'addScriptToEvaluateOnNewDocument': { params: { browserContextId: t.Optional(t.String), script: t.String, } }, 'addBinding': { params: { browserContextId: t.Optional(t.String), worldName: t.Optional(t.String), name: t.String, script: t.String, }, }, 'grantPermissions': { params: { origin: t.String, browserContextId: t.Optional(t.String), permissions: t.Array(t.String), }, }, 'resetPermissions': { params: { browserContextId: t.Optional(t.String), } }, 'setCookies': { params: { browserContextId: t.Optional(t.String), cookies: t.Array(browserTypes.CookieOptions), } }, 'clearCookies': { params: { browserContextId: t.Optional(t.String), } }, 'getCookies': { params: { browserContextId: t.Optional(t.String) }, returns: { cookies: t.Array(browserTypes.Cookie), }, }, 'setOnlineOverride': { params: { browserContextId: t.Optional(t.String), override: t.Nullable(t.Enum(['online', 'offline'])), } }, 'setColorScheme': { params: { browserContextId: t.Optional(t.String), colorScheme: t.Nullable(t.Enum(['dark', 'light', 'no-preference'])), }, }, 'setReducedMotion': { params: { browserContextId: t.Optional(t.String), reducedMotion: t.Nullable(t.Enum(['reduce', 'no-preference'])), }, }, 'setForcedColors': { params: { browserContextId: t.Optional(t.String), forcedColors: t.Nullable(t.Enum(['active', 'none'])), }, }, 'setVideoRecordingOptions': { params: { browserContextId: t.Optional(t.String), options: t.Optional({ dir: t.String, width: t.Number, height: t.Number, }), }, }, 'cancelDownload': { params: { uuid: t.Optional(t.String), } } }, }; const Network = { targets: ['page'], types: networkTypes, events: { 'requestWillBeSent': { // frameId may be absent for redirected requests. frameId: t.Optional(t.String), requestId: t.String, // RequestID of redirected request. redirectedFrom: t.Optional(t.String), postData: t.Optional(t.String), headers: t.Array(networkTypes.HTTPHeader), isIntercepted: t.Boolean, url: t.String, method: t.String, navigationId: t.Optional(t.String), cause: t.String, internalCause: t.String, }, 'responseReceived': { securityDetails: t.Nullable(networkTypes.SecurityDetails), requestId: t.String, fromCache: t.Boolean, remoteIPAddress: t.Optional(t.String), remotePort: t.Optional(t.Number), status: t.Number, statusText: t.String, headers: t.Array(networkTypes.HTTPHeader), timing: networkTypes.ResourceTiming, }, 'requestFinished': { requestId: t.String, responseEndTime: t.Number, transferSize: t.Number, encodedBodySize: t.Number, protocolVersion: t.String, }, 'requestFailed': { requestId: t.String, errorCode: t.String, }, }, methods: { 'setRequestInterception': { params: { enabled: t.Boolean, }, }, 'setExtraHTTPHeaders': { params: { headers: t.Array(networkTypes.HTTPHeader), }, }, 'abortInterceptedRequest': { params: { requestId: t.String, errorCode: t.String, }, }, 'resumeInterceptedRequest': { params: { requestId: t.String, url: t.Optional(t.String), method: t.Optional(t.String), headers: t.Optional(t.Array(networkTypes.HTTPHeader)), postData: t.Optional(t.String), interceptResponse: t.Optional(t.Boolean), }, returns: { response: t.Optional(networkTypes.InterceptedResponse), error: t.Optional(t.String), }, }, 'fulfillInterceptedRequest': { params: { requestId: t.String, status: t.Number, statusText: t.String, headers: t.Array(networkTypes.HTTPHeader), base64body: t.Optional(t.String), // base64-encoded }, }, 'getResponseBody': { params: { requestId: t.String, }, returns: { base64body: t.String, evicted: t.Optional(t.Boolean), }, }, }, }; const Runtime = { targets: ['page'], types: runtimeTypes, events: { 'executionContextCreated': { executionContextId: t.String, auxData: runtimeTypes.AuxData, }, 'executionContextDestroyed': { executionContextId: t.String, }, 'console': { executionContextId: t.String, args: t.Array(runtimeTypes.RemoteObject), type: t.String, location: runtimeTypes.ScriptLocation, }, }, methods: { 'evaluate': { params: { // Pass frameId here. executionContextId: t.String, expression: t.String, returnByValue: t.Optional(t.Boolean), }, returns: { result: t.Optional(runtimeTypes.RemoteObject), exceptionDetails: t.Optional(runtimeTypes.ExceptionDetails), } }, 'callFunction': { params: { // Pass frameId here. executionContextId: t.String, functionDeclaration: t.String, returnByValue: t.Optional(t.Boolean), args: t.Array(runtimeTypes.CallFunctionArgument), }, returns: { result: t.Optional(runtimeTypes.RemoteObject), exceptionDetails: t.Optional(runtimeTypes.ExceptionDetails), } }, 'disposeObject': { params: { executionContextId: t.String, objectId: t.String, }, }, 'getObjectProperties': { params: { executionContextId: t.String, objectId: t.String, }, returns: { properties: t.Array(runtimeTypes.ObjectProperty), } }, }, }; const Page = { targets: ['page'], types: pageTypes, events: { 'ready': { }, 'crashed': { }, 'eventFired': { frameId: t.String, name: t.Enum(['load', 'DOMContentLoaded']), }, 'uncaughtError': { frameId: t.String, message: t.String, stack: t.String, }, 'frameAttached': { frameId: t.String, parentFrameId: t.Optional(t.String), }, 'frameDetached': { frameId: t.String, }, 'navigationStarted': { frameId: t.String, navigationId: t.String, url: t.String, }, 'navigationCommitted': { frameId: t.String, // |navigationId| can only be null in response to enable. navigationId: t.Optional(t.String), url: t.String, // frame.id or frame.name name: t.String, }, 'navigationAborted': { frameId: t.String, navigationId: t.String, errorText: t.String, }, 'sameDocumentNavigation': { frameId: t.String, url: t.String, }, 'dialogOpened': { dialogId: t.String, type: t.Enum(['prompt', 'alert', 'confirm', 'beforeunload']), message: t.String, defaultValue: t.Optional(t.String), }, 'dialogClosed': { dialogId: t.String, }, 'bindingCalled': { executionContextId: t.String, name: t.String, payload: t.Any, }, 'linkClicked': { phase: t.Enum(['before', 'after']), }, 'willOpenNewWindowAsynchronously': {}, 'fileChooserOpened': { executionContextId: t.String, element: runtimeTypes.RemoteObject }, 'workerCreated': { workerId: t.String, frameId: t.String, url: t.String, }, 'workerDestroyed': { workerId: t.String, }, 'dispatchMessageFromWorker': { workerId: t.String, message: t.String, }, 'videoRecordingStarted': { screencastId: t.String, file: t.String, }, 'webSocketCreated': { frameId: t.String, wsid: t.String, requestURL: t.String, }, 'webSocketOpened': { frameId: t.String, requestId: t.String, wsid: t.String, effectiveURL: t.String, }, 'webSocketClosed': { frameId: t.String, wsid: t.String, error: t.String, }, 'webSocketFrameSent': { frameId: t.String, wsid: t.String, opcode: t.Number, data: t.String, }, 'webSocketFrameReceived': { frameId: t.String, wsid: t.String, opcode: t.Number, data: t.String, }, 'screencastFrame': { data: t.String, deviceWidth: t.Number, deviceHeight: t.Number, }, }, methods: { 'close': { params: { runBeforeUnload: t.Optional(t.Boolean), }, }, 'setFileInputFiles': { params: { frameId: t.String, objectId: t.String, files: t.Array(t.String), }, }, 'addBinding': { params: { worldName: t.Optional(t.String), name: t.String, script: t.String, }, }, 'setViewportSize': { params: { viewportSize: t.Nullable(pageTypes.Size), }, }, 'bringToFront': { params: { }, }, 'setEmulatedMedia': { params: { type: t.Optional(t.Enum(['screen', 'print', ''])), colorScheme: t.Optional(t.Enum(['dark', 'light', 'no-preference'])), reducedMotion: t.Optional(t.Enum(['reduce', 'no-preference'])), forcedColors: t.Optional(t.Enum(['active', 'none'])), }, }, 'setCacheDisabled': { params: { cacheDisabled: t.Boolean, }, }, 'describeNode': { params: { frameId: t.String, objectId: t.String, }, returns: { contentFrameId: t.Optional(t.String), ownerFrameId: t.Optional(t.String), }, }, 'scrollIntoViewIfNeeded': { params: { frameId: t.String, objectId: t.String, rect: t.Optional(pageTypes.Rect), }, }, 'addScriptToEvaluateOnNewDocument': { params: { script: t.String, worldName: t.Optional(t.String), } }, 'navigate': { params: { frameId: t.String, url: t.String, referer: t.Optional(t.String), }, returns: { navigationId: t.Nullable(t.String), navigationURL: t.Nullable(t.String), } }, 'goBack': { params: { frameId: t.String, }, returns: { success: t.Boolean, }, }, 'goForward': { params: { frameId: t.String, }, returns: { success: t.Boolean, }, }, 'reload': { params: { frameId: t.String, }, }, 'adoptNode': { params: { frameId: t.String, objectId: t.String, executionContextId: t.String, }, returns: { remoteObject: t.Nullable(runtimeTypes.RemoteObject), }, }, 'screenshot': { params: { mimeType: t.Enum(['image/png', 'image/jpeg']), clip: t.Optional(pageTypes.Clip), omitDeviceScaleFactor: t.Optional(t.Boolean), }, returns: { data: t.String, } }, 'getContentQuads': { params: { frameId: t.String, objectId: t.String, }, returns: { quads: t.Array(pageTypes.DOMQuad), }, }, 'dispatchKeyEvent': { params: { type: t.String, key: t.String, keyCode: t.Number, location: t.Number, code: t.String, repeat: t.Boolean, text: t.Optional(t.String), } }, 'dispatchTouchEvent': { params: { type: t.Enum(['touchStart', 'touchEnd', 'touchMove', 'touchCancel']), touchPoints: t.Array(pageTypes.TouchPoint), modifiers: t.Number, }, returns: { defaultPrevented: t.Boolean, } }, 'dispatchTapEvent': { params: { x: t.Number, y: t.Number, modifiers: t.Number, } }, 'dispatchMouseEvent': { params: { type: t.String, button: t.Number, x: t.Number, y: t.Number, modifiers: t.Number, clickCount: t.Optional(t.Number), buttons: t.Number, } }, 'dispatchWheelEvent': { params: { x: t.Number, y: t.Number, deltaX: t.Number, deltaY: t.Number, deltaZ: t.Number, modifiers: t.Number, } }, 'insertText': { params: { text: t.String, } }, 'crash': { params: {} }, 'handleDialog': { params: { dialogId: t.String, accept: t.Boolean, promptText: t.Optional(t.String), }, }, 'setInterceptFileChooserDialog': { params: { enabled: t.Boolean, }, }, 'sendMessageToWorker': { params: { frameId: t.String, workerId: t.String, message: t.String, }, }, 'startScreencast': { params: { width: t.Number, height: t.Number, quality: t.Number, }, returns: { screencastId: t.String, }, }, 'screencastFrameAck': { params: { screencastId: t.String, }, }, 'stopScreencast': { }, }, }; const Accessibility = { targets: ['page'], types: axTypes, events: {}, methods: { 'getFullAXTree': { params: { objectId: t.Optional(t.String), }, returns: { tree: axTypes.AXTree }, } } } this.protocol = { domains: {Browser, Page, Runtime, Network, Accessibility}, }; this.checkScheme = checkScheme; this.EXPORTED_SYMBOLS = ['protocol', 'checkScheme'];
browser_patches/firefox-beta/juggler/protocol/Protocol.js
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.004751861095428467, 0.00022866639483254403, 0.0001663887087488547, 0.0001749262009980157, 0.0004566284769680351 ]
{ "id": 3, "code_window": [ " if (response && requestExtraInfo)\n", " response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\\n'));\n", " const responseExtraInfo = info.responseReceivedExtraInfo[index];\n", " if (response && responseExtraInfo)\n", " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if (response && responseExtraInfo) {\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 679 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import net from 'net'; import { assert } from './utils'; // https://tools.ietf.org/html/rfc1928 enum SocksAuth { NO_AUTHENTICATION_REQUIRED = 0x00, GSSAPI = 0x01, USERNAME_PASSWORD = 0x02, NO_ACCEPTABLE_METHODS = 0xFF } enum SocksAddressType { IPv4 = 0x01, FqName = 0x03, IPv6 = 0x04 } enum SocksCommand { CONNECT = 0x01, BIND = 0x02, UDP_ASSOCIATE = 0x03 } enum SocksReply { Succeeded = 0x00, GeneralServerFailure = 0x01, NotAllowedByRuleSet = 0x02, NetworkUnreachable = 0x03, HostUnreachable = 0x04, ConnectionRefused = 0x05, TtlExpired = 0x06, CommandNotSupported = 0x07, AddressTypeNotSupported = 0x08 } export interface SocksConnectionClient { onSocketRequested(uid: string, host: string, port: number): void; onSocketData(uid: string, data: Buffer): void; onSocketClosed(uid: string): void; } export class SocksConnection { private _buffer = Buffer.from([]); private _offset = 0; private _fence = 0; private _fenceCallback: (() => void) | undefined; private _socket: net.Socket; private _boundOnData: (buffer: Buffer) => void; private _uid: string; private _client: SocksConnectionClient; constructor(uid: string, socket: net.Socket, client: SocksConnectionClient) { this._uid = uid; this._socket = socket; this._client = client; this._boundOnData = this._onData.bind(this); socket.on('data', this._boundOnData); socket.on('close', () => this._onClose()); socket.on('end', () => this._onClose()); socket.on('error', () => this._onClose()); this._run().catch(() => this._socket.end()); } async _run() { assert(await this._authenticate()); const { command, host, port } = await this._parseRequest(); if (command !== SocksCommand.CONNECT) { this._writeBytes(Buffer.from([ 0x05, SocksReply.CommandNotSupported, 0x00, // RSV 0x01, // IPv4 0x00, 0x00, 0x00, 0x00, // Address 0x00, 0x00 // Port ])); return; } this._socket.off('data', this._boundOnData); this._client.onSocketRequested(this._uid, host, port); } async _authenticate(): Promise<boolean> { // Request: // +----+----------+----------+ // |VER | NMETHODS | METHODS | // +----+----------+----------+ // | 1 | 1 | 1 to 255 | // +----+----------+----------+ // Response: // +----+--------+ // |VER | METHOD | // +----+--------+ // | 1 | 1 | // +----+--------+ const version = await this._readByte(); assert(version === 0x05, 'The VER field must be set to x05 for this version of the protocol, was ' + version); const nMethods = await this._readByte(); assert(nMethods, 'No authentication methods specified'); const methods = await this._readBytes(nMethods); for (const method of methods) { if (method === 0) { this._writeBytes(Buffer.from([version, method])); return true; } } this._writeBytes(Buffer.from([version, SocksAuth.NO_ACCEPTABLE_METHODS])); return false; } async _parseRequest(): Promise<{ host: string, port: number, command: SocksCommand }> { // Request. // +----+-----+-------+------+----------+----------+ // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ // Response. // +----+-----+-------+------+----------+----------+ // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ const version = await this._readByte(); assert(version === 0x05, 'The VER field must be set to x05 for this version of the protocol, was ' + version); const command = await this._readByte(); await this._readByte(); // skip reserved. const addressType = await this._readByte(); let host = ''; switch (addressType) { case SocksAddressType.IPv4: host = (await this._readBytes(4)).join('.'); break; case SocksAddressType.FqName: const length = await this._readByte(); host = (await this._readBytes(length)).toString(); break; case SocksAddressType.IPv6: const bytes = await this._readBytes(16); const tokens = []; for (let i = 0; i < 8; ++i) tokens.push(bytes.readUInt16BE(i * 2)); host = tokens.join(':'); break; } const port = (await this._readBytes(2)).readUInt16BE(0); this._buffer = Buffer.from([]); this._offset = 0; this._fence = 0; return { command, host, port }; } private async _readByte(): Promise<number> { const buffer = await this._readBytes(1); return buffer[0]; } private async _readBytes(length: number): Promise<Buffer> { this._fence = this._offset + length; if (!this._buffer || this._buffer.length < this._fence) await new Promise<void>(f => this._fenceCallback = f); this._offset += length; return this._buffer.slice(this._offset - length, this._offset); } private _writeBytes(buffer: Buffer) { if (this._socket.writable) this._socket.write(buffer); } private _onClose() { this._client.onSocketClosed(this._uid); } private _onData(buffer: Buffer) { this._buffer = Buffer.concat([this._buffer, buffer]); if (this._fenceCallback && this._buffer.length >= this._fence) { const callback = this._fenceCallback; this._fenceCallback = undefined; callback(); } } socketConnected(host: string, port: number) { this._writeBytes(Buffer.from([ 0x05, SocksReply.Succeeded, 0x00, // RSV 0x01, // IPv4 ...parseIP(host), // Address port << 8, port & 0xFF // Port ])); this._socket.on('data', data => this._client.onSocketData(this._uid, data)); } socketFailed(errorCode: string) { const buffer = Buffer.from([ 0x05, 0, 0x00, // RSV 0x01, // IPv4 ...parseIP('0.0.0.0'), // Address 0, 0 // Port ]); switch (errorCode) { case 'ENOENT': case 'ENOTFOUND': case 'ETIMEDOUT': case 'EHOSTUNREACH': buffer[1] = SocksReply.HostUnreachable; break; case 'ENETUNREACH': buffer[1] = SocksReply.NetworkUnreachable; break; case 'ECONNREFUSED': buffer[1] = SocksReply.ConnectionRefused; break; } this._writeBytes(buffer); this._socket.end(); } sendData(data: Buffer) { this._socket.write(data); } end() { this._socket.end(); } error(error: string) { this._socket.destroy(new Error(error)); } } function parseIP(address: string): number[] { if (!net.isIPv4(address)) throw new Error('IPv6 is not supported'); return address.split('.', 4).map(t => +t); }
src/utils/socksProxy.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001793165283743292, 0.00017136315000243485, 0.00016226767911575735, 0.00017153029330074787, 0.000003490950120976777 ]
{ "id": 3, "code_window": [ " if (response && requestExtraInfo)\n", " response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\\n'));\n", " const responseExtraInfo = info.responseReceivedExtraInfo[index];\n", " if (response && responseExtraInfo)\n", " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if (response && responseExtraInfo) {\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "replace", "edit_start_line_idx": 679 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { NodeSnapshot } from './snapshotTypes'; export type SnapshotData = { doctype?: string, html: NodeSnapshot, resourceOverrides: { url: string, // String is the content. Number is "x snapshots ago", same url. content: string | number, contentType: 'text/css' }[], viewport: { width: number, height: number }, url: string, timestamp: number, collectionTime: number, }; export function frameSnapshotStreamer(snapshotStreamer: string) { // Communication with Playwright. if ((window as any)[snapshotStreamer]) return; // Attributes present in the snapshot. const kShadowAttribute = '__playwright_shadow_root_'; const kScrollTopAttribute = '__playwright_scroll_top_'; const kScrollLeftAttribute = '__playwright_scroll_left_'; const kStyleSheetAttribute = '__playwright_style_sheet_'; const kBlobUrlPrefix = 'http://playwright.bloburl/#'; // Symbols for our own info on Nodes/StyleSheets. const kSnapshotFrameId = Symbol('__playwright_snapshot_frameid_'); const kCachedData = Symbol('__playwright_snapshot_cache_'); const kEndOfList = Symbol('__playwright_end_of_list_'); type CachedData = { cached?: any[], // Cached values to determine whether the snapshot will be the same. ref?: [number, number], // Previous snapshotNumber and nodeIndex. attributesCached?: boolean, // Whether node attributes have not changed. cssText?: string, // Text for stylesheets. cssRef?: number, // Previous snapshotNumber for overridden stylesheets. }; function resetCachedData(obj: any) { delete obj[kCachedData]; } function ensureCachedData(obj: any): CachedData { if (!obj[kCachedData]) obj[kCachedData] = {}; return obj[kCachedData]; } function removeHash(url: string) { try { const u = new URL(url); u.hash = ''; return u.toString(); } catch (e) { return url; } } class Streamer { private _removeNoScript = true; private _lastSnapshotNumber = 0; private _staleStyleSheets = new Set<CSSStyleSheet>(); private _readingStyleSheet = false; // To avoid invalidating due to our own reads. private _fakeBase: HTMLBaseElement; private _observer: MutationObserver; constructor() { this._interceptNativeMethod(window.CSSStyleSheet.prototype, 'insertRule', (sheet: CSSStyleSheet) => this._invalidateStyleSheet(sheet)); this._interceptNativeMethod(window.CSSStyleSheet.prototype, 'deleteRule', (sheet: CSSStyleSheet) => this._invalidateStyleSheet(sheet)); this._interceptNativeMethod(window.CSSStyleSheet.prototype, 'addRule', (sheet: CSSStyleSheet) => this._invalidateStyleSheet(sheet)); this._interceptNativeMethod(window.CSSStyleSheet.prototype, 'removeRule', (sheet: CSSStyleSheet) => this._invalidateStyleSheet(sheet)); this._interceptNativeGetter(window.CSSStyleSheet.prototype, 'rules', (sheet: CSSStyleSheet) => this._invalidateStyleSheet(sheet)); this._interceptNativeGetter(window.CSSStyleSheet.prototype, 'cssRules', (sheet: CSSStyleSheet) => this._invalidateStyleSheet(sheet)); this._fakeBase = document.createElement('base'); this._observer = new MutationObserver(list => this._handleMutations(list)); const observerConfig = { attributes: true, subtree: true }; this._observer.observe(document, observerConfig); } private _interceptNativeMethod(obj: any, method: string, cb: (thisObj: any, result: any) => void) { const native = obj[method] as Function; if (!native) return; obj[method] = function(...args: any[]) { const result = native.call(this, ...args); cb(this, result); return result; }; } private _interceptNativeGetter(obj: any, prop: string, cb: (thisObj: any, result: any) => void) { const descriptor = Object.getOwnPropertyDescriptor(obj, prop)!; Object.defineProperty(obj, prop, { ...descriptor, get: function() { const result = descriptor.get!.call(this); cb(this, result); return result; }, }); } private _handleMutations(list: MutationRecord[]) { for (const mutation of list) ensureCachedData(mutation.target).attributesCached = undefined; } private _invalidateStyleSheet(sheet: CSSStyleSheet) { if (this._readingStyleSheet) return; this._staleStyleSheets.add(sheet); } private _updateStyleElementStyleSheetTextIfNeeded(sheet: CSSStyleSheet): string | undefined { const data = ensureCachedData(sheet); if (this._staleStyleSheets.has(sheet)) { this._staleStyleSheets.delete(sheet); try { data.cssText = this._getSheetText(sheet); } catch (e) { // Sometimes we cannot access cross-origin stylesheets. } } return data.cssText; } // Returns either content, ref, or no override. private _updateLinkStyleSheetTextIfNeeded(sheet: CSSStyleSheet, snapshotNumber: number): string | number | undefined { const data = ensureCachedData(sheet); if (this._staleStyleSheets.has(sheet)) { this._staleStyleSheets.delete(sheet); try { data.cssText = this._getSheetText(sheet); data.cssRef = snapshotNumber; return data.cssText; } catch (e) { // Sometimes we cannot access cross-origin stylesheets. } } return data.cssRef === undefined ? undefined : snapshotNumber - data.cssRef; } markIframe(iframeElement: HTMLIFrameElement | HTMLFrameElement, frameId: string) { (iframeElement as any)[kSnapshotFrameId] = frameId; } reset() { this._staleStyleSheets.clear(); const visitNode = (node: Node | ShadowRoot) => { resetCachedData(node); if (node.nodeType === Node.ELEMENT_NODE) { const element = node as Element; if (element.shadowRoot) visitNode(element.shadowRoot); } for (let child = node.firstChild; child; child = child.nextSibling) visitNode(child); }; visitNode(document.documentElement); visitNode(this._fakeBase); } private _sanitizeUrl(url: string): string { if (url.startsWith('javascript:')) return ''; // Rewrite blob urls so that Service Worker can intercept them. if (url.startsWith('blob:')) return kBlobUrlPrefix + url; return url; } private _sanitizeSrcSet(srcset: string): string { return srcset.split(',').map(src => { src = src.trim(); const spaceIndex = src.lastIndexOf(' '); if (spaceIndex === -1) return this._sanitizeUrl(src); return this._sanitizeUrl(src.substring(0, spaceIndex).trim()) + src.substring(spaceIndex); }).join(', '); } private _resolveUrl(base: string, url: string): string { if (url === '') return ''; try { return new URL(url, base).href; } catch (e) { return url; } } private _getSheetBase(sheet: CSSStyleSheet): string { let rootSheet = sheet; while (rootSheet.parentStyleSheet) rootSheet = rootSheet.parentStyleSheet; if (rootSheet.ownerNode) return rootSheet.ownerNode.baseURI; return document.baseURI; } private _getSheetText(sheet: CSSStyleSheet): string { this._readingStyleSheet = true; try { const rules: string[] = []; for (const rule of sheet.cssRules) rules.push(rule.cssText); return rules.join('\n'); } finally { this._readingStyleSheet = false; } } captureSnapshot(): SnapshotData | undefined { const timestamp = performance.now(); const snapshotNumber = ++this._lastSnapshotNumber; let nodeCounter = 0; let shadowDomNesting = 0; // Ensure we are up to date. this._handleMutations(this._observer.takeRecords()); const visitNode = (node: Node | ShadowRoot): { equals: boolean, n: NodeSnapshot } | undefined => { const nodeType = node.nodeType; const nodeName = nodeType === Node.DOCUMENT_FRAGMENT_NODE ? 'template' : node.nodeName; if (nodeType !== Node.ELEMENT_NODE && nodeType !== Node.DOCUMENT_FRAGMENT_NODE && nodeType !== Node.TEXT_NODE) return; if (nodeName === 'SCRIPT') return; if (this._removeNoScript && nodeName === 'NOSCRIPT') return; if (nodeName === 'META' && (node as HTMLMetaElement).httpEquiv.toLowerCase() === 'content-security-policy') return; const data = ensureCachedData(node); const values: any[] = []; let equals = !!data.cached; let extraNodes = 0; const expectValue = (value: any) => { equals = equals && data.cached![values.length] === value; values.push(value); }; const checkAndReturn = (n: NodeSnapshot): { equals: boolean, n: NodeSnapshot } => { data.attributesCached = true; if (equals) return { equals: true, n: [[ snapshotNumber - data.ref![0], data.ref![1] ]] }; nodeCounter += extraNodes; data.ref = [snapshotNumber, nodeCounter++]; data.cached = values; return { equals: false, n }; }; if (nodeType === Node.TEXT_NODE) { const value = node.nodeValue || ''; expectValue(value); return checkAndReturn(value); } if (nodeName === 'STYLE') { const sheet = (node as HTMLStyleElement).sheet; let cssText: string | undefined; if (sheet) cssText = this._updateStyleElementStyleSheetTextIfNeeded(sheet); cssText = cssText || node.textContent || ''; expectValue(cssText); // Compensate for the extra 'cssText' text node. extraNodes++; return checkAndReturn(['style', {}, cssText]); } const attrs: { [attr: string]: string } = {}; const result: NodeSnapshot = [nodeName, attrs]; const visitChild = (child: Node) => { const snapshot = visitNode(child); if (snapshot) { result.push(snapshot.n); expectValue(child); equals = equals && snapshot.equals; } }; const visitChildStyleSheet = (child: CSSStyleSheet) => { const snapshot = visitStyleSheet(child); if (snapshot) { result.push(snapshot.n); expectValue(child); equals = equals && snapshot.equals; } }; if (nodeType === Node.DOCUMENT_FRAGMENT_NODE) attrs[kShadowAttribute] = 'open'; if (nodeType === Node.ELEMENT_NODE) { const element = node as Element; if (nodeName === 'INPUT') { const value = (element as HTMLInputElement).value; expectValue('value'); expectValue(value); attrs['value'] = value; if ((element as HTMLInputElement).checked) { expectValue('checked'); attrs['checked'] = ''; } } if (element.scrollTop) { expectValue(kScrollTopAttribute); expectValue(element.scrollTop); attrs[kScrollTopAttribute] = '' + element.scrollTop; } if (element.scrollLeft) { expectValue(kScrollLeftAttribute); expectValue(element.scrollLeft); attrs[kScrollLeftAttribute] = '' + element.scrollLeft; } if (element.shadowRoot) { ++shadowDomNesting; visitChild(element.shadowRoot); --shadowDomNesting; } } if (nodeName === 'TEXTAREA') { const value = (node as HTMLTextAreaElement).value; expectValue(value); extraNodes++; // Compensate for the extra text node. result.push(value); } else { if (nodeName === 'HEAD') { // Insert fake <base> first, to ensure all <link> elements use the proper base uri. this._fakeBase.setAttribute('href', document.baseURI); visitChild(this._fakeBase); } for (let child = node.firstChild; child; child = child.nextSibling) visitChild(child); expectValue(kEndOfList); let documentOrShadowRoot = null; if (node.ownerDocument!.documentElement === node) documentOrShadowRoot = node.ownerDocument; else if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) documentOrShadowRoot = node; if (documentOrShadowRoot) { for (const sheet of (documentOrShadowRoot as any).adoptedStyleSheets || []) visitChildStyleSheet(sheet); expectValue(kEndOfList); } } // Process iframe src attribute before bailing out since it depends on a symbol, not the DOM. if (nodeName === 'IFRAME' || nodeName === 'FRAME') { const element = node as Element; const frameId = (element as any)[kSnapshotFrameId]; const name = 'src'; const value = frameId ? `/snapshot/${frameId}` : ''; expectValue(name); expectValue(value); attrs[name] = value; } // We can skip attributes comparison because nothing else has changed, // and mutation observer didn't tell us about the attributes. if (equals && data.attributesCached && !shadowDomNesting) return checkAndReturn(result); if (nodeType === Node.ELEMENT_NODE) { const element = node as Element; for (let i = 0; i < element.attributes.length; i++) { const name = element.attributes[i].name; if (name === 'value' && (nodeName === 'INPUT' || nodeName === 'TEXTAREA')) continue; if (nodeName === 'LINK' && name === 'integrity') continue; if (nodeName === 'IFRAME' && name === 'src') continue; let value = element.attributes[i].value; if (name === 'src' && (nodeName === 'IMG')) value = this._sanitizeUrl(value); else if (name === 'srcset' && (nodeName === 'IMG')) value = this._sanitizeSrcSet(value); else if (name === 'srcset' && (nodeName === 'SOURCE')) value = this._sanitizeSrcSet(value); else if (name === 'href' && (nodeName === 'LINK')) value = this._sanitizeUrl(value); else if (name.startsWith('on')) value = ''; expectValue(name); expectValue(value); attrs[name] = value; } expectValue(kEndOfList); } if (result.length === 2 && !Object.keys(attrs).length) result.pop(); // Remove empty attrs when there are no children. return checkAndReturn(result); }; const visitStyleSheet = (sheet: CSSStyleSheet) => { const data = ensureCachedData(sheet); const oldCSSText = data.cssText; const cssText = this._updateStyleElementStyleSheetTextIfNeeded(sheet) || ''; if (cssText === oldCSSText) return { equals: true, n: [[ snapshotNumber - data.ref![0], data.ref![1] ]] }; data.ref = [snapshotNumber, nodeCounter++]; return { equals: false, n: ['template', { [kStyleSheetAttribute]: cssText, }] }; }; let html: NodeSnapshot; if (document.documentElement) { const { n } = visitNode(document.documentElement)!; html = n; } else { html = ['html']; } const result: SnapshotData = { html, doctype: document.doctype ? document.doctype.name : undefined, resourceOverrides: [], viewport: { width: window.innerWidth, height: window.innerHeight, }, url: location.href, timestamp, collectionTime: 0, }; for (const sheet of this._staleStyleSheets) { if (sheet.href === null) continue; const content = this._updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber); if (content === undefined) { // Unable to capture stylesheet contents. continue; } const base = this._getSheetBase(sheet); const url = removeHash(this._resolveUrl(base, sheet.href!)); result.resourceOverrides.push({ url, content, contentType: 'text/css' },); } result.collectionTime = performance.now() - result.timestamp; return result; } } (window as any)[snapshotStreamer] = new Streamer(); }
src/server/snapshot/snapshotterInjected.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017757555178832263, 0.0001727719936752692, 0.00016662639973219484, 0.00017254933482035995, 0.0000026341713237343356 ]
{ "id": 4, "code_window": [ " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n", " }\n", "\n", " private _checkFinished(info: RequestInfo) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " response.request().responseSize.responseHeadersSize = responseExtraInfo.headersText?.length || 0;\n", " }\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 681 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.9988080263137817, 0.058456581085920334, 0.00016314657113980502, 0.000264631409663707, 0.2296389639377594 ]
{ "id": 4, "code_window": [ " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n", " }\n", "\n", " private _checkFinished(info: RequestInfo) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " response.request().responseSize.responseHeadersSize = responseExtraInfo.headersText?.length || 0;\n", " }\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 681 }
/* * Copyright (C) 2018 Sony Interactive Entertainment Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "stdafx.h" #include <string> #include <vector> class Dialog { public: bool run(HINSTANCE hInst, HWND hwnd, int dialogId) { auto result = DialogBoxParam(hInst, MAKEINTRESOURCE(dialogId), hwnd, doalogProc, reinterpret_cast<LPARAM>(this)); return (result > 0); } static INT_PTR CALLBACK doalogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_INITDIALOG) SetWindowLongPtr(hDlg, DWLP_USER, lParam); else lParam = GetWindowLongPtr(hDlg, DWLP_USER); auto* dialog = reinterpret_cast<Dialog*>(lParam); return dialog->handle(hDlg, message, wParam); } protected: INT_PTR handle(HWND hDlg, UINT message, WPARAM wParam) { switch (message) { case WM_INITDIALOG: { m_hDlg = hDlg; setup(); update(); return TRUE; } case WM_COMMAND: int wmId = LOWORD(wParam); switch (wmId) { case IDOK: ok(); close(true); return TRUE; case IDCANCEL: cancel(); close(false); return TRUE; default: auto handled = command(wmId); update(); return handled; } } return FALSE; } virtual void setup() { } virtual void update() { updateOkButton(validate()); } virtual bool validate() { return true; } virtual void updateOkButton(bool isValid) { setEnabled(IDOK, isValid); } virtual bool command(int wmId) { return false; } virtual void ok() { } virtual void cancel() { } void close(bool success) { EndDialog(m_hDlg, success); } HWND hDlg() { return m_hDlg; } HWND item(int itemId) { return GetDlgItem(m_hDlg, itemId); } void setEnabled(int itemId, bool enabled) { EnableWindow(item(itemId), enabled); } void setText(int itemId, const std::wstring& str) { SetDlgItemText(m_hDlg, itemId, _bstr_t(str.c_str())); } std::wstring getText(int itemId) { auto length = getTextLength(itemId); std::vector<TCHAR> buffer(length + 1, 0); GetWindowText(item(itemId), buffer.data(), length + 1); return std::wstring { buffer.data() }; } int getTextLength(int itemId) { return GetWindowTextLength(item(itemId)); } class RadioGroup { public: RadioGroup(Dialog& dialog, int first, int last) : m_dialog(dialog) , m_first(first) , m_last(last) { } void set(int item) { CheckRadioButton(m_dialog.hDlg(), m_first, m_last, item); } int get() { for (int id = m_first; id <= m_last; id++) { if (IsDlgButtonChecked(m_dialog.hDlg(), id) == BST_CHECKED) return id; } return 0; } private: Dialog& m_dialog; int m_first; int m_last; }; RadioGroup radioGroup(int first, int last) { return RadioGroup(*this, first, last); } HWND m_hDlg { }; };
browser_patches/webkit/embedder/Playwright/win/DialogHelper.h
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017204039613716304, 0.00016856243018992245, 0.00016598384536337107, 0.00016805727500468493, 0.0000016447288544441108 ]
{ "id": 4, "code_window": [ " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n", " }\n", "\n", " private _checkFinished(info: RequestInfo) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " response.request().responseSize.responseHeadersSize = responseExtraInfo.headersText?.length || 0;\n", " }\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 681 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import '../third_party/vscode/codicon.css'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { applyTheme } from '../theme'; import '../common.css'; import { Report } from './htmlReport'; (async () => { applyTheme(); ReactDOM.render(<Report />, document.querySelector('#root')); })();
src/web/htmlReport/index.tsx
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017654168186709285, 0.0001745860354276374, 0.00017165744793601334, 0.00017555900558363646, 0.000002109332399413688 ]
{ "id": 4, "code_window": [ " response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\\n'));\n", " }\n", "\n", " private _checkFinished(info: RequestInfo) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " response.request().responseSize.responseHeadersSize = responseExtraInfo.headersText?.length || 0;\n", " }\n" ], "file_path": "src/server/chromium/crNetworkManager.ts", "type": "add", "edit_start_line_idx": 681 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; it('should check the box', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox'></input>`); await page.check('input'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); }); it('should not check the checked box', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox' checked></input>`); await page.check('input'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); }); it('should uncheck the box', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox' checked></input>`); await page.uncheck('input'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(false); }); it('should not uncheck the unchecked box', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox'></input>`); await page.uncheck('input'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(false); }); it('should check the box by label', async ({page}) => { await page.setContent(`<label for='checkbox'><input id='checkbox' type='checkbox'></input></label>`); await page.check('label'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); }); it('should check the box outside label', async ({page}) => { await page.setContent(`<label for='checkbox'>Text</label><div><input id='checkbox' type='checkbox'></input></div>`); await page.check('label'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); }); it('should check the box inside label w/o id', async ({page}) => { await page.setContent(`<label>Text<span><input id='checkbox' type='checkbox'></input></span></label>`); await page.check('label'); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); }); it('should check the box outside shadow dom label', async ({page}) => { await page.setContent('<div></div>'); await page.$eval('div', div => { const root = div.attachShadow({ mode: 'open' }); const label = document.createElement('label'); label.setAttribute('for', 'target'); label.textContent = 'Click me'; root.appendChild(label); const input = document.createElement('input'); input.setAttribute('type', 'checkbox'); input.setAttribute('id', 'target'); root.appendChild(input); }); await page.check('label'); expect(await page.$eval('input', input => input.checked)).toBe(true); }); it('should check radio', async ({page}) => { await page.setContent(` <input type='radio'>one</input> <input id='two' type='radio'>two</input> <input type='radio'>three</input>`); await page.check('#two'); expect(await page.evaluate(() => window['two'].checked)).toBe(true); }); it('should check radio by aria role', async ({page}) => { await page.setContent(`<div role='radio' id='checkbox'>CHECKBOX</div> <script> checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true')); </script>`); await page.check('div'); expect(await page.evaluate(() => window['checkbox'].getAttribute('aria-checked'))).toBe('true'); }); it('should uncheck radio by aria role', async ({page}) => { await page.setContent(`<div role='radio' id='checkbox' aria-checked="true">CHECKBOX</div> <script> checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'false')); </script>`); await page.uncheck('div'); expect(await page.evaluate(() => window['checkbox'].getAttribute('aria-checked'))).toBe('false'); }); it('should check the box by aria role', async ({page}) => { await page.setContent(`<div role='checkbox' id='checkbox'>CHECKBOX</div> <script> checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true')); </script>`); await page.check('div'); expect(await page.evaluate(() => window['checkbox'].getAttribute('aria-checked'))).toBe('true'); }); it('should uncheck the box by aria role', async ({page}) => { await page.setContent(`<div role='checkbox' id='checkbox' aria-checked="true">CHECKBOX</div> <script> checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'false')); </script>`); await page.uncheck('div'); expect(await page.evaluate(() => window['checkbox'].getAttribute('aria-checked'))).toBe('false'); }); it('should throw when not a checkbox', async ({page}) => { await page.setContent(`<div>Check me</div>`); const error = await page.check('div').catch(e => e); expect(error.message).toContain('Not a checkbox or radio button'); }); it('should check the box inside a button', async ({page}) => { await page.setContent(`<div role='button'><input type='checkbox'></div>`); await page.check('input'); expect(await page.$eval('input', input => input.checked)).toBe(true); expect(await page.isChecked('input')).toBe(true); expect(await (await page.$('input')).isChecked()).toBe(true); }); it('should check the label with position', async ({page, server}) => { await page.setContent(` <input id='checkbox' type='checkbox' style='width: 5px; height: 5px;'> <label for='checkbox'> <a href=${JSON.stringify(server.EMPTY_PAGE)}>I am a long link that goes away so that nothing good will happen if you click on me</a> Click me </label>`); const box = await (await page.$('text=Click me')).boundingBox(); await page.check('text=Click me', { position: { x: box.width - 10, y: 2 } }); expect(await page.$eval('input', input => input.checked)).toBe(true); }); it('trial run should not check', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox'></input>`); await page.check('input', { trial: true }); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(false); }); it('trial run should not uncheck', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox' checked></input>`); await page.uncheck('input', { trial: true }); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); }); it('should check the box using setChecked', async ({page}) => { await page.setContent(`<input id='checkbox' type='checkbox'></input>`); await page.setChecked('input', true); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(true); await page.setChecked('input', false); expect(await page.evaluate(() => window['checkbox'].checked)).toBe(false); });
tests/page/page-check.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017705076606944203, 0.0001721889420878142, 0.00016799198056105524, 0.00017214985564351082, 0.000002554796537879156 ]
{ "id": 5, "code_window": [ "}\n", "\n", "type ResponseSize = {\n", " encodedBodySize: number;\n", " transferSize: number;\n", "};\n", "\n", "export class Request extends SdkObject {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " responseHeadersSize: number;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 85 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.986687183380127, 0.13630735874176025, 0.0001626008452149108, 0.0002431934408377856, 0.32328733801841736 ]
{ "id": 5, "code_window": [ "}\n", "\n", "type ResponseSize = {\n", " encodedBodySize: number;\n", " transferSize: number;\n", "};\n", "\n", "export class Request extends SdkObject {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " responseHeadersSize: number;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 85 }
CALL gn gen out/Default CALL ninja -j 200 -C out/Default chrome eventlog_provider
browser_patches/chromium/buildwingoma.bat
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00016769046487752348, 0.00016769046487752348, 0.00016769046487752348, 0.00016769046487752348, 0 ]
{ "id": 5, "code_window": [ "}\n", "\n", "type ResponseSize = {\n", " encodedBodySize: number;\n", " transferSize: number;\n", "};\n", "\n", "export class Request extends SdkObject {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " responseHeadersSize: number;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 85 }
# Playwright and FFMPEG Playwright requires FFMPEG to produce screncast and bundles FFMPEG binaries for Mac , Linux and Windows. ## Configuration We compile `libvpx` and `ffmpeg` only. Their source versions and build configurations are defined in [`//browser_patches/ffmpeg/CONFIG.sh`](./CONFIG.sh). ## Building `ffmpeg-linux` Compilation scripts are based on: - https://trac.ffmpeg.org/wiki/CompilationGuide/Generic Prerequisites: - Mac or Linux - Docker Building: ``` ~/playwright$ ./browser_patches/ffmpeg/build.sh --linux ``` ## Building `ffmpeg-mac` Compilation scripts are based on: - https://trac.ffmpeg.org/wiki/CompilationGuide/Generic - https://trac.ffmpeg.org/wiki/CompilationGuide/macOS Prerequisites: - Mac - xcode command line tools: `xcode-select --install` - [homebrew](https://brew.sh/) Building: ``` ~/playwright$ ./browser_patches/ffmpeg/build.sh --mac ``` ## Building `ffmpeg-win*` Cross-compilation scripts are based on: - https://trac.ffmpeg.org/wiki/CompilationGuide/Generic - https://trac.ffmpeg.org/wiki/CompilationGuide/CrossCompilingForWindows Prerequisites: - Mac or Linux - [Docker](https://www.docker.com/) Building: ``` ~/playwright$ ./browser_patches/ffmpeg/build.sh --cross-compile-win32 ~/playwright$ ./browser_patches/ffmpeg/build.sh --cross-compile-win64 ```
browser_patches/ffmpeg/README.md
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017423322424292564, 0.00016950782446656376, 0.00016610021702945232, 0.00016923058137763292, 0.000002897830427173176 ]
{ "id": 5, "code_window": [ "}\n", "\n", "type ResponseSize = {\n", " encodedBodySize: number;\n", " transferSize: number;\n", "};\n", "\n", "export class Request extends SdkObject {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " responseHeadersSize: number;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 85 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Explicitly empty install.js to avoid touching browser registry at all. // See https://github.com/microsoft/playwright/issues/4083
packages/playwright-core/install.js
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017607516201678663, 0.00017586714238859713, 0.00017565912276040763, 0.00017586714238859713, 2.0801962818950415e-7 ]
{ "id": 6, "code_window": [ " readonly _headers: types.HeadersArray;\n", " private _headersMap = new Map<string, string>();\n", " private _frame: frames.Frame;\n", " private _waitForResponsePromise = new ManualPromise<Response | null>();\n", " _responseEndTiming = -1;\n", " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0 };\n", "\n", " constructor(frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined,\n", " url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0, responseHeadersSize: 0 };\n" ], "file_path": "src/server/network.ts", "type": "replace", "edit_start_line_idx": 103 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.007406165357679129, 0.0005141268484294415, 0.00016011866682674736, 0.00017068322631530464, 0.0010028777178376913 ]
{ "id": 6, "code_window": [ " readonly _headers: types.HeadersArray;\n", " private _headersMap = new Map<string, string>();\n", " private _frame: frames.Frame;\n", " private _waitForResponsePromise = new ManualPromise<Response | null>();\n", " _responseEndTiming = -1;\n", " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0 };\n", "\n", " constructor(frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined,\n", " url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0, responseHeadersSize: 0 };\n" ], "file_path": "src/server/network.ts", "type": "replace", "edit_start_line_idx": 103 }
# text files must be lf for golden file tests to work *.txt eol=lf *.json eol=lf
.gitattributes
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017305534856859595, 0.00017305534856859595, 0.00017305534856859595, 0.00017305534856859595, 0 ]
{ "id": 6, "code_window": [ " readonly _headers: types.HeadersArray;\n", " private _headersMap = new Map<string, string>();\n", " private _frame: frames.Frame;\n", " private _waitForResponsePromise = new ManualPromise<Response | null>();\n", " _responseEndTiming = -1;\n", " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0 };\n", "\n", " constructor(frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined,\n", " url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0, responseHeadersSize: 0 };\n" ], "file_path": "src/server/network.ts", "type": "replace", "edit_start_line_idx": 103 }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; it('should fail page.textContent in strict mode', async ({ page }) => { await page.setContent(`<span>span1</span><div><span>target</span></div>`); const error = await page.textContent('span', { strict: true }).catch(e => e); expect(error.message).toContain('strict mode violation'); expect(error.message).toContain('1) <span>span1</span> aka playwright.$("text=span1")'); expect(error.message).toContain('2) <span>target</span> aka playwright.$("text=target")'); }); it('should fail page.getAttribute in strict mode', async ({ page }) => { await page.setContent(`<span>span1</span><div><span>target</span></div>`); const error = await page.getAttribute('span', 'id', { strict: true }).catch(e => e); expect(error.message).toContain('strict mode violation'); }); it('should fail page.fill in strict mode', async ({ page }) => { await page.setContent(`<input></input><div><input></input></div>`); const error = await page.fill('input', 'text', { strict: true }).catch(e => e); expect(error.message).toContain('strict mode violation'); expect(error.message).toContain('1) <input/> aka playwright.$("input")'); expect(error.message).toContain('2) <input/> aka playwright.$("div input")'); }); it('should fail page.$ in strict mode', async ({ page }) => { await page.setContent(`<span>span1</span><div><span>target</span></div>`); const error = await page.$('span', { strict: true }).catch(e => e); expect(error.message).toContain('strict mode violation'); }); it('should fail page.waitForSelector in strict mode', async ({ page }) => { await page.setContent(`<span>span1</span><div><span>target</span></div>`); const error = await page.waitForSelector('span', { strict: true }).catch(e => e); expect(error.message).toContain('strict mode violation'); }); it('should fail page.dispatchEvent in strict mode', async ({ page }) => { await page.setContent(`<span></span><div><span></span></div>`); const error = await page.dispatchEvent('span', 'click', {}, { strict: true }).catch(e => e); expect(error.message).toContain('strict mode violation'); expect(error.message).toContain('1) <span></span> aka playwright.$("span")'); expect(error.message).toContain('2) <span></span> aka playwright.$("div span")'); });
tests/page/page-strict.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017584700253792107, 0.00017389694403391331, 0.0001714613172225654, 0.00017403665697202086, 0.0000015182847619144013 ]
{ "id": 6, "code_window": [ " readonly _headers: types.HeadersArray;\n", " private _headersMap = new Map<string, string>();\n", " private _frame: frames.Frame;\n", " private _waitForResponsePromise = new ManualPromise<Response | null>();\n", " _responseEndTiming = -1;\n", " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0 };\n", "\n", " constructor(frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined,\n", " url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0, responseHeadersSize: 0 };\n" ], "file_path": "src/server/network.ts", "type": "replace", "edit_start_line_idx": 103 }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="CompilerConfiguration"> <bytecodeTargetLevel target="1.8" /> </component> </project>
src/server/android/driver/.idea/compiler.xml
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001688331103650853, 0.0001688331103650853, 0.0001688331103650853, 0.0001688331103650853, 0 ]
{ "id": 7, "code_window": [ " return headersSize;\n", " }\n", "\n", " private async _responseHeadersSize(): Promise<number> {\n", " let headersSize = 4; // 4 = 2 spaces + 2 line breaks (HTTP/1.1 200 Ok\\r\\n)\n", " headersSize += 8; // httpVersion;\n", " headersSize += 3; // statusCode;\n", " headersSize += this.statusText().length;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this._request.responseSize.responseHeadersSize)\n", " return this._request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 448 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.9576108455657959, 0.08011991530656815, 0.00016596121713519096, 0.00019320599676575512, 0.2192540168762207 ]
{ "id": 7, "code_window": [ " return headersSize;\n", " }\n", "\n", " private async _responseHeadersSize(): Promise<number> {\n", " let headersSize = 4; // 4 = 2 spaces + 2 line breaks (HTTP/1.1 200 Ok\\r\\n)\n", " headersSize += 8; // httpVersion;\n", " headersSize += 3; // statusCode;\n", " headersSize += this.statusText().length;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this._request.responseSize.responseHeadersSize)\n", " return this._request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 448 }
# class: TestStep * langs: js Represents a step in the [TestRun]. ## property: TestStep.category - type: <[string]> Step category to differentiate steps with different origin and verbosity. Built-in categories are: * `hook` for fixtures and hooks initialization and teardown * `expect` for expect calls * `pw:api` for Playwright API calls. * `test.step` for test.step API calls. ## property: TestStep.duration - type: <[float]> Running time in milliseconds. ## property: TestStep.error - type: <[void]|[TestError]> An error thrown during the step execution, if any. ## property: TestStep.parent - type: <[void]|[TestStep]> Parent step, if any. ## property: TestStep.startTime - type: <[Date]> Start time of this particular test step. ## property: TestStep.steps - type: <[Array]<[TestStep]>> List of steps inside this step. ## property: TestStep.title - type: <[string]> User-friendly test step title. ## method: TestStep.titlePath - returns: <[Array]<[string]>> Returns a list of step titles from the root step down to this step.
docs/src/test-reporter-api/class-teststep.md
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017267065413761884, 0.00016830353706609458, 0.00016154533659573644, 0.0001697703992249444, 0.000003919469691027189 ]
{ "id": 7, "code_window": [ " return headersSize;\n", " }\n", "\n", " private async _responseHeadersSize(): Promise<number> {\n", " let headersSize = 4; // 4 = 2 spaces + 2 line breaks (HTTP/1.1 200 Ok\\r\\n)\n", " headersSize += 8; // httpVersion;\n", " headersSize += 3; // statusCode;\n", " headersSize += this.statusText().length;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this._request.responseSize.responseHeadersSize)\n", " return this._request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 448 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; import fs from 'fs'; it('should work', async ({page, server}) => { await page.route('**/*', route => { route.fulfill({ status: 201, headers: { foo: 'bar' }, contentType: 'text/html', body: 'Yo, page!' }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(201); expect(response.headers().foo).toBe('bar'); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should work with buffer as body', async ({page, server, browserName, isLinux}) => { it.fail(browserName === 'webkit' && isLinux, 'Loading of application/octet-stream resource fails'); await page.route('**/*', route => { route.fulfill({ status: 200, body: Buffer.from('Yo, page!') }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(200); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should work with status code 422', async ({page, server}) => { await page.route('**/*', route => { route.fulfill({ status: 422, body: 'Yo, page!' }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(422); expect(response.statusText()).toBe('Unprocessable Entity'); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should allow mocking binary responses', async ({page, server, browserName, headless, asset, isAndroid}) => { it.skip(browserName === 'firefox' && !headless, 'Firefox headed produces a different image.'); it.skip(isAndroid); await page.route('**/*', route => { const imageBuffer = fs.readFileSync(asset('pptr.png')); route.fulfill({ contentType: 'image/png', body: imageBuffer }); }); await page.evaluate(PREFIX => { const img = document.createElement('img'); img.src = PREFIX + '/does-not-exist.png'; document.body.appendChild(img); return new Promise(fulfill => img.onload = fulfill); }, server.PREFIX); const img = await page.$('img'); expect(await img.screenshot()).toMatchSnapshot('mock-binary-response.png'); }); it('should allow mocking svg with charset', async ({page, server, browserName, headless, isAndroid}) => { it.skip(browserName === 'firefox' && !headless, 'Firefox headed produces a different image.'); it.skip(isAndroid); await page.route('**/*', route => { route.fulfill({ contentType: 'image/svg+xml ; charset=utf-8', body: '<svg width="50" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg"><rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/></svg>' }); }); await page.evaluate(PREFIX => { const img = document.createElement('img'); img.src = PREFIX + '/does-not-exist.svg'; document.body.appendChild(img); return new Promise((f, r) => { img.onload = f; img.onerror = r; }); }, server.PREFIX); const img = await page.$('img'); expect(await img.screenshot()).toMatchSnapshot('mock-svg.png'); }); it('should work with file path', async ({page, server, asset, isAndroid}) => { it.skip(isAndroid); await page.route('**/*', route => route.fulfill({ contentType: 'shouldBeIgnored', path: asset('pptr.png') })); await page.evaluate(PREFIX => { const img = document.createElement('img'); img.src = PREFIX + '/does-not-exist.png'; document.body.appendChild(img); return new Promise(fulfill => img.onload = fulfill); }, server.PREFIX); const img = await page.$('img'); expect(await img.screenshot()).toMatchSnapshot('mock-binary-response.png'); }); it('should stringify intercepted request response headers', async ({page, server}) => { await page.route('**/*', route => { route.fulfill({ status: 200, headers: { 'foo': 'true' }, body: 'Yo, page!' }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(200); const headers = response.headers(); expect(headers.foo).toBe('true'); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should not modify the headers sent to the server', async ({page, server}) => { await page.goto(server.PREFIX + '/empty.html'); const interceptedRequests = []; // this is just to enable request interception, which disables caching in chromium await page.route(server.PREFIX + '/unused', () => {}); server.setRoute('/something', (request, response) => { interceptedRequests.push(request); response.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); response.end('done'); }); const text = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.CROSS_PROCESS_PREFIX + '/something'); expect(text).toBe('done'); await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => { route.continue({ headers: { ...request.headers() } }); }); const textAfterRoute = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.CROSS_PROCESS_PREFIX + '/something'); expect(textAfterRoute).toBe('done'); expect(interceptedRequests.length).toBe(2); expect(interceptedRequests[1].headers).toEqual(interceptedRequests[0].headers); }); it('should include the origin header', async ({page, server, isAndroid}) => { it.skip(isAndroid, 'No cross-process on Android'); await page.goto(server.PREFIX + '/empty.html'); let interceptedRequest; await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => { interceptedRequest = request; route.fulfill({ headers: { 'Access-Control-Allow-Origin': '*', }, contentType: 'text/plain', body: 'done' }); }); const text = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.CROSS_PROCESS_PREFIX + '/something'); expect(text).toBe('done'); expect(interceptedRequest.headers()['origin']).toEqual(server.PREFIX); }); it('should fulfill with fetch result', async ({page, server, isElectron}) => { it.fixme(isElectron, 'error: Browser context management is not supported.'); await page.route('**/*', async route => { // @ts-expect-error const response = await page._fetch(server.PREFIX + '/simple.json'); // @ts-expect-error route.fulfill({ response }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(200); expect(await response.json()).toEqual({'foo': 'bar'}); }); it('should fulfill with fetch result and overrides', async ({page, server, isElectron}) => { it.fixme(isElectron, 'error: Browser context management is not supported.'); await page.route('**/*', async route => { // @ts-expect-error const response = await page._fetch(server.PREFIX + '/simple.json'); route.fulfill({ // @ts-expect-error response, status: 201, headers: { 'foo': 'bar' } }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(201); expect((await response.allHeaders()).foo).toEqual('bar'); expect(await response.json()).toEqual({'foo': 'bar'}); }); it('should fetch original request and fulfill', async ({page, server, isElectron}) => { it.fixme(isElectron, 'error: Browser context management is not supported.'); await page.route('**/*', async route => { // @ts-expect-error const response = await page._fetch(route.request()); route.fulfill({ // @ts-expect-error response, }); }); const response = await page.goto(server.PREFIX + '/title.html'); expect(response.status()).toBe(200); expect(await page.title()).toEqual('Woof-Woof'); });
tests/page/page-request-fulfill.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.005487101152539253, 0.00046330157783813775, 0.0001643822033656761, 0.00017188035417348146, 0.0010618510423228145 ]
{ "id": 7, "code_window": [ " return headersSize;\n", " }\n", "\n", " private async _responseHeadersSize(): Promise<number> {\n", " let headersSize = 4; // 4 = 2 spaces + 2 line breaks (HTTP/1.1 200 Ok\\r\\n)\n", " headersSize += 8; // httpVersion;\n", " headersSize += 3; // statusCode;\n", " headersSize += this.statusText().length;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this._request.responseSize.responseHeadersSize)\n", " return this._request.responseSize.responseHeadersSize;\n" ], "file_path": "src/server/network.ts", "type": "add", "edit_start_line_idx": 448 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Page, BindingCall } from './page'; import { Frame } from './frame'; import * as network from './network'; import * as channels from '../protocol/channels'; import fs from 'fs'; import { ChannelOwner } from './channelOwner'; import { deprecate, evaluationScript } from './clientHelper'; import { Browser } from './browser'; import { Worker } from './worker'; import { Events } from './events'; import { TimeoutSettings } from '../utils/timeoutSettings'; import { Waiter } from './waiter'; import { URLMatch, Headers, WaitForEventOptions, BrowserContextOptions, StorageState, LaunchOptions } from './types'; import { isUnderTest, headersObjectToArray, mkdirIfNeeded, isString, assert } from '../utils/utils'; import { isSafeCloseError } from '../utils/errors'; import * as api from '../../types/types'; import * as structs from '../../types/structs'; import { CDPSession } from './cdpSession'; import { Tracing } from './tracing'; import type { BrowserType } from './browserType'; import { Artifact } from './artifact'; export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel, channels.BrowserContextInitializer> implements api.BrowserContext { _pages = new Set<Page>(); private _routes: network.RouteHandler[] = []; readonly _browser: Browser | null = null; private _browserType: BrowserType | undefined; readonly _bindings = new Map<string, (source: structs.BindingSource, ...args: any[]) => any>(); _timeoutSettings = new TimeoutSettings(); _ownerPage: Page | undefined; private _closedPromise: Promise<void>; _options: channels.BrowserNewContextParams = { }; readonly tracing: Tracing; private _closed = false; readonly _backgroundPages = new Set<Page>(); readonly _serviceWorkers = new Set<Worker>(); readonly _isChromium: boolean; static from(context: channels.BrowserContextChannel): BrowserContext { return (context as any)._object; } static fromNullable(context: channels.BrowserContextChannel | null): BrowserContext | null { return context ? BrowserContext.from(context) : null; } constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserContextInitializer) { super(parent, type, guid, initializer); if (parent instanceof Browser) this._browser = parent; this._isChromium = this._browser?._name === 'chromium'; this.tracing = new Tracing(this); this._channel.on('bindingCall', ({binding}) => this._onBinding(BindingCall.from(binding))); this._channel.on('close', () => this._onClose()); this._channel.on('page', ({page}) => this._onPage(Page.from(page))); this._channel.on('route', ({ route, request }) => this._onRoute(network.Route.from(route), network.Request.from(request))); this._channel.on('backgroundPage', ({ page }) => { const backgroundPage = Page.from(page); this._backgroundPages.add(backgroundPage); this.emit(Events.BrowserContext.BackgroundPage, backgroundPage); }); this._channel.on('serviceWorker', ({worker}) => { const serviceWorker = Worker.from(worker); serviceWorker._context = this; this._serviceWorkers.add(serviceWorker); this.emit(Events.BrowserContext.ServiceWorker, serviceWorker); }); this._channel.on('request', ({ request, page }) => this._onRequest(network.Request.from(request), Page.fromNullable(page))); this._channel.on('requestFailed', ({ request, failureText, responseEndTiming, page }) => this._onRequestFailed(network.Request.from(request), responseEndTiming, failureText, Page.fromNullable(page))); this._channel.on('requestFinished', params => this._onRequestFinished(params)); this._channel.on('response', ({ response, page }) => this._onResponse(network.Response.from(response), Page.fromNullable(page))); this._closedPromise = new Promise(f => this.once(Events.BrowserContext.Close, f)); } _setBrowserType(browserType: BrowserType) { this._browserType = browserType; browserType._contexts.add(this); } private _onPage(page: Page): void { this._pages.add(page); this.emit(Events.BrowserContext.Page, page); if (page._opener && !page._opener.isClosed()) page._opener.emit(Events.Page.Popup, page); } private _onRequest(request: network.Request, page: Page | null) { this.emit(Events.BrowserContext.Request, request); if (page) page.emit(Events.Page.Request, request); } private _onResponse(response: network.Response, page: Page | null) { this.emit(Events.BrowserContext.Response, response); if (page) page.emit(Events.Page.Response, response); } private _onRequestFailed(request: network.Request, responseEndTiming: number, failureText: string | undefined, page: Page | null) { request._failureText = failureText || null; if (request._timing) request._timing.responseEnd = responseEndTiming; this.emit(Events.BrowserContext.RequestFailed, request); if (page) page.emit(Events.Page.RequestFailed, request); } private _onRequestFinished(params: channels.BrowserContextRequestFinishedEvent) { const { responseEndTiming } = params; const request = network.Request.from(params.request); const response = network.Response.fromNullable(params.response); const page = Page.fromNullable(params.page); if (request._timing) request._timing.responseEnd = responseEndTiming; this.emit(Events.BrowserContext.RequestFinished, request); if (page) page.emit(Events.Page.RequestFinished, request); if (response) response._finishedPromise.resolve(); } _onRoute(route: network.Route, request: network.Request) { for (const routeHandler of this._routes) { if (routeHandler.matches(request.url())) { routeHandler.handle(route, request); return; } } // it can race with BrowserContext.close() which then throws since its closed route.continue().catch(() => {}); } async _onBinding(bindingCall: BindingCall) { const func = this._bindings.get(bindingCall._initializer.name); if (!func) return; await bindingCall.call(func); } setDefaultNavigationTimeout(timeout: number) { this._timeoutSettings.setDefaultNavigationTimeout(timeout); this._channel.setDefaultNavigationTimeoutNoReply({ timeout }); } setDefaultTimeout(timeout: number) { this._timeoutSettings.setDefaultTimeout(timeout); this._channel.setDefaultTimeoutNoReply({ timeout }); } browser(): Browser | null { return this._browser; } pages(): Page[] { return [...this._pages]; } async newPage(): Promise<Page> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { if (this._ownerPage) throw new Error('Please use browser.newContext()'); return Page.from((await channel.newPage()).page); }); } async cookies(urls?: string | string[]): Promise<network.NetworkCookie[]> { if (!urls) urls = []; if (urls && typeof urls === 'string') urls = [ urls ]; return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { return (await channel.cookies({ urls: urls as string[] })).cookies; }); } async addCookies(cookies: network.SetNetworkCookieParam[]): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.addCookies({ cookies }); }); } async clearCookies(): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.clearCookies(); }); } async grantPermissions(permissions: string[], options?: { origin?: string }): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.grantPermissions({ permissions, ...options }); }); } async clearPermissions(): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.clearPermissions(); }); } async _fetch(request: network.Request, options?: { timeout?: number }): Promise<network.FetchResponse>; async _fetch(url: string, options?: FetchOptions): Promise<network.FetchResponse>; async _fetch(urlOrRequest: string|network.Request, options: FetchOptions = {}): Promise<network.FetchResponse> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { const request: network.Request | undefined = (urlOrRequest instanceof network.Request) ? urlOrRequest as network.Request : undefined; assert(request || typeof urlOrRequest === 'string', 'First argument must be either URL string or Request'); const url = request ? request.url() : urlOrRequest as string; const method = request?.method() || options.method; // Cannot call allHeaders() here as the request may be paused inside route handler. const headersObj = request?.headers() || options.headers; const headers = headersObj ? headersObjectToArray(headersObj) : undefined; let postDataBuffer = request?.postDataBuffer(); if (postDataBuffer === undefined) postDataBuffer = (isString(options.postData) ? Buffer.from(options.postData, 'utf8') : options.postData); const postData = (postDataBuffer ? postDataBuffer.toString('base64') : undefined); const result = await channel.fetch({ url, method, headers, postData, timeout: options.timeout, }); if (result.error) throw new Error(`Request failed: ${result.error}`); return new network.FetchResponse(this, result.response!); }); } async setGeolocation(geolocation: { longitude: number, latitude: number, accuracy?: number } | null): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.setGeolocation({ geolocation: geolocation || undefined }); }); } async setExtraHTTPHeaders(headers: Headers): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { network.validateHeaders(headers); await channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) }); }); } async setOffline(offline: boolean): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.setOffline({ offline }); }); } async setHTTPCredentials(httpCredentials: { username: string, password: string } | null): Promise<void> { if (!isUnderTest()) deprecate(`context.setHTTPCredentials`, `warning: method |context.setHTTPCredentials()| is deprecated. Instead of changing credentials, create another browser context with new credentials.`); return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.setHTTPCredentials({ httpCredentials: httpCredentials || undefined }); }); } async addInitScript(script: Function | string | { path?: string, content?: string }, arg?: any): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { const source = await evaluationScript(script, arg); await channel.addInitScript({ source }); }); } async exposeBinding(name: string, callback: (source: structs.BindingSource, ...args: any[]) => any, options: { handle?: boolean } = {}): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.exposeBinding({ name, needsHandle: options.handle }); this._bindings.set(name, callback); }); } async exposeFunction(name: string, callback: Function): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await channel.exposeBinding({ name }); const binding = (source: structs.BindingSource, ...args: any[]) => callback(...args); this._bindings.set(name, binding); }); } async route(url: URLMatch, handler: network.RouteHandlerCallback, options: { times?: number } = {}): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { this._routes.unshift(new network.RouteHandler(this._options.baseURL, url, handler, options.times)); if (this._routes.length === 1) await channel.setNetworkInterceptionEnabled({ enabled: true }); }); } async unroute(url: URLMatch, handler?: network.RouteHandlerCallback): Promise<void> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { this._routes = this._routes.filter(route => route.url !== url || (handler && route.handler !== handler)); if (this._routes.length === 0) await channel.setNetworkInterceptionEnabled({ enabled: false }); }); } async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> { return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate); const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate; const waiter = Waiter.createForEvent(this, event); waiter.rejectOnTimeout(timeout, `Timeout while waiting for event "${event}"`); if (event !== Events.BrowserContext.Close) waiter.rejectOnEvent(this, Events.BrowserContext.Close, new Error('Context closed')); const result = await waiter.waitForEvent(this, event, predicate as any); waiter.dispose(); return result; }); } async storageState(options: { path?: string } = {}): Promise<StorageState> { return await this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { const state = await channel.storageState(); if (options.path) { await mkdirIfNeeded(options.path); await fs.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8'); } return state; }); } backgroundPages(): Page[] { return [...this._backgroundPages]; } serviceWorkers(): Worker[] { return [...this._serviceWorkers]; } async newCDPSession(page: Page | Frame): Promise<api.CDPSession> { // channelOwner.ts's validation messages don't handle the pseudo-union type, so we're explicit here if (!(page instanceof Page) && !(page instanceof Frame)) throw new Error('page: expected Page or Frame'); return this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { const result = await channel.newCDPSession(page instanceof Page ? { page: page._channel } : { frame: page._channel }); return CDPSession.from(result.session); }); } _onClose() { this._closed = true; if (this._browser) this._browser._contexts.delete(this); this._browserType?._contexts?.delete(this); this.emit(Events.BrowserContext.Close, this); } async close(): Promise<void> { try { await this._wrapApiCall(async (channel: channels.BrowserContextChannel) => { await this._browserType?._onWillCloseContext?.(this); if (this._options.recordHar) { const har = await this._channel.harExport(); const artifact = Artifact.from(har.artifact); if (this.browser()?._remoteType) artifact._isRemote = true; await artifact.saveAs(this._options.recordHar.path); await artifact.delete(); } await channel.close(); await this._closedPromise; }); } catch (e) { if (isSafeCloseError(e)) return; throw e; } } async _enableRecorder(params: { language: string, launchOptions?: LaunchOptions, contextOptions?: BrowserContextOptions, device?: string, saveStorage?: string, startRecording?: boolean, outputFile?: string }) { await this._channel.recorderSupplementEnable(params); } } export type FetchOptions = { url?: string, method?: string, headers?: Headers, postData?: string | Buffer, timeout?: number }; export async function prepareBrowserContextParams(options: BrowserContextOptions): Promise<channels.BrowserNewContextParams> { if (options.videoSize && !options.videosPath) throw new Error(`"videoSize" option requires "videosPath" to be specified`); if (options.extraHTTPHeaders) network.validateHeaders(options.extraHTTPHeaders); const contextParams: channels.BrowserNewContextParams = { ...options, viewport: options.viewport === null ? undefined : options.viewport, noDefaultViewport: options.viewport === null, extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined, storageState: typeof options.storageState === 'string' ? JSON.parse(await fs.promises.readFile(options.storageState, 'utf8')) : options.storageState, }; if (!contextParams.recordVideo && options.videosPath) { contextParams.recordVideo = { dir: options.videosPath, size: options.videoSize }; } return contextParams; }
src/client/browserContext.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.01518622413277626, 0.0007746937917545438, 0.00016343913739547133, 0.00017057236982509494, 0.0024432209320366383 ]
{ "id": 8, "code_window": [ " validTo: responseReceivedPayload?.response.security?.certificate?.validUntil,\n", " });\n", " if (event.metrics?.protocol)\n", " response._setHttpVersion(event.metrics.protocol);\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (event.metrics?.responseBodyBytesReceived)\n", " request.request.responseSize.encodedBodySize = event.metrics.responseBodyBytesReceived;\n", " if (event.metrics?.responseHeaderBytesReceived)\n", " request.request.responseSize.responseHeadersSize = event.metrics.responseHeaderBytesReceived;\n", "\n" ], "file_path": "src/server/webkit/wkPage.ts", "type": "add", "edit_start_line_idx": 1000 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as frames from './frames'; import * as types from './types'; import { assert } from '../utils/utils'; import { ManualPromise } from '../utils/async'; import { SdkObject } from './instrumentation'; import { NameValue } from '../common/types'; export function filterCookies(cookies: types.NetworkCookie[], urls: string[]): types.NetworkCookie[] { const parsedURLs = urls.map(s => new URL(s)); // Chromiums's cookies are missing sameSite when it is 'None' return cookies.filter(c => { // Firefox and WebKit can return cookies with empty values. if (!c.value) return false; if (!parsedURLs.length) return true; for (const parsedURL of parsedURLs) { let domain = c.domain; if (!domain.startsWith('.')) domain = '.' + domain; if (!('.' + parsedURL.hostname).endsWith(domain)) continue; if (!parsedURL.pathname.startsWith(c.path)) continue; if (parsedURL.protocol !== 'https:' && c.secure) continue; return true; } return false; }); } export function rewriteCookies(cookies: types.SetNetworkCookieParam[]): types.SetNetworkCookieParam[] { return cookies.map(c => { assert(c.name, 'Cookie should have a name'); assert(c.value, 'Cookie should have a value'); assert(c.url || (c.domain && c.path), 'Cookie should have a url or a domain/path pair'); assert(!(c.url && c.domain), 'Cookie should have either url or domain'); assert(!(c.url && c.path), 'Cookie should have either url or path'); const copy = {...c}; if (copy.url) { assert(copy.url !== 'about:blank', `Blank page can not have cookie "${c.name}"`); assert(!copy.url.startsWith('data:'), `Data URL page can not have cookie "${c.name}"`); const url = new URL(copy.url); copy.domain = url.hostname; copy.path = url.pathname.substring(0, url.pathname.lastIndexOf('/') + 1); copy.secure = url.protocol === 'https:'; } return copy; }); } export function parsedURL(url: string): URL | null { try { return new URL(url); } catch (e) { return null; } } export function stripFragmentFromUrl(url: string): string { if (!url.includes('#')) return url; return url.substring(0, url.indexOf('#')); } type ResponseSize = { encodedBodySize: number; transferSize: number; }; export class Request extends SdkObject { private _response: Response | null = null; private _redirectedFrom: Request | null; _redirectedTo: Request | null = null; readonly _documentId?: string; readonly _isFavicon: boolean; _failureText: string | null = null; private _url: string; private _resourceType: string; private _method: string; private _postData: Buffer | null; readonly _headers: types.HeadersArray; private _headersMap = new Map<string, string>(); private _frame: frames.Frame; private _waitForResponsePromise = new ManualPromise<Response | null>(); _responseEndTiming = -1; readonly responseSize: ResponseSize = { encodedBodySize: 0, transferSize: 0 }; constructor(frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined, url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) { super(frame, 'request'); assert(!url.startsWith('data:'), 'Data urls should not fire requests'); this._frame = frame; this._redirectedFrom = redirectedFrom; if (redirectedFrom) redirectedFrom._redirectedTo = this; this._documentId = documentId; this._url = stripFragmentFromUrl(url); this._resourceType = resourceType; this._method = method; this._postData = postData; this._headers = headers; for (const { name, value } of this._headers) this._headersMap.set(name.toLowerCase(), value); this._isFavicon = url.endsWith('/favicon.ico') || !!redirectedFrom?._isFavicon; } _setFailureText(failureText: string) { this._failureText = failureText; this._waitForResponsePromise.resolve(null); } url(): string { return this._url; } resourceType(): string { return this._resourceType; } method(): string { return this._method; } postDataBuffer(): Buffer | null { return this._postData; } headers(): types.HeadersArray { return this._headers; } headerValue(name: string): string | undefined { return this._headersMap.get(name); } async rawHeaders(): Promise<NameValue[]> { return this._headers; } response(): PromiseLike<Response | null> { return this._waitForResponsePromise; } _existingResponse(): Response | null { return this._response; } _setResponse(response: Response) { this._response = response; this._waitForResponsePromise.resolve(response); } _finalRequest(): Request { return this._redirectedTo ? this._redirectedTo._finalRequest() : this; } frame(): frames.Frame { return this._frame; } isNavigationRequest(): boolean { return !!this._documentId; } redirectedFrom(): Request | null { return this._redirectedFrom; } failure(): { errorText: string } | null { if (this._failureText === null) return null; return { errorText: this._failureText }; } bodySize(): number { return this.postDataBuffer()?.length || 0; } } export class Route extends SdkObject { private readonly _request: Request; private readonly _delegate: RouteDelegate; private _handled = false; private _response: InterceptedResponse | null = null; constructor(request: Request, delegate: RouteDelegate) { super(request.frame(), 'route'); this._request = request; this._delegate = delegate; } request(): Request { return this._request; } async abort(errorCode: string = 'failed') { assert(!this._handled, 'Route is already handled!'); this._handled = true; await this._delegate.abort(errorCode); } async fulfill(overrides: { status?: number, headers?: types.HeadersArray, body?: string, isBase64?: boolean, useInterceptedResponseBody?: boolean, fetchResponseUid?: string }) { assert(!this._handled, 'Route is already handled!'); this._handled = true; let body = overrides.body; let isBase64 = overrides.isBase64 || false; if (body === undefined) { if (overrides.fetchResponseUid) { const context = this._request.frame()._page._browserContext; const buffer = context.fetchResponses.get(overrides.fetchResponseUid); assert(buffer, 'Fetch response has been disposed'); body = buffer.toString('utf8'); isBase64 = false; } else if (this._response && overrides.useInterceptedResponseBody) { body = (await this._delegate.responseBody()).toString('utf8'); isBase64 = false; } else { body = ''; isBase64 = false; } } await this._delegate.fulfill({ status: overrides.status || 200, headers: overrides.headers || [], body, isBase64, }); } async continue(overrides: types.NormalizedContinueOverrides = {}): Promise<InterceptedResponse|null> { assert(!this._handled, 'Route is already handled!'); assert(!this._response, 'Cannot call continue after response interception!'); if (overrides.url) { const newUrl = new URL(overrides.url); const oldUrl = new URL(this._request.url()); if (oldUrl.protocol !== newUrl.protocol) throw new Error('New URL must have same protocol as overridden URL'); } this._response = await this._delegate.continue(this._request, overrides); return this._response; } async responseBody(): Promise<Buffer> { assert(!this._handled, 'Route is already handled!'); return this._delegate.responseBody(); } } export type RouteHandler = (route: Route, request: Request) => void; type GetResponseBodyCallback = () => Promise<Buffer>; export type ResourceTiming = { startTime: number; domainLookupStart: number; domainLookupEnd: number; connectStart: number; secureConnectionStart: number; connectEnd: number; requestStart: number; responseStart: number; }; export type ResourceSizes = { requestBodySize: number, requestHeadersSize: number, responseBodySize: number, responseHeadersSize: number, }; export type RemoteAddr = { ipAddress: string; port: number; }; export type SecurityDetails = { protocol?: string; subjectName?: string; issuer?: string; validFrom?: number; validTo?: number; }; export class Response extends SdkObject { private _request: Request; private _contentPromise: Promise<Buffer> | null = null; _finishedPromise = new ManualPromise<void>(); private _status: number; private _statusText: string; private _url: string; private _headers: types.HeadersArray; private _headersMap = new Map<string, string>(); private _getResponseBodyCallback: GetResponseBodyCallback; private _timing: ResourceTiming; private _serverAddrPromise = new ManualPromise<RemoteAddr | undefined>(); private _securityDetailsPromise = new ManualPromise<SecurityDetails | undefined>(); private _rawRequestHeadersPromise: ManualPromise<types.HeadersArray> | undefined; private _rawResponseHeadersPromise: ManualPromise<types.HeadersArray> | undefined; private _httpVersion: string | undefined; constructor(request: Request, status: number, statusText: string, headers: types.HeadersArray, timing: ResourceTiming, getResponseBodyCallback: GetResponseBodyCallback, httpVersion?: string) { super(request.frame(), 'response'); this._request = request; this._timing = timing; this._status = status; this._statusText = statusText; this._url = request.url(); this._headers = headers; for (const { name, value } of this._headers) this._headersMap.set(name.toLowerCase(), value); this._getResponseBodyCallback = getResponseBodyCallback; this._request._setResponse(this); this._httpVersion = httpVersion; } _serverAddrFinished(addr?: RemoteAddr) { this._serverAddrPromise.resolve(addr); } _securityDetailsFinished(securityDetails?: SecurityDetails) { this._securityDetailsPromise.resolve(securityDetails); } _requestFinished(responseEndTiming: number) { this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart); this._finishedPromise.resolve(); } _setHttpVersion(httpVersion: string) { this._httpVersion = httpVersion; } url(): string { return this._url; } status(): number { return this._status; } statusText(): string { return this._statusText; } headers(): types.HeadersArray { return this._headers; } headerValue(name: string): string | undefined { return this._headersMap.get(name); } async rawRequestHeaders(): Promise<NameValue[]> { return this._rawRequestHeadersPromise || Promise.resolve(this._request._headers); } async rawResponseHeaders(): Promise<NameValue[]> { return this._rawResponseHeadersPromise || Promise.resolve(this._headers); } setWillReceiveExtraHeaders() { this._rawRequestHeadersPromise = new ManualPromise(); this._rawResponseHeadersPromise = new ManualPromise(); } setRawRequestHeaders(headers: types.HeadersArray) { if (!this._rawRequestHeadersPromise) this._rawRequestHeadersPromise = new ManualPromise(); this._rawRequestHeadersPromise!.resolve(headers); } setRawResponseHeaders(headers: types.HeadersArray) { if (!this._rawResponseHeadersPromise) this._rawResponseHeadersPromise = new ManualPromise(); this._rawResponseHeadersPromise!.resolve(headers); } timing(): ResourceTiming { return this._timing; } async serverAddr(): Promise<RemoteAddr|null> { return await this._serverAddrPromise || null; } async securityDetails(): Promise<SecurityDetails|null> { return await this._securityDetailsPromise || null; } body(): Promise<Buffer> { if (!this._contentPromise) { this._contentPromise = this._finishedPromise.then(async () => { if (this._status >= 300 && this._status <= 399) throw new Error('Response body is unavailable for redirect responses'); return this._getResponseBodyCallback(); }); } return this._contentPromise; } request(): Request { return this._request; } frame(): frames.Frame { return this._request.frame(); } httpVersion(): string { if (!this._httpVersion) return 'HTTP/1.1'; if (this._httpVersion === 'http/1.1') return 'HTTP/1.1'; return this._httpVersion; } private async _requestHeadersSize(): Promise<number> { let headersSize = 4; // 4 = 2 spaces + 2 line breaks (GET /path \r\n) headersSize += this._request.method().length; headersSize += (new URL(this.url())).pathname.length; headersSize += 8; // httpVersion const headers = this._rawRequestHeadersPromise ? await this._rawRequestHeadersPromise : this._request._headers; for (const header of headers) headersSize += header.name.length + header.value.length + 4; // 4 = ': ' + '\r\n' return headersSize; } private async _responseHeadersSize(): Promise<number> { let headersSize = 4; // 4 = 2 spaces + 2 line breaks (HTTP/1.1 200 Ok\r\n) headersSize += 8; // httpVersion; headersSize += 3; // statusCode; headersSize += this.statusText().length; const headers = await this._bestEffortResponseHeaders(); for (const header of headers) headersSize += header.name.length + header.value.length + 4; // 4 = ': ' + '\r\n' headersSize += 2; // '\r\n' return headersSize; } private async _bestEffortResponseHeaders(): Promise<types.HeadersArray> { return this._rawResponseHeadersPromise ? await this._rawResponseHeadersPromise : this._headers; } async sizes(): Promise<ResourceSizes> { await this._finishedPromise; const requestHeadersSize = await this._requestHeadersSize(); const responseHeadersSize = await this._responseHeadersSize(); let { encodedBodySize } = this._request.responseSize; if (!encodedBodySize) { const headers = await this._bestEffortResponseHeaders(); const contentLength = headers.find(h => h.name.toLowerCase() === 'content-length')?.value; encodedBodySize = contentLength ? +contentLength : 0; } return { requestBodySize: this._request.bodySize(), requestHeadersSize, responseBodySize: encodedBodySize, responseHeadersSize, }; } } export class InterceptedResponse extends SdkObject { private readonly _request: Request; private readonly _status: number; private readonly _statusText: string; private readonly _headers: types.HeadersArray; constructor(request: Request, status: number, statusText: string, headers: types.HeadersArray) { super(request.frame(), 'interceptedResponse'); this._request = request._finalRequest(); this._status = status; this._statusText = statusText; this._headers = headers; } status(): number { return this._status; } statusText(): string { return this._statusText; } headers(): types.HeadersArray { return this._headers; } request(): Request { return this._request; } } export class WebSocket extends SdkObject { private _url: string; static Events = { Close: 'close', SocketError: 'socketerror', FrameReceived: 'framereceived', FrameSent: 'framesent', }; constructor(parent: SdkObject, url: string) { super(parent, 'ws'); this._url = url; } url(): string { return this._url; } frameSent(opcode: number, data: string) { this.emit(WebSocket.Events.FrameSent, { opcode, data }); } frameReceived(opcode: number, data: string) { this.emit(WebSocket.Events.FrameReceived, { opcode, data }); } error(errorMessage: string) { this.emit(WebSocket.Events.SocketError, errorMessage); } closed() { this.emit(WebSocket.Events.Close); } } export interface RouteDelegate { abort(errorCode: string): Promise<void>; fulfill(response: types.NormalizedFulfillResponse): Promise<void>; continue(request: Request, overrides: types.NormalizedContinueOverrides): Promise<InterceptedResponse|null>; responseBody(): Promise<Buffer>; } // List taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml with extra 306 and 418 codes. export const STATUS_TEXTS: { [status: string]: string } = { '100': 'Continue', '101': 'Switching Protocols', '102': 'Processing', '103': 'Early Hints', '200': 'OK', '201': 'Created', '202': 'Accepted', '203': 'Non-Authoritative Information', '204': 'No Content', '205': 'Reset Content', '206': 'Partial Content', '207': 'Multi-Status', '208': 'Already Reported', '226': 'IM Used', '300': 'Multiple Choices', '301': 'Moved Permanently', '302': 'Found', '303': 'See Other', '304': 'Not Modified', '305': 'Use Proxy', '306': 'Switch Proxy', '307': 'Temporary Redirect', '308': 'Permanent Redirect', '400': 'Bad Request', '401': 'Unauthorized', '402': 'Payment Required', '403': 'Forbidden', '404': 'Not Found', '405': 'Method Not Allowed', '406': 'Not Acceptable', '407': 'Proxy Authentication Required', '408': 'Request Timeout', '409': 'Conflict', '410': 'Gone', '411': 'Length Required', '412': 'Precondition Failed', '413': 'Payload Too Large', '414': 'URI Too Long', '415': 'Unsupported Media Type', '416': 'Range Not Satisfiable', '417': 'Expectation Failed', '418': 'I\'m a teapot', '421': 'Misdirected Request', '422': 'Unprocessable Entity', '423': 'Locked', '424': 'Failed Dependency', '425': 'Too Early', '426': 'Upgrade Required', '428': 'Precondition Required', '429': 'Too Many Requests', '431': 'Request Header Fields Too Large', '451': 'Unavailable For Legal Reasons', '500': 'Internal Server Error', '501': 'Not Implemented', '502': 'Bad Gateway', '503': 'Service Unavailable', '504': 'Gateway Timeout', '505': 'HTTP Version Not Supported', '506': 'Variant Also Negotiates', '507': 'Insufficient Storage', '508': 'Loop Detected', '510': 'Not Extended', '511': 'Network Authentication Required', }; export function singleHeader(name: string, value: string): types.HeadersArray { return [{ name, value }]; } export function mergeHeaders(headers: (types.HeadersArray | undefined | null)[]): types.HeadersArray { const lowerCaseToValue = new Map<string, string>(); const lowerCaseToOriginalCase = new Map<string, string>(); for (const h of headers) { if (!h) continue; for (const { name, value } of h) { const lower = name.toLowerCase(); lowerCaseToOriginalCase.set(lower, name); lowerCaseToValue.set(lower, value); } } const result: types.HeadersArray = []; for (const [lower, value] of lowerCaseToValue) result.push({ name: lowerCaseToOriginalCase.get(lower)!, value }); return result; }
src/server/network.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.002574580255895853, 0.0003077954752370715, 0.0001641217531869188, 0.00017208812641911209, 0.0004356475837994367 ]
{ "id": 8, "code_window": [ " validTo: responseReceivedPayload?.response.security?.certificate?.validUntil,\n", " });\n", " if (event.metrics?.protocol)\n", " response._setHttpVersion(event.metrics.protocol);\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (event.metrics?.responseBodyBytesReceived)\n", " request.request.responseSize.encodedBodySize = event.metrics.responseBodyBytesReceived;\n", " if (event.metrics?.responseHeaderBytesReceived)\n", " request.request.responseSize.responseHeadersSize = event.metrics.responseHeaderBytesReceived;\n", "\n" ], "file_path": "src/server/webkit/wkPage.ts", "type": "add", "edit_start_line_idx": 1000 }
name: "infra" on: push: branches: - master - release-* pull_request: branches: - master - release-* jobs: doc-and-lint: name: "docs & lint" runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: 12 - run: npm ci - run: npm run build - run: node lib/cli/cli install-deps - run: npm run lint - name: Verify clean tree run: | if [[ -n $(git status -s) ]]; then echo "ERROR: tree is dirty after npm run build:" git diff exit 1 fi
.github/workflows/infra.yml
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017751411360222846, 0.00017457963258493692, 0.00017105256847571582, 0.00017487590957898647, 0.0000023093855361366877 ]