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": 7, "code_window": [ " }),\n", " );\n", " });\n", " });\n", " describe('getModuleName', () => {\n", " it('should map module metatype to name', () => {\n", " const metatype = () => {};\n", " expect(factory.getModuleName(metatype as any)).to.be.eql(metatype.name);\n", " });\n", " });\n", " describe('getDynamicMetadataToken', () => {\n", " describe('when metadata exists', () => {\n", " it('should return hash', () => {\n", " const metadata = { providers: ['', {}] };\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/injector/module-token-factory.spec.ts", "type": "replace", "edit_start_line_idx": 53 }
import { Injectable } from '@nestjs/common'; import { Cat } from './interfaces/cat.interface'; @Injectable() export class CatsService { static COUNTER = 0; private readonly cats: Cat[] = [{ id: 1, name: 'Cat', age: 5 }]; constructor() { CatsService.COUNTER++; } create(cat: Cat): Cat { this.cats.push(cat); return cat; } findAll(): Cat[] { return this.cats; } findOneById(id: number): Cat { return this.cats.find(cat => cat.id === id); } }
integration/graphql/src/cats/cats.service.ts
0
https://github.com/nestjs/nest/commit/ed3da85252fef246c73b5bc120fb218018a5abf9
[ 0.00017620516882743686, 0.00017389829736202955, 0.00017058236699085683, 0.00017490735626779497, 0.0000024038336050580256 ]
{ "id": 7, "code_window": [ " }),\n", " );\n", " });\n", " });\n", " describe('getModuleName', () => {\n", " it('should map module metatype to name', () => {\n", " const metatype = () => {};\n", " expect(factory.getModuleName(metatype as any)).to.be.eql(metatype.name);\n", " });\n", " });\n", " describe('getDynamicMetadataToken', () => {\n", " describe('when metadata exists', () => {\n", " it('should return hash', () => {\n", " const metadata = { providers: ['', {}] };\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/injector/module-token-factory.spec.ts", "type": "replace", "edit_start_line_idx": 53 }
export const longPayload = [ { _id: '584f17147fce7ca0a8bacfd2', index: 0, guid: '1d127572-0369-45fb-aa2f-e3bb083ac2b2', isActive: true, balance: '$2,926.06', picture: 'http://placehold.it/32x32', age: 26, eyeColor: 'green', name: 'Wçêtson Aguilar [special characters in name that used to fail on long payloads]', gender: 'male', company: 'PROWASTE', email: '[email protected]', phone: '+1 (821) 517-2430', address: '910 Robert Street, Bangor, Delaware, 4159', about: 'Aliqua et irure id do id id non dolore ipsum sit in proident ipsum. Id elit incididunt occaecat do laboris sunt officia fugiat aliquip. Incididunt aute ad minim Lorem cupidatat aute labore enim elit nostrud amet. Tempor sint irure incididunt aliquip amet sunt mollit aliqua Lorem officia pariatur.\r\n', registered: '2014-02-11T08:45:28 +05:00', latitude: 73.891198, longitude: 90.23414, tags: ['veniam', 'nulla', 'cillum', 'tempor', 'sint', 'magna', 'nostrud'], friends: [ { id: 0, name: 'Cecelia James', }, { id: 1, name: 'Hilary Young', }, { id: 2, name: 'Sharron Goodwin', }, ], greeting: 'Hello, Watson Aguilar! You have 3 unread messages.', favoriteFruit: 'banana', }, { _id: '584f1714b2e945fb30f73892', index: 1, guid: '3ffce1ee-a442-4dae-804f-40c59f19e7ee', isActive: false, balance: '$2,507.49', picture: 'http://placehold.it/32x32', age: 34, eyeColor: 'brown', name: 'Aguirre Salazar', gender: 'male', company: 'EZENTIA', email: '[email protected]', phone: '+1 (910) 443-3647', address: '629 Burnett Street, Tyhee, West Virginia, 2905', about: 'Labore laboris et deserunt aliquip. Occaecat esse officia est eiusmod. Officia tempor cupidatat commodo minim deserunt mollit qui ut culpa. Est occaecat laborum occaecat non mollit ad reprehenderit magna ad. Consequat culpa excepteur qui aliqua dolore occaecat aliqua sunt elit ea nisi. Officia consectetur dolor labore voluptate. Esse ad esse qui id incididunt.\r\n', registered: '2015-01-28T06:47:34 +05:00', latitude: -64.632254, longitude: -116.659127, tags: [ 'sit', 'anim', 'quis', 'officia', 'minim', 'cupidatat', 'adipisicing', ], friends: [ { id: 0, name: 'Olson Mccall', }, { id: 1, name: 'Carolina Conway', }, { id: 2, name: 'Carlson Pacheco', }, ], greeting: 'Hello, Aguirre Salazar! You have 9 unread messages.', favoriteFruit: 'apple', }, { _id: '584f17148282bb876fc4e9a2', index: 2, guid: '892ba80c-7149-4904-bd36-22f619d4df0a', isActive: true, balance: '$2,132.56', picture: 'http://placehold.it/32x32', age: 26, eyeColor: 'green', name: 'Hardin Grant', gender: 'male', company: 'CINASTER', email: '[email protected]', phone: '+1 (900) 437-2390', address: '180 Ide Court, Gibsonia, Washington, 3027', about: 'Ut aliquip officia adipisicing voluptate aliquip aute fugiat ad quis ad eu non consectetur. Laboris labore veniam officia qui eiusmod. Duis aliqua est quis do dolor excepteur ea dolore non. Nisi mollit laboris nostrud nostrud pariatur culpa laboris anim est irure id aute.\r\n', registered: '2016-09-13T10:54:27 +04:00', latitude: 8.651031, longitude: -136.777747, tags: ['consequat', 'deserunt', 'magna', 'enim', 'esse', 'minim', 'ipsum'], friends: [ { id: 0, name: 'Lesley Velasquez', }, { id: 1, name: 'Natasha Simmons', }, { id: 2, name: 'Isabel Avery', }, ], greeting: 'Hello, Hardin Grant! You have 7 unread messages.', favoriteFruit: 'strawberry', }, { _id: '584f1714d90ff4b8914a69e7', index: 3, guid: '76f37726-1f73-4cf7-aabe-8dadf37d3ddd', isActive: true, balance: '$2,493.04', picture: 'http://placehold.it/32x32', age: 32, eyeColor: 'blue', name: 'Randall Roy', gender: 'male', company: 'ZAJ', email: '[email protected]', phone: '+1 (938) 562-2214', address: '872 Rugby Road, Hoehne, Indiana, 9792', about: 'Non laboris id et cupidatat velit ea ipsum ea mollit quis qui dolore nisi laboris. Enim sit irure enim dolor velit proident sunt pariatur proident consequat mollit enim minim. Laboris deserunt cupidatat nisi enim adipisicing officia dolore ex cupidatat anim. Cupidatat labore voluptate non magna est dolor. Occaecat occaecat magna anim laborum adipisicing esse excepteur cillum aute qui eu do excepteur eu. Nostrud consectetur consectetur aliquip deserunt velit culpa sint excepteur mollit nostrud sit ex. Est ex ut laboris pariatur.\r\n', registered: '2016-05-05T05:24:56 +04:00', latitude: 18.943281, longitude: -110.942673, tags: [ 'eu', 'aliqua', 'reprehenderit', 'amet', 'nulla', 'consequat', 'nisi', ], friends: [ { id: 0, name: 'Barron Maynard', }, { id: 1, name: 'Lynn Shepard', }, { id: 2, name: 'Robin Whitehead', }, ], greeting: 'Hello, Randall Roy! You have 3 unread messages.', favoriteFruit: 'strawberry', }, { _id: '584f17142a8f47cef0f5401a', index: 4, guid: '9b50ec22-3fbe-40ce-a5b8-b956f1340a77', isActive: false, balance: '$3,234.48', picture: 'http://placehold.it/32x32', age: 33, eyeColor: 'green', name: 'Chandler Vasquez', gender: 'male', company: 'ZILLACTIC', email: '[email protected]', phone: '+1 (830) 550-3428', address: '610 Hunts Lane, Cazadero, Michigan, 3584', about: 'Fugiat in anim adipisicing sint aliquip ea velit do proident eu ad amet. Nulla velit duis ullamco labore ea Lorem velit elit Lorem. Id laboris do mollit exercitation veniam do amet culpa est excepteur reprehenderit consectetur laborum.\r\n', registered: '2014-04-20T05:23:32 +04:00', latitude: -88.088841, longitude: -163.602482, tags: [ 'sunt', 'excepteur', 'enim', 'incididunt', 'officia', 'amet', 'irure', ], friends: [ { id: 0, name: 'Mckee Norton', }, { id: 1, name: 'Durham Parrish', }, { id: 2, name: 'Stewart Kramer', }, ], greeting: 'Hello, Chandler Vasquez! You have 3 unread messages.', favoriteFruit: 'strawberry', }, { _id: '584f171450a4e9dda687adc5', index: 5, guid: '68eeea45-ba6e-4740-b89b-10d690c37a02', isActive: false, balance: '$3,771.46', picture: 'http://placehold.it/32x32', age: 25, eyeColor: 'blue', name: 'Fernandez Caldwell', gender: 'male', company: 'SNIPS', email: '[email protected]', phone: '+1 (911) 544-3684', address: '786 Newel Street, Elliston, Massachusetts, 6683', about: 'Voluptate commodo labore aliqua excepteur irure aliquip officia. Incididunt excepteur elit quis reprehenderit voluptate aliqua ad voluptate duis nisi dolor dolor id dolor. Irure sit consequat amet ea magna laborum velit eu in. Sunt occaecat quis consectetur laboris. Duis est do eu consectetur dolore id incididunt incididunt ut esse magna est. Nostrud irure magna nulla fugiat deserunt deserunt enim mollit proident qui sint dolore incididunt. Incididunt incididunt do quis culpa sint ut aliqua id.\r\n', registered: '2015-08-09T09:02:36 +04:00', latitude: -46.941347, longitude: -171.796168, tags: [ 'sit', 'irure', 'reprehenderit', 'ut', 'proident', 'aliquip', 'labore', ], friends: [ { id: 0, name: 'Adela Preston', }, { id: 1, name: 'Phillips Moses', }, { id: 2, name: 'Neva Wise', }, ], greeting: 'Hello, Fernandez Caldwell! You have 10 unread messages.', favoriteFruit: 'apple', }, ];
packages/microservices/test/json-socket/data/long-payload-with-special-chars.ts
0
https://github.com/nestjs/nest/commit/ed3da85252fef246c73b5bc120fb218018a5abf9
[ 0.00018060482398141176, 0.00017566599126439542, 0.0001708195050014183, 0.00017544854199513793, 0.0000025848985387710854 ]
{ "id": 0, "code_window": [ "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\t\tthis.setState(State.Idle);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.004428771324455738, 0.0004768841026816517, 0.00016439976752735674, 0.0001762254978530109, 0.0008637780556455255 ]
{ "id": 0, "code_window": [ "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\t\tthis.setState(State.Idle);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "replace", "edit_start_line_idx": 86 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ] }
i18n/ptb/extensions/package-json/package.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017723269411362708, 0.00017723269411362708, 0.00017723269411362708, 0.00017723269411362708, 0 ]
{ "id": 0, "code_window": [ "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\t\tthis.setState(State.Idle);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "replace", "edit_start_line_idx": 86 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "noResultsMatching": "没有匹配的结果", "noResultsFound2": "未找到结果" }
i18n/chs/src/vs/workbench/browser/quickopen.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017863714310806245, 0.00017725740326568484, 0.00017587767797522247, 0.00017725740326568484, 0.0000013797326801068266 ]
{ "id": 0, "code_window": [ "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\t\tthis.setState(State.Idle);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "replace", "edit_start_line_idx": 86 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "strict.title": "Строгий", "strict.description": "Загружать только безопасное содержимое", "insecureContent.title": "Разрешить небезопасное содержимое", "insecureContent.description": "Включить загрузку содержимого через HTTP", "disable.title": "Отключить", "disable.description": "Разрешить все содержимое и выполнение сценариев. Не рекомендуется", "moreInfo.title": "Дополнительные сведения", "enableSecurityWarning.title": "Включить предварительный просмотр предупреждений системы безопасности в этой рабочей области", "disableSecurityWarning.title": "Отключить предварительный просмотр предупреждений системы безопасности в этой рабочей области", "toggleSecurityWarning.description": "Не влияет на уровень безопасности содержимого", "preview.showPreviewSecuritySelector.title": "Установите параметры безопасности для предварительного просмотра Markdown в этой рабочей области" }
i18n/rus/extensions/markdown/out/security.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0012326632859185338, 0.0005284753278829157, 0.0001743593456922099, 0.00017840341024566442, 0.0004979388322681189 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "}" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.setState(State.Idle);\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "add", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.4759177565574646, 0.02147515118122101, 0.00016294447414111346, 0.00016881573537830263, 0.09690319001674652 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "}" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.setState(State.Idle);\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "add", "edit_start_line_idx": 88 }
{ "name": "typescript-language-features", "description": "%description%", "displayName": "%displayName%", "version": "1.0.0", "icon": "icon.png", "author": "vscode", "publisher": "vscode", "license": "MIT", "aiKey": "AIF-d9b70cd4-b9f9-4d70-929b-a071c400b217", "enableProposedApi": true, "engines": { "vscode": "*" }, "categories": [ "Programming Languages" ], "dependencies": { "semver": "4.3.6", "vscode-extension-telemetry": "0.0.17", "vscode-nls": "^3.2.1" }, "devDependencies": { "@types/node": "8.0.33", "@types/semver": "5.4.0", "vscode": "^1.1.10" }, "scripts": { "vscode:prepublish": "node ../../node_modules/gulp/bin/gulp.js --gulpfile ../../build/gulpfile.extensions.js compile-extension:typescript ./tsconfig.json" }, "activationEvents": [ "onLanguage:javascript", "onLanguage:javascriptreact", "onLanguage:typescript", "onLanguage:typescriptreact", "onLanguage:jsx-tags", "onCommand:typescript.reloadProjects", "onCommand:javascript.reloadProjects", "onCommand:typescript.selectTypeScriptVersion", "onCommand:javascript.goToProjectConfig", "onCommand:typescript.goToProjectConfig", "onCommand:typescript.openTsServerLog", "onCommand:workbench.action.tasks.runTask" ], "main": "./out/extension", "contributes": { "jsonValidation": [ { "fileMatch": "package.json", "url": "./schemas/package.schema.json" } ], "configuration": { "type": "object", "title": "%configuration.typescript%", "order": 20, "properties": { "typescript.tsdk": { "type": [ "string", "null" ], "default": null, "description": "%typescript.tsdk.desc%", "scope": "window" }, "typescript.disableAutomaticTypeAcquisition": { "type": "boolean", "default": false, "description": "%typescript.disableAutomaticTypeAcquisition%", "scope": "window" }, "typescript.npm": { "type": [ "string", "null" ], "default": null, "description": "%typescript.npm%", "scope": "application" }, "typescript.check.npmIsInstalled": { "type": "boolean", "default": true, "description": "%typescript.check.npmIsInstalled%", "scope": "window" }, "javascript.referencesCodeLens.enabled": { "type": "boolean", "default": false, "description": "%javascript.referencesCodeLens.enabled%", "scope": "window" }, "typescript.referencesCodeLens.enabled": { "type": "boolean", "default": false, "description": "%typescript.referencesCodeLens.enabled%", "scope": "window" }, "typescript.implementationsCodeLens.enabled": { "type": "boolean", "default": false, "description": "%typescript.implementationsCodeLens.enabled%", "scope": "window" }, "typescript.tsserver.log": { "type": "string", "enum": [ "off", "terse", "normal", "verbose" ], "default": "off", "description": "%typescript.tsserver.log%", "scope": "window" }, "typescript.tsserver.pluginPaths": { "type": "array", "items": { "type": "string", "description": "%typescript.tsserver.pluginPaths.item%" }, "default": [], "description": "%typescript.tsserver.pluginPaths%", "scope": "application" }, "typescript.tsserver.trace": { "type": "string", "enum": [ "off", "messages", "verbose" ], "default": "off", "description": "%typescript.tsserver.trace%", "scope": "window" }, "typescript.useCodeSnippetsOnMethodSuggest": { "type": "boolean", "default": false, "description": "%typescript.useCodeSnippetsOnMethodSuggest.dec%", "scope": "resource" }, "typescript.reportStyleChecksAsWarnings": { "type": "boolean", "default": true, "description": "%typescript.reportStyleChecksAsWarnings%", "scope": "window" }, "typescript.validate.enable": { "type": "boolean", "default": true, "description": "%typescript.validate.enable%", "scope": "window" }, "typescript.format.enable": { "type": "boolean", "default": true, "description": "%typescript.format.enable%", "scope": "window" }, "typescript.format.insertSpaceAfterCommaDelimiter": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterCommaDelimiter%", "scope": "resource" }, "typescript.format.insertSpaceAfterConstructor": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterConstructor%", "scope": "resource" }, "typescript.format.insertSpaceAfterSemicolonInForStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterSemicolonInForStatements%", "scope": "resource" }, "typescript.format.insertSpaceBeforeAndAfterBinaryOperators": { "type": "boolean", "default": true, "description": "%format.insertSpaceBeforeAndAfterBinaryOperators%", "scope": "resource" }, "typescript.format.insertSpaceAfterKeywordsInControlFlowStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterKeywordsInControlFlowStatements%", "scope": "resource" }, "typescript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterFunctionKeywordForAnonymousFunctions%", "scope": "resource" }, "typescript.format.insertSpaceBeforeFunctionParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceBeforeFunctionParenthesis%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterTypeAssertion": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterTypeAssertion%", "scope": "resource" }, "typescript.format.placeOpenBraceOnNewLineForFunctions": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForFunctions%", "scope": "resource" }, "typescript.format.placeOpenBraceOnNewLineForControlBlocks": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForControlBlocks%", "scope": "resource" }, "javascript.validate.enable": { "type": "boolean", "default": true, "description": "%javascript.validate.enable%", "scope": "window" }, "javascript.format.enable": { "type": "boolean", "default": true, "description": "%javascript.format.enable%", "scope": "window" }, "javascript.format.insertSpaceAfterCommaDelimiter": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterCommaDelimiter%", "scope": "resource" }, "javascript.format.insertSpaceAfterConstructor": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterConstructor%", "scope": "resource" }, "javascript.format.insertSpaceAfterSemicolonInForStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterSemicolonInForStatements%", "scope": "resource" }, "javascript.format.insertSpaceBeforeAndAfterBinaryOperators": { "type": "boolean", "default": true, "description": "%format.insertSpaceBeforeAndAfterBinaryOperators%", "scope": "resource" }, "javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterKeywordsInControlFlowStatements%", "scope": "resource" }, "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterFunctionKeywordForAnonymousFunctions%", "scope": "resource" }, "javascript.format.insertSpaceBeforeFunctionParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceBeforeFunctionParenthesis%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces%", "scope": "resource" }, "javascript.format.placeOpenBraceOnNewLineForFunctions": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForFunctions%", "scope": "resource" }, "javascript.format.placeOpenBraceOnNewLineForControlBlocks": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForControlBlocks%", "scope": "resource" }, "jsDocCompletion.enabled": { "type": "boolean", "default": true, "description": "%jsDocCompletion.enabled%", "scope": "resource" }, "javascript.implicitProjectConfig.checkJs": { "type": "boolean", "default": false, "description": "%javascript.implicitProjectConfig.checkJs%", "scope": "window" }, "javascript.implicitProjectConfig.experimentalDecorators": { "type": "boolean", "default": false, "description": "%javascript.implicitProjectConfig.experimentalDecorators%", "scope": "window" }, "javascript.nameSuggestions": { "type": "boolean", "default": true, "description": "%javascript.nameSuggestions%", "scope": "resource" }, "typescript.tsc.autoDetect": { "type": "string", "default": "on", "enum": [ "on", "off", "build", "watch" ], "description": "%typescript.tsc.autoDetect%", "scope": "window" }, "typescript.quickSuggestionsForPaths": { "type": "boolean", "default": true, "description": "%typescript.quickSuggestionsForPaths%", "scope": "resource" }, "typescript.autoImportSuggestions.enabled": { "type": "boolean", "default": true, "description": "%typescript.autoImportSuggestions.enabled%", "scope": "resource" }, "typescript.locale": { "type": [ "string", "null" ], "enum": [ "de", "es", "en", "fr", "it", "ja", "ko", "ru", "zh-CN", "zh-TW", null ], "default": null, "description": "%typescript.locale%", "scope": "window" }, "javascript.suggestionActions.enabled": { "type": "boolean", "default": true, "description": "%javascript.suggestionActions.enabled%", "scope": "resource" }, "typescript.suggestionActions.enabled": { "type": "boolean", "default": true, "description": "%typescript.suggestionActions.enabled%", "scope": "resource" }, "javascript.preferences.quoteStyle": { "type": "string", "enum": [ "auto", "single", "double" ], "default": "auto", "description": "%typescript.preferences.quoteStyle%", "scope": "resource" }, "typescript.preferences.quoteStyle": { "type": "string", "enum": [ "auto", "single", "double" ], "default": "auto", "description": "%typescript.preferences.quoteStyle%", "scope": "resource" }, "javascript.preferences.importModuleSpecifier": { "type": "string", "enum": [ "auto", "relative", "non-relative" ], "default": "auto", "description": "%typescript.preferences.importModuleSpecifier%", "scope": "resource" }, "typescript.preferences.importModuleSpecifier": { "type": "string", "enum": [ "auto", "relative", "non-relative" ], "default": "auto", "description": "%typescript.preferences.importModuleSpecifier%", "scope": "resource" }, "javascript.showUnused": { "type": "boolean", "default": true, "description": "%typescript.showUnused%", "scope": "resource" }, "typescript.showUnused": { "type": "boolean", "default": true, "description": "%typescript.showUnused%", "scope": "resource" }, "typescript.updateImportsOnFileMove.enabled": { "type": "string", "enum": [ "prompt", "always", "never" ], "default": "prompt", "description": "%typescript.updateImportsOnFileMove.enabled%", "scope": "resource" }, "javascript.updateImportsOnFileMove.enabled": { "type": "string", "enum": [ "prompt", "always", "never" ], "default": "prompt", "description": "%typescript.updateImportsOnFileMove.enabled%", "scope": "resource" } } }, "commands": [ { "command": "typescript.reloadProjects", "title": "%reloadProjects.title%", "category": "TypeScript" }, { "command": "javascript.reloadProjects", "title": "%reloadProjects.title%", "category": "JavaScript" }, { "command": "typescript.selectTypeScriptVersion", "title": "%typescript.selectTypeScriptVersion.title%", "category": "TypeScript" }, { "command": "typescript.goToProjectConfig", "title": "%goToProjectConfig.title%", "category": "TypeScript" }, { "command": "javascript.goToProjectConfig", "title": "%goToProjectConfig.title%", "category": "JavaScript" }, { "command": "typescript.openTsServerLog", "title": "%typescript.openTsServerLog.title%", "category": "TypeScript" }, { "command": "typescript.restartTsServer", "title": "%typescript.restartTsServer%", "category": "TypeScript" } ], "menus": { "commandPalette": [ { "command": "typescript.reloadProjects", "when": "editorLangId == typescript && typescript.isManagedFile" }, { "command": "typescript.reloadProjects", "when": "editorLangId == typescriptreact && typescript.isManagedFile" }, { "command": "javascript.reloadProjects", "when": "editorLangId == javascript && typescript.isManagedFile" }, { "command": "javascript.reloadProjects", "when": "editorLangId == javascriptreact && typescript.isManagedFile" }, { "command": "typescript.goToProjectConfig", "when": "editorLangId == typescript && typescript.isManagedFile" }, { "command": "typescript.goToProjectConfig", "when": "editorLangId == typescriptreact" }, { "command": "javascript.goToProjectConfig", "when": "editorLangId == javascript && typescript.isManagedFile" }, { "command": "javascript.goToProjectConfig", "when": "editorLangId == javascriptreact && typescript.isManagedFile" }, { "command": "typescript.selectTypeScriptVersion", "when": "typescript.isManagedFile" }, { "command": "typescript.openTsServerLog", "when": "typescript.isManagedFile" }, { "command": "typescript.restartTsServer", "when": "typescript.isManagedFile" } ] }, "breakpoints": [ { "language": "typescript" }, { "language": "typescriptreact" } ], "taskDefinitions": [ { "type": "typescript", "required": [ "tsconfig" ], "properties": { "tsconfig": { "type": "string", "description": "%taskDefinition.tsconfig.description%" }, "option": { "type": "string" } } } ], "problemPatterns": [ { "name": "tsc", "regexp": "^([^\\s].*)[\\(:](\\d+)[,:](\\d+)(?:\\):\\s+|\\s+-\\s+)(error|warning|info)\\s+(TS\\d+)\\s*:\\s*(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "code": 5, "message": 6 } ], "problemMatchers": [ { "name": "tsc", "label": "%typescript.problemMatchers.tsc.label%", "owner": "typescript", "source": "ts", "applyTo": "closedDocuments", "fileLocation": [ "relative", "${cwd}" ], "pattern": "$tsc" }, { "name": "tsc-watch", "label": "%typescript.problemMatchers.tscWatch.label%", "owner": "typescript", "source": "ts", "applyTo": "closedDocuments", "fileLocation": [ "relative", "${cwd}" ], "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "^\\s*(?:message TS6032:|\\[?\\d{1,2}:\\d{1,2}:\\d{1,2}(?: AM| PM| a\\.m\\.| p\\.m\\.)?(?:\\]| -)) File change detected\\. Starting incremental compilation\\.\\.\\." }, "endsPattern": { "regexp": "^\\s*(?:message TS6042:|\\[?\\d{1,2}:\\d{1,2}:\\d{1,2}(?: AM| PM| a\\.m\\.| p\\.m\\.)?(?:\\]| -)) (?:Compilation complete\\.|Found \\d+ errors?\\.) Watching for file changes\\." } } } ] } }
extensions/typescript-language-features/package.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00040385444299317896, 0.00017640356963966042, 0.0001645311713218689, 0.0001667017349973321, 0.00003429113712627441 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "}" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.setState(State.Idle);\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "add", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import { Selection, workspace, ConfigurationTarget } from 'vscode'; import { withRandomFileEditor, closeAllEditors } from './testUtils'; import { removeTag } from '../removeTag'; import { updateTag } from '../updateTag'; import { matchTag } from '../matchTag'; import { splitJoinTag } from '../splitJoinTag'; import { mergeLines } from '../mergeLines'; suite('Tests for Emmet actions on html tags', () => { teardown(() => { // close all editors return closeAllEditors; }); const contents = ` <div class="hello"> <ul> <li><span>Hello</span></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> </ul> <span/> </div> `; let contentsWithTemplate = ` <script type="text/template"> <ul> <li><span>Hello</span></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> </ul> <span/> </script> `; test('update tag with multiple cursors', () => { const expectedContents = ` <div class="hello"> <ul> <li><section>Hello</section></li> <section><span>There</span></section> <section><li><span>Bye</span></li></section> </ul> <span/> </div> `; return withRandomFileEditor(contents, 'html', (editor, doc) => { editor.selections = [ new Selection(3, 17, 3, 17), // cursor inside tags new Selection(4, 5, 4, 5), // cursor inside opening tag new Selection(5, 35, 5, 35), // cursor inside closing tag ]; return updateTag('section')!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('update tag with template', () => { const expectedContents = ` <script type="text/template"> <section> <li><span>Hello</span></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> </section> <span/> </script> `; return withRandomFileEditor(contentsWithTemplate, 'html', (editor, doc) => { editor.selections = [ new Selection(2, 4, 2, 4), // cursor inside ul tag ]; return updateTag('section')!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('remove tag with mutliple cursors', () => { const expectedContents = ` <div class="hello"> <ul> <li>Hello</li> <span>There</span> <li><span>Bye</span></li> </ul> <span/> </div> `; return withRandomFileEditor(contents, 'html', (editor, doc) => { editor.selections = [ new Selection(3, 17, 3, 17), // cursor inside tags new Selection(4, 5, 4, 5), // cursor inside opening tag new Selection(5, 35, 5, 35), // cursor inside closing tag ]; return removeTag()!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('remove tag with template', () => { const expectedContents = ` <script type="text/template"> \t\t <li><span>Hello</span></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> \t <span/> </script> `; return withRandomFileEditor(contentsWithTemplate, 'html', (editor, doc) => { editor.selections = [ new Selection(2, 4, 2, 4), // cursor inside ul tag ]; return removeTag()!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('split/join tag with mutliple cursors', () => { const expectedContents = ` <div class="hello"> <ul> <li><span/></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> </ul> <span></span> </div> `; return withRandomFileEditor(contents, 'html', (editor, doc) => { editor.selections = [ new Selection(3, 17, 3, 17), // join tag new Selection(7, 5, 7, 5), // split tag ]; return splitJoinTag()!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('split/join tag with templates', () => { const expectedContents = ` <script type="text/template"> <ul> <li><span/></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> </ul> <span></span> </script> `; return withRandomFileEditor(contentsWithTemplate, 'html', (editor, doc) => { editor.selections = [ new Selection(3, 17, 3, 17), // join tag new Selection(7, 5, 7, 5), // split tag ]; return splitJoinTag()!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('split/join tag in jsx with xhtml self closing tag', () => { const expectedContents = ` <div class="hello"> <ul> <li><span /></li> <li><span>There</span></li> <div><li><span>Bye</span></li></div> </ul> <span></span> </div> `; const oldValueForSyntaxProfiles = workspace.getConfiguration('emmet').inspect('syntaxProfiles'); return workspace.getConfiguration('emmet').update('syntaxProfiles', { jsx: { selfClosingStyle: 'xhtml' } }, ConfigurationTarget.Global).then(() => { return withRandomFileEditor(contents, 'jsx', (editor, doc) => { editor.selections = [ new Selection(3, 17, 3, 17), // join tag new Selection(7, 5, 7, 5), // split tag ]; return splitJoinTag()!.then(() => { assert.equal(doc.getText(), expectedContents); return workspace.getConfiguration('emmet').update('syntaxProfiles', oldValueForSyntaxProfiles ? oldValueForSyntaxProfiles.globalValue : undefined, ConfigurationTarget.Global); }); }); }); }); test('match tag with mutliple cursors', () => { return withRandomFileEditor(contents, 'html', (editor, doc) => { editor.selections = [ new Selection(1, 0, 1, 0), // just before tag starts, i.e before < new Selection(1, 1, 1, 1), // just before tag name starts new Selection(1, 2, 1, 2), // inside tag name new Selection(1, 6, 1, 6), // after tag name but before opening tag ends new Selection(1, 18, 1, 18), // just before opening tag ends new Selection(1, 19, 1, 19), // just after opening tag ends ]; matchTag(); editor.selections.forEach(selection => { assert.equal(selection.active.line, 8); assert.equal(selection.active.character, 3); assert.equal(selection.anchor.line, 8); assert.equal(selection.anchor.character, 3); }); return Promise.resolve(); }); }); test('match tag with template scripts', () => { let templateScript = ` <script type="text/template"> <div> Hello </div> </script>`; return withRandomFileEditor(templateScript, 'html', (editor, doc) => { editor.selections = [ new Selection(2, 2, 2, 2), // just before div tag starts, i.e before < ]; matchTag(); editor.selections.forEach(selection => { assert.equal(selection.active.line, 4); assert.equal(selection.active.character, 4); assert.equal(selection.anchor.line, 4); assert.equal(selection.anchor.character, 4); }); return Promise.resolve(); }); }); test('merge lines of tag with children when empty selection', () => { const expectedContents = ` <div class="hello"> <ul><li><span>Hello</span></li><li><span>There</span></li><div><li><span>Bye</span></li></div></ul> <span/> </div> `; return withRandomFileEditor(contents, 'html', (editor, doc) => { editor.selections = [ new Selection(2, 3, 2, 3) ]; return mergeLines()!.then(() => { assert.equal(doc.getText(), expectedContents); return Promise.resolve(); }); }); }); test('merge lines is no-op when start and end nodes are on the same line', () => { return withRandomFileEditor(contents, 'html', (editor, doc) => { editor.selections = [ new Selection(3, 9, 3, 9), // cursor is inside the <span> in <li><span>Hello</span></li> new Selection(4, 5, 4, 5), // cursor is inside the <li> in <li><span>Hello</span></li> new Selection(5, 5, 5, 20) // selection spans multiple nodes in the same line ]; return mergeLines()!.then(() => { assert.equal(doc.getText(), contents); return Promise.resolve(); }); }); }); });
extensions/emmet/src/test/tagActions.test.ts
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0003010689397342503, 0.00017233846301678568, 0.0001635532535146922, 0.0001677378168096766, 0.000023634751414647326 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "}" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.setState(State.Idle);\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.linux.ts", "type": "add", "edit_start_line_idx": 88 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "output": "{0} - Ausgabe", "channel": "Ausgabekanal für '{0}'" }
i18n/deu/src/vs/workbench/parts/output/electron-browser/outputServices.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0001789114176062867, 0.00017610607028473169, 0.00017330072296317667, 0.00017610607028473169, 0.0000028053473215550184 ]
{ "id": 2, "code_window": [ "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';\n", "import { IRequestService } from 'vs/platform/request/node/request';\n", "import product from 'vs/platform/node/product';\n", "import { TPromise, Promise } from 'vs/base/common/winjs.base';\n", "import { State, IUpdate, StateType } from 'vs/platform/update/common/update';\n", "import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n", "import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { State, IUpdate, StateType, AvailableForDownload } from 'vs/platform/update/common/update';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.9958956241607666, 0.04408400505781174, 0.00016462251369375736, 0.00018406166054774076, 0.20293693244457245 ]
{ "id": 2, "code_window": [ "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';\n", "import { IRequestService } from 'vs/platform/request/node/request';\n", "import product from 'vs/platform/node/product';\n", "import { TPromise, Promise } from 'vs/base/common/winjs.base';\n", "import { State, IUpdate, StateType } from 'vs/platform/update/common/update';\n", "import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n", "import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { State, IUpdate, StateType, AvailableForDownload } from 'vs/platform/update/common/update';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------- The base color for this template is #5c87b2. If you'd like to use a different color start by replacing all instances of #5c87b2 with your new color. ----------------------------------------------------------*/ body { background-color: #5c87b2; font-size: .75em; font-family: Segoe UI, Verdana, Helvetica, Sans-Serif; margin: 8px; padding: 0; color: #696969; } h1, h2, h3, h4, h5, h6 { color: #000; font-size: 40px; margin: 0px; } textarea { font-family: Consolas } #results { margin-top: 2em; margin-left: 2em; color: black; font-size: medium; }
src/vs/workbench/services/files/test/electron-browser/fixtures/resolver/site.css
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017663443577475846, 0.00017451176245231181, 0.00016964900714810938, 0.00017527966701891273, 0.0000025380534225405427 ]
{ "id": 2, "code_window": [ "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';\n", "import { IRequestService } from 'vs/platform/request/node/request';\n", "import product from 'vs/platform/node/product';\n", "import { TPromise, Promise } from 'vs/base/common/winjs.base';\n", "import { State, IUpdate, StateType } from 'vs/platform/update/common/update';\n", "import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n", "import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { State, IUpdate, StateType, AvailableForDownload } from 'vs/platform/update/common/update';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * 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. { "previousEditPoint": "Emmet: Ugrás az előző szerkesztési pontra", "nextEditPoint": "Emmet: Ugrás a következő szerkesztési pontra" }
i18n/hun/src/vs/workbench/parts/emmet/electron-browser/actions/editPoints.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017637660494074225, 0.00017637660494074225, 0.00017637660494074225, 0.00017637660494074225, 0 ]
{ "id": 2, "code_window": [ "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';\n", "import { IRequestService } from 'vs/platform/request/node/request';\n", "import product from 'vs/platform/node/product';\n", "import { TPromise, Promise } from 'vs/base/common/winjs.base';\n", "import { State, IUpdate, StateType } from 'vs/platform/update/common/update';\n", "import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n", "import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { State, IUpdate, StateType, AvailableForDownload } from 'vs/platform/update/common/update';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 16 }
{ "compilerOptions": { "module": "amd", "moduleResolution": "classic", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "target": "es5", "sourceMap": false, "experimentalDecorators": true, "declaration": true, "noImplicitReturns": true, "noUnusedLocals": true, "noImplicitThis": true, "alwaysStrict": true, "baseUrl": ".", "outDir": "../out", "typeRoots": [ "typings" ] } }
src/tsconfig.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017632683739066124, 0.0001747529167914763, 0.0001728506904328242, 0.00017508123710285872, 0.000001437994683328725 ]
{ "id": 3, "code_window": [ "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n", "import { checksum } from 'vs/base/node/crypto';\n", "import { tmpdir } from 'os';\n", "import { spawn } from 'child_process';\n", "\n", "function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> {\n", "\treturn new TPromise<void>(c => {\n", "\t\tconst poll = () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { shell } from 'electron';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 25 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.9983585476875305, 0.08673633635044098, 0.00016164671978913248, 0.00016977734048850834, 0.27672508358955383 ]
{ "id": 3, "code_window": [ "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n", "import { checksum } from 'vs/base/node/crypto';\n", "import { tmpdir } from 'os';\n", "import { spawn } from 'child_process';\n", "\n", "function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> {\n", "\treturn new TPromise<void>(c => {\n", "\t\tconst poll = () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { shell } from 'electron';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 25 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "defineKeybinding.start": "Définir une combinaison de touches", "defineKeybinding.kbLayoutErrorMessage": "Vous ne pouvez pas produire cette combinaison de touches avec la disposition actuelle du clavier.", "defineKeybinding.kbLayoutLocalAndUSMessage": "**{0}** pour votre disposition actuelle du clavier (**{1}** pour le clavier États-Unis standard).", "defineKeybinding.kbLayoutLocalMessage": "**{0}** pour votre disposition actuelle du clavier." }
i18n/fra/src/vs/workbench/parts/preferences/browser/keybindingsEditorContribution.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017806437972467393, 0.00017555161321070045, 0.00017303884669672698, 0.00017555161321070045, 0.0000025127665139734745 ]
{ "id": 3, "code_window": [ "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n", "import { checksum } from 'vs/base/node/crypto';\n", "import { tmpdir } from 'os';\n", "import { spawn } from 'child_process';\n", "\n", "function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> {\n", "\treturn new TPromise<void>(c => {\n", "\t\tconst poll = () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { shell } from 'electron';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 25 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "quickOpen.terminal": "開いているすべてのターミナルを表示", "terminal": "ターミナル", "terminalIntegratedConfigurationTitle": "統合ターミナル", "terminal.integrated.shell.linux": "ターミナルが Linux で使用するシェルのパス。", "terminal.integrated.shellArgs.linux": "Linux のターミナルで使用するコマンド ライン引数。", "terminal.integrated.shell.osx": "ターミナルが OS X で使用するシェルのパス。", "terminal.integrated.shellArgs.osx": "OS X 端末で使用するコマンド ライン引数。", "terminal.integrated.shell.windows": "Windows でターミナルが使用するシェルのパス。 Windows に同梱されているシェルを使用する場合 (cmd、PowerShell、または Bash on Ubuntu) 。", "terminal.integrated.shellArgs.windows": "Windows ターミナル上の場合に使用されるコマンド ライン引数。", "terminal.integrated.macOptionIsMeta": "macOS のターミナルでは、オプション キーをメタ キーとして扱います。", "terminal.integrated.copyOnSelection": "設定した場合、ターミナルで選択しているテキストはクリップボードにコピーされます。", "terminal.integrated.fontFamily": "端末のフォント ファミリを制御します。既定値は editor.fontFamily になります。", "terminal.integrated.fontSize": "ターミナルのフォント サイズをピクセル単位で制御します。", "terminal.integrated.letterSpacing": "ターミナルの文字間隔を制御、これは文字間の追加ピクセル数を表す整数値です。", "terminal.integrated.lineHeight": "ターミナルの行の高さを制御します。この数値にターミナルのフォント サイズを乗算すると、実際の行の高さ (ピクセル単位) になります。", "terminal.integrated.fontWeight": "ターミナル内で太字ではないテキストに使用するフォントの太さ。", "terminal.integrated.fontWeightBold": "ターミナル内で太字のテキストに使用するフォントの太さ。", "terminal.integrated.cursorBlinking": "ターミナルのカーソルを点滅させるかどうかを制御します。", "terminal.integrated.cursorStyle": "端末のカーソルのスタイルを制御します。", "terminal.integrated.scrollback": "端末がそのバッファーに保持できる最大行数を制御します。", "terminal.integrated.setLocaleVariables": "ターミナルの開始時にロケール変数を設定するかどうかを制御します。OS X では既定で true になり、その他のプラットフォームでは false です。", "terminal.integrated.rendererType": "ターミナルのレンダリングを制御します。オプションは標準的な (速い) キャンバス方式の \"canvas\"、代替的な DOM ベースのレンダリングの \"dom\"、いずれか良い方を VS Code に推測させる \"auto\" です。この設定は反映させるために VS Code を再読み込みする必要があります。", "terminal.integrated.rightClickBehavior": "ターミナルが右クリックにどのように反応するかを制御します。\"default\"、\"copyPaste\"、 \"selectWord\" を指定できます。\"default\" はコンテキスト メニューを表示します。\"copyPaste\" は選択範囲があるとコピーし、そうでない場合は貼り付けを行います。\"selectWord\" はカーソル下の単語を選択し、コンテキスト メニューを表示します。", "terminal.integrated.cwd": "端末を起動する明示的な開始パスです。これはシェル プロセスの現在の作業ディレクトリ (cwd) として使用されます。特にルート ディレクトリが cwd に適していない場合に、ワークスペースの設定で役立ちます。", "terminal.integrated.confirmOnExit": "アクティブなターミナル セッションがある場合に終了の確認をするかどうか。", "terminal.integrated.enableBell": "ターミナルのベルが有効かどうか。", "terminal.integrated.commandsToSkipShell": "キーバインドがシェルに送信されず、代わりに常に Code で処理されるコマンド ID のセット。これにより、ターミナルがフォーカスされていない場合と同じ動作をするシェルによって通常使用されるキーバインドを使用できるようになります。例: Ctrl+p で Quick Open を起動します。", "terminal.integrated.env.osx": "OS X のターミナルで使用される VS Code のプロセスに追加される環境変数を持つオブジェクト", "terminal.integrated.env.linux": "Linux のターミナルで使用される VS Code のプロセスに追加される環境変数を持つオブジェクト", "terminal.integrated.env.windows": "Windows のターミナルで使用される VS Code のプロセスに追加される環境変数を持つオブジェクト", "terminal.integrated.showExitAlert": "0 以外の終了コードのとき `終了コードを伴ってターミナルの処理が終了しました` と警告を表示します。", "terminal.integrated.experimentalRestore": "VS Code の起動時に自動的にワークスペースのターミナル セッションを復元するかどうか。これは実験的な設定です。不具合や将来的に変更される可能性があります。", "terminalCategory": "ターミナル", "viewCategory": "表示" }
i18n/jpn/src/vs/workbench/parts/terminal/electron-browser/terminal.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0002033503697020933, 0.0001816231815610081, 0.00016403038171119988, 0.00017773258150555193, 0.0000144372352224309 ]
{ "id": 3, "code_window": [ "import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService';\n", "import { download, asJson } from 'vs/base/node/request';\n", "import { checksum } from 'vs/base/node/crypto';\n", "import { tmpdir } from 'os';\n", "import { spawn } from 'child_process';\n", "\n", "function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> {\n", "\treturn new TPromise<void>(c => {\n", "\t\tconst poll = () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { shell } from 'electron';\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 25 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "first.chord": "Была нажата клавиша ({0}). Ожидание нажатия второй клавиши сочетания...", "missing.chord": "Сочетание клавиш ({0} и {1}) не является командой." }
i18n/rus/src/vs/platform/keybinding/common/abstractKeybindingService.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017575027595739812, 0.00017475582717452198, 0.00017376137839164585, 0.00017475582717452198, 9.94448782876134e-7 ]
{ "id": 4, "code_window": [ "interface IAvailableUpdate {\n", "\tpackagePath: string;\n", "\tupdateFilePath?: string;\n", "}\n", "\n", "export class Win32UpdateService extends AbstractUpdateService {\n", "\n", "\t_serviceBrand: any;\n", "\n", "\tprivate url: string | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "enum UpdateType {\n", "\tAutomatic,\n", "\tManual\n", "}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * 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 product from 'vs/platform/node/product'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import { State, IUpdate, AvailableForDownload } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { asJson } from 'vs/base/node/request'; import { TPromise } from 'vs/base/common/winjs.base'; import { shell } from 'electron'; export class LinuxUpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { this.url = createUpdateURL(`linux-${process.arch}`, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version || !update.productVersion) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); } else { this.setState(State.AvailableForDownload(update)); } }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } protected doDownloadUpdate(state: AvailableForDownload): TPromise<void> { // Use the download URL if available as we don't currently detect the package type that was // installed and the website download page is more useful than the tarball generally. if (product.downloadUrl && product.downloadUrl.length > 0) { shell.openExternal(product.downloadUrl); } else { shell.openExternal(state.update.url); } this.setState(State.Idle); return TPromise.as(null); } }
src/vs/platform/update/electron-main/updateService.linux.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.963125467300415, 0.09746003895998001, 0.00016819553275126964, 0.0003890724328812212, 0.28856366872787476 ]
{ "id": 4, "code_window": [ "interface IAvailableUpdate {\n", "\tpackagePath: string;\n", "\tupdateFilePath?: string;\n", "}\n", "\n", "export class Win32UpdateService extends AbstractUpdateService {\n", "\n", "\t_serviceBrand: any;\n", "\n", "\tprivate url: string | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "enum UpdateType {\n", "\tAutomatic,\n", "\tManual\n", "}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 45 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "ratedByUsers": "{0} 人が評価", "ratedBySingleUser": "1 人が評価" }
i18n/jpn/src/vs/workbench/parts/extensions/browser/extensionsWidgets.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017421328811906278, 0.00017419716459698975, 0.00017418105562683195, 0.00017419716459698975, 1.6116247891773128e-8 ]
{ "id": 4, "code_window": [ "interface IAvailableUpdate {\n", "\tpackagePath: string;\n", "\tupdateFilePath?: string;\n", "}\n", "\n", "export class Win32UpdateService extends AbstractUpdateService {\n", "\n", "\t_serviceBrand: any;\n", "\n", "\tprivate url: string | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "enum UpdateType {\n", "\tAutomatic,\n", "\tManual\n", "}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 45 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "alertErrorMessage": "Errore: {0}", "alertWarningMessage": "Avviso: {0}", "alertInfoMessage": "Info: {0}" }
i18n/ita/src/vs/workbench/browser/parts/notifications/notificationsAlerts.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.000175280831172131, 0.0001732706732582301, 0.00017126050079241395, 0.0001732706732582301, 0.000002010165189858526 ]
{ "id": 4, "code_window": [ "interface IAvailableUpdate {\n", "\tpackagePath: string;\n", "\tupdateFilePath?: string;\n", "}\n", "\n", "export class Win32UpdateService extends AbstractUpdateService {\n", "\n", "\t_serviceBrand: any;\n", "\n", "\tprivate url: string | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "enum UpdateType {\n", "\tAutomatic,\n", "\tManual\n", "}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 45 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "displayName": "搜尋 (ripgrep)", "description": "使用 Ripgrep 提供搜尋。" }
i18n/cht/extensions/search-rg/package.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017418105562683195, 0.00017393112648278475, 0.00017368121189065278, 0.00017393112648278475, 2.499218680895865e-7 ]
{ "id": 5, "code_window": [ "\n", "\tprivate url: string | undefined;\n", "\tprivate availableUpdate: IAvailableUpdate | undefined;\n", "\n", "\t@memoize\n", "\tget cachePath(): TPromise<string> {\n", "\t\tconst result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate updateType: UpdateType;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.9982308745384216, 0.1714911311864853, 0.00016325581236742437, 0.0002527369651943445, 0.372285932302475 ]
{ "id": 5, "code_window": [ "\n", "\tprivate url: string | undefined;\n", "\tprivate availableUpdate: IAvailableUpdate | undefined;\n", "\n", "\t@memoize\n", "\tget cachePath(): TPromise<string> {\n", "\t\tconst result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate updateType: UpdateType;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 51 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "showHover": "Afficher par pointage" }
i18n/fra/src/vs/editor/contrib/hover/hover.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017695187125355005, 0.00017527176532894373, 0.00017359164485242218, 0.00017527176532894373, 0.0000016801132005639374 ]
{ "id": 5, "code_window": [ "\n", "\tprivate url: string | undefined;\n", "\tprivate availableUpdate: IAvailableUpdate | undefined;\n", "\n", "\t@memoize\n", "\tget cachePath(): TPromise<string> {\n", "\t\tconst result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate updateType: UpdateType;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * 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. { "typescript.projectConfigNoWorkspace": "TypeScript または JavaScript プロジェクトを使用するには、VS Code でフォルダーを開いてください", "typescript.projectConfigUnsupportedFile": "TypeScript または JavaScript のプロジェクトを判別できませんでした。サポートされていないファイルの種類です", "typescript.projectConfigCouldNotGetInfo": "TypeScript または JavaScript のプロジェクトを判別できませんでした", "typescript.noTypeScriptProjectConfig": "ファイルは TypeScript プロジェクトの一部ではない", "typescript.noJavaScriptProjectConfig": "ファイルは JavaScript プロジェクトの一部ではない", "typescript.configureTsconfigQuickPick": "tsconfig.json を構成する", "typescript.configureJsconfigQuickPick": "jsconfig.json を構成する", "typescript.projectConfigLearnMore": "詳細情報" }
i18n/jpn/extensions/typescript/out/typescriptMain.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00016912652063183486, 0.00016696794773451984, 0.00016480938938912004, 0.00016696794773451984, 0.000002158565621357411 ]
{ "id": 5, "code_window": [ "\n", "\tprivate url: string | undefined;\n", "\tprivate availableUpdate: IAvailableUpdate | undefined;\n", "\n", "\t@memoize\n", "\tget cachePath(): TPromise<string> {\n", "\t\tconst result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate updateType: UpdateType;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * 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. { "selectPreviousItem": "Emmet : Select Previous Item", "selectNextItem": "Emmet : Select Next Item" }
i18n/fra/src/vs/workbench/parts/emmet/electron-browser/actions/selectItem.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0001759189326548949, 0.0001759189326548949, 0.0001759189326548949, 0.0001759189326548949, 0 ]
{ "id": 6, "code_window": [ "\t\t@IRequestService private requestService: IRequestService,\n", "\t\t@ILogService logService: ILogService\n", "\t) {\n", "\t\tsuper(lifecycleService, configurationService, environmentService, logService);\n", "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tthis.updateType = fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))\n", "\t\t\t? UpdateType.Automatic\n", "\t\t\t: UpdateType.Manual;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 67 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.8092254400253296, 0.035401009023189545, 0.00016491362475790083, 0.0001715396501822397, 0.16498009860515594 ]
{ "id": 6, "code_window": [ "\t\t@IRequestService private requestService: IRequestService,\n", "\t\t@ILogService logService: ILogService\n", "\t) {\n", "\t\tsuper(lifecycleService, configurationService, environmentService, logService);\n", "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tthis.updateType = fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))\n", "\t\t\t? UpdateType.Automatic\n", "\t\t\t: UpdateType.Manual;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 67 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor.vs .dnd-target { border-right: 2px dotted black; color: white; /* opposite of black */ } .monaco-editor.vs-dark .dnd-target { border-right: 2px dotted #AEAFAD; color: #51504f; /* opposite of #AEAFAD */ } .monaco-editor.hc-black .dnd-target { border-right: 2px dotted #fff; color: #000; /* opposite of #fff */ } .monaco-editor.mouse-default .view-lines, .monaco-editor.vs-dark.mac.mouse-default .view-lines, .monaco-editor.hc-black.mac.mouse-default .view-lines { cursor: default; } .monaco-editor.mouse-copy .view-lines, .monaco-editor.vs-dark.mac.mouse-copy .view-lines, .monaco-editor.hc-black.mac.mouse-copy .view-lines { cursor: copy; }
src/vs/editor/contrib/dnd/dnd.css
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017678271979093552, 0.0001740645820973441, 0.00017155386740341783, 0.00017385715909767896, 0.000002139702928616316 ]
{ "id": 6, "code_window": [ "\t\t@IRequestService private requestService: IRequestService,\n", "\t\t@ILogService logService: ILogService\n", "\t) {\n", "\t\tsuper(lifecycleService, configurationService, environmentService, logService);\n", "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tthis.updateType = fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))\n", "\t\t\t? UpdateType.Automatic\n", "\t\t\t: UpdateType.Manual;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 67 }
<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg"><title>Layer 1</title><rect height="3" width="11" y="7" x="3" fill="#424242"/></svg>
src/vs/editor/browser/widget/media/deletion.svg
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.000173647262272425, 0.000173647262272425, 0.000173647262272425, 0.000173647262272425, 0 ]
{ "id": 6, "code_window": [ "\t\t@IRequestService private requestService: IRequestService,\n", "\t\t@ILogService logService: ILogService\n", "\t) {\n", "\t\tsuper(lifecycleService, configurationService, environmentService, logService);\n", "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tthis.updateType = fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))\n", "\t\t\t? UpdateType.Automatic\n", "\t\t\t: UpdateType.Manual;\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 67 }
/*--------------------------------------------------------------------------------------------- * 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. { "tasksAriaLabel": "テスト タスクの名前を入力してください", "noTasksMatching": "一致するタスクがありません", "noTasksFound": "テスト タスクが見つかりません" }
i18n/jpn/src/vs/workbench/parts/tasks/browser/testQuickOpen.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017849207506515086, 0.00017564122390467674, 0.00017279037274420261, 0.00017564122390467674, 0.0000028508511604741216 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n", "\t\tif (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\tlet platform = 'win32';\n", "\n", "\t\tif (process.arch === 'x64') {\n", "\t\t\tplatform += '-x64';\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 70 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.9986768364906311, 0.08749352395534515, 0.00016395485727116466, 0.00017073207709472626, 0.2811475694179535 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n", "\t\tif (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\tlet platform = 'win32';\n", "\n", "\t\tif (process.arch === 'x64') {\n", "\t\t\tplatform += '-x64';\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 70 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "displayName": "Conceptos básicos del lenguaje Handlebars ", "description": "Proporciona resaltado de sintaxis y correspondencia de corchetes en archivos de Handlebars." }
i18n/esn/extensions/handlebars/package.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0001765527849784121, 0.00017545698210597038, 0.0001743611937854439, 0.00017545698210597038, 0.0000010957955964840949 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n", "\t\tif (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\tlet platform = 'win32';\n", "\n", "\t\tif (process.arch === 'x64') {\n", "\t\t\tplatform += '-x64';\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 70 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "mainLog": "Protokoll (Haupt)", "sharedLog": "Protokoll (freigegeben)", "rendererLog": "Protokoll (Fenster)", "extensionsLog": "Protokoll (Erweiterungshost)", "developer": "Entwickler" }
i18n/deu/src/vs/workbench/parts/logs/electron-browser/logs.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017572227807249874, 0.0001722238666843623, 0.00016872545529622585, 0.0001722238666843623, 0.0000034984113881364465 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tprotected setUpdateFeedUrl(quality: string): boolean {\n", "\t\tif (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\tlet platform = 'win32';\n", "\n", "\t\tif (process.arch === 'x64') {\n", "\t\t\tplatform += '-x64';\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 70 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "displayName": "Tema Kimbie Escuro", "description": "Tema Kimble escruto para o Visual Studio Code" }
i18n/ptb/extensions/theme-kimbie-dark/package.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017609716451261193, 0.00017522918642498553, 0.0001743611937854439, 0.00017522918642498553, 8.679853635840118e-7 ]
{ "id": 8, "code_window": [ "\n", "\t\tthis.requestService.request({ url: this.url })\n", "\t\t\t.then<IUpdate>(asJson)\n", "\t\t\t.then(update => {\n", "\t\t\t\tif (!update || !update.url || !update.version) {\n", "\t\t\t\t\t/* __GDPR__\n", "\t\t\t\t\t\t\t\"update:notAvailable\" : {\n", "\t\t\t\t\t\t\t\t\"explicit\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true }\n", "\t\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (!update || !update.url || !update.version || !update.productVersion) {\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.9524693489074707, 0.04476811736822128, 0.00016331186634488404, 0.00017275166464969516, 0.19397684931755066 ]
{ "id": 8, "code_window": [ "\n", "\t\tthis.requestService.request({ url: this.url })\n", "\t\t\t.then<IUpdate>(asJson)\n", "\t\t\t.then(update => {\n", "\t\t\t\tif (!update || !update.url || !update.version) {\n", "\t\t\t\t\t/* __GDPR__\n", "\t\t\t\t\t\t\t\"update:notAvailable\" : {\n", "\t\t\t\t\t\t\t\t\"explicit\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true }\n", "\t\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (!update || !update.url || !update.version || !update.productVersion) {\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ITextBufferBuilder, ITextBufferFactory, ITextBuffer, DefaultEndOfLine } from 'vs/editor/common/model'; import { PieceTreeTextBufferBuilder } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder'; export function doBenchmark<T>(id: string, ts: T[], fn: (t: T) => void) { let columns: string[] = [id]; for (let i = 0; i < ts.length; i++) { let start = process.hrtime(); fn(ts[i]); let diff = process.hrtime(start); columns.push(`${(diff[0] * 1000 + diff[1] / 1000000).toFixed(3)} ms`); } console.log('|' + columns.join('\t|') + '|'); } export interface IBenchmark { name: string; /** * Before each cycle, this function will be called to create TextBufferFactory */ buildBuffer: (textBufferBuilder: ITextBufferBuilder) => ITextBufferFactory; /** * Before each cycle, this function will be called to do pre-work for text buffer. * This will be called onece `buildBuffer` is finished. */ preCycle: (textBuffer: ITextBuffer) => void; /** * The function we are benchmarking */ fn: (textBuffer: ITextBuffer) => void; } export class BenchmarkSuite { name: string; iterations: number; benchmarks: IBenchmark[]; constructor(suiteOptions: { name: string, iterations: number }) { this.name = suiteOptions.name; this.iterations = suiteOptions.iterations; this.benchmarks = []; } add(benchmark: IBenchmark) { this.benchmarks.push(benchmark); } run() { console.log(`|${this.name}\t|line buffer\t|piece table\t|edcore\t`); console.log('|---|---|---|---|'); for (let i = 0; i < this.benchmarks.length; i++) { let benchmark = this.benchmarks[i]; let columns: string[] = [benchmark.name]; [new PieceTreeTextBufferBuilder()].forEach((builder: ITextBufferBuilder) => { let timeDiffTotal = 0.0; for (let j = 0; j < this.iterations; j++) { let factory = benchmark.buildBuffer(builder); let buffer = factory.create(DefaultEndOfLine.LF); benchmark.preCycle(buffer); let start = process.hrtime(); benchmark.fn(buffer); let diff = process.hrtime(start); timeDiffTotal += (diff[0] * 1000 * 1000 + diff[1] / 1000); } columns.push(`${(timeDiffTotal / 1000 / this.iterations).toFixed(3)} ms`); }); console.log('|' + columns.join('\t|') + '|'); } console.log('\n'); } }
src/vs/editor/test/common/model/benchmark/benchmarkUtils.ts
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017584464512765408, 0.00017203998868353665, 0.0001640055124880746, 0.00017324319924227893, 0.0000037959928249620134 ]
{ "id": 8, "code_window": [ "\n", "\t\tthis.requestService.request({ url: this.url })\n", "\t\t\t.then<IUpdate>(asJson)\n", "\t\t\t.then(update => {\n", "\t\t\t\tif (!update || !update.url || !update.version) {\n", "\t\t\t\t\t/* __GDPR__\n", "\t\t\t\t\t\t\t\"update:notAvailable\" : {\n", "\t\t\t\t\t\t\t\t\"explicit\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true }\n", "\t\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (!update || !update.url || !update.version || !update.productVersion) {\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 98 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "html.editor.label": "HTML 预览" }
i18n/chs/src/vs/workbench/parts/html/electron-browser/html.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0001780187158146873, 0.0001763362088240683, 0.0001746537018334493, 0.0001763362088240683, 0.0000016825069906190038 ]
{ "id": 8, "code_window": [ "\n", "\t\tthis.requestService.request({ url: this.url })\n", "\t\t\t.then<IUpdate>(asJson)\n", "\t\t\t.then(update => {\n", "\t\t\t\tif (!update || !update.url || !update.version) {\n", "\t\t\t\t\t/* __GDPR__\n", "\t\t\t\t\t\t\t\"update:notAvailable\" : {\n", "\t\t\t\t\t\t\t\t\"explicit\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true }\n", "\t\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (!update || !update.url || !update.version || !update.productVersion) {\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * 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 { SignatureHelpProvider, SignatureHelp, SignatureInformation, CancellationToken, TextDocument, Position, workspace } from 'vscode'; import phpGlobals = require('./phpGlobals'); import phpGlobalFunctions = require('./phpGlobalFunctions'); var _NL = '\n'.charCodeAt(0); var _TAB = '\t'.charCodeAt(0); var _WSB = ' '.charCodeAt(0); var _LBracket = '['.charCodeAt(0); var _RBracket = ']'.charCodeAt(0); var _LCurly = '{'.charCodeAt(0); var _RCurly = '}'.charCodeAt(0); var _LParent = '('.charCodeAt(0); var _RParent = ')'.charCodeAt(0); var _Comma = ','.charCodeAt(0); var _Quote = '\''.charCodeAt(0); var _DQuote = '"'.charCodeAt(0); var _USC = '_'.charCodeAt(0); var _a = 'a'.charCodeAt(0); var _z = 'z'.charCodeAt(0); var _A = 'A'.charCodeAt(0); var _Z = 'Z'.charCodeAt(0); var _0 = '0'.charCodeAt(0); var _9 = '9'.charCodeAt(0); var BOF = 0; class BackwardIterator { private lineNumber: number; private offset: number; private line: string; private model: TextDocument; constructor(model: TextDocument, offset: number, lineNumber: number) { this.lineNumber = lineNumber; this.offset = offset; this.line = model.lineAt(this.lineNumber).text; this.model = model; } public hasNext(): boolean { return this.lineNumber >= 0; } public next(): number { if (this.offset < 0) { if (this.lineNumber > 0) { this.lineNumber--; this.line = this.model.lineAt(this.lineNumber).text; this.offset = this.line.length - 1; return _NL; } this.lineNumber = -1; return BOF; } var ch = this.line.charCodeAt(this.offset); this.offset--; return ch; } } export default class PHPSignatureHelpProvider implements SignatureHelpProvider { public provideSignatureHelp(document: TextDocument, position: Position, _token: CancellationToken): Promise<SignatureHelp> | null { let enable = workspace.getConfiguration('php').get<boolean>('suggest.basic', true); if (!enable) { return null; } var iterator = new BackwardIterator(document, position.character - 1, position.line); var paramCount = this.readArguments(iterator); if (paramCount < 0) { return null; } var ident = this.readIdent(iterator); if (!ident) { return null; } var entry = phpGlobalFunctions.globalfunctions[ident] || phpGlobals.keywords[ident]; if (!entry || !entry.signature) { return null; } var paramsString = entry.signature.substring(0, entry.signature.lastIndexOf(')') + 1); let signatureInfo = new SignatureInformation(ident + paramsString, entry.description); var re = /\w*\s+\&?\$[\w_\.]+|void/g; var match: RegExpExecArray | null = null; while ((match = re.exec(paramsString)) !== null) { signatureInfo.parameters.push({ label: match[0], documentation: '' }); } let ret = new SignatureHelp(); ret.signatures.push(signatureInfo); ret.activeSignature = 0; ret.activeParameter = Math.min(paramCount, signatureInfo.parameters.length - 1); return Promise.resolve(ret); } private readArguments(iterator: BackwardIterator): number { var parentNesting = 0; var bracketNesting = 0; var curlyNesting = 0; var paramCount = 0; while (iterator.hasNext()) { var ch = iterator.next(); switch (ch) { case _LParent: parentNesting--; if (parentNesting < 0) { return paramCount; } break; case _RParent: parentNesting++; break; case _LCurly: curlyNesting--; break; case _RCurly: curlyNesting++; break; case _LBracket: bracketNesting--; break; case _RBracket: bracketNesting++; break; case _DQuote: case _Quote: while (iterator.hasNext() && ch !== iterator.next()) { // find the closing quote or double quote } break; case _Comma: if (!parentNesting && !bracketNesting && !curlyNesting) { paramCount++; } break; } } return -1; } private isIdentPart(ch: number): boolean { if (ch === _USC || // _ ch >= _a && ch <= _z || // a-z ch >= _A && ch <= _Z || // A-Z ch >= _0 && ch <= _9 || // 0/9 ch >= 0x80 && ch <= 0xFFFF) { // nonascii return true; } return false; } private readIdent(iterator: BackwardIterator): string { var identStarted = false; var ident = ''; while (iterator.hasNext()) { var ch = iterator.next(); if (!identStarted && (ch === _WSB || ch === _TAB || ch === _NL)) { continue; } if (this.isIdentPart(ch)) { identStarted = true; ident = String.fromCharCode(ch) + ident; } else if (identStarted) { return ident; } } return ident; } }
extensions/php-language-features/src/features/signatureHelpProvider.ts
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0001759630540618673, 0.00017330794071312994, 0.00016622300609014928, 0.00017390010179951787, 0.0000024650482828292297 ]
{ "id": 9, "code_window": [ "\t\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tthis.setState(State.Downloading(update));\n", "\n", "\t\t\t\treturn this.cleanup(update.version).then(() => {\n", "\t\t\t\t\treturn this.getUpdatePackagePath(update.version).then(updatePackagePath => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.updateType === UpdateType.Manual) {\n", "\t\t\t\t\tthis.setState(State.AvailableForDownload(update));\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 110 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.5779420733451843, 0.03202300891280174, 0.00016554286412429065, 0.0003223931707907468, 0.11953549087047577 ]
{ "id": 9, "code_window": [ "\t\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tthis.setState(State.Downloading(update));\n", "\n", "\t\t\t\treturn this.cleanup(update.version).then(() => {\n", "\t\t\t\t\treturn this.getUpdatePackagePath(update.version).then(updatePackagePath => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.updateType === UpdateType.Manual) {\n", "\t\t\t\t\tthis.setState(State.AvailableForDownload(update));\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 110 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ interface ArrayConstructor { isArray(arg: any): arg is Array<any>; isArray<T>(arg: any): arg is Array<T>; }
src/typings/lib.array-ext.d.ts
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017253009718842804, 0.00017253009718842804, 0.00017253009718842804, 0.00017253009718842804, 0 ]
{ "id": 9, "code_window": [ "\t\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tthis.setState(State.Downloading(update));\n", "\n", "\t\t\t\treturn this.cleanup(update.version).then(() => {\n", "\t\t\t\t\treturn this.getUpdatePackagePath(update.version).then(updatePackagePath => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.updateType === UpdateType.Manual) {\n", "\t\t\t\t\tthis.setState(State.AvailableForDownload(update));\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 110 }
/*--------------------------------------------------------------------------------------------- * 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. { "process": "Процесс", "paused": "Приостановлено", "running": "Работает", "thread": "Поток", "pausedOn": "Приостановлено на {0}", "loadMoreStackFrames": "Загрузить больше кадров стека", "threadAriaLabel": "Поток {0}, стек вызовов, отладка", "stackFrameAriaLabel": "Кадр стека {0}, строка {1} {2}, стек вызовов, отладка", "variableValueAriaLabel": "Введите новое значение переменной", "variableScopeAriaLabel": "Область {0}, переменные, отладка", "variableAriaLabel": "{0} значение {1}, переменные, отладка", "watchExpressionPlaceholder": "Выражение с контрольным значением", "watchExpressionInputAriaLabel": "Введите выражение контрольного значения", "watchExpressionAriaLabel": "{0} значение {1}, контрольное значение, отладка", "watchVariableAriaLabel": "{0} значение {1}, контрольное значение, отладка", "functionBreakpointPlaceholder": "Функция, в которой производится останов", "functionBreakPointInputAriaLabel": "Введите точку останова в функции", "functionBreakpointsNotSupported": "Точки останова функций не поддерживаются в этом типе отладки", "breakpointAriaLabel": "Строка точки останова {0} {1}, точки останова, отладка", "functionBreakpointAriaLabel": "Точка останова в функции {0}, точки останова, отладка", "exceptionBreakpointAriaLabel": "Точка останова в исключении {0}, точки останова, отладка" }
i18n/rus/src/vs/workbench/parts/debug/electron-browser/debugViewer.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0002768578415270895, 0.00023352990683633834, 0.00017337642202619463, 0.0002503554569557309, 0.00004388944580568932 ]
{ "id": 9, "code_window": [ "\t\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tthis.setState(State.Downloading(update));\n", "\n", "\t\t\t\treturn this.cleanup(update.version).then(() => {\n", "\t\t\t\t\treturn this.getUpdatePackagePath(update.version).then(updatePackagePath => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.updateType === UpdateType.Manual) {\n", "\t\t\t\t\tthis.setState(State.AvailableForDownload(update));\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 110 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/[email protected]": version "7.0.43" resolved "https://registry.yarnpkg.com/@types/node/-/node-7.0.43.tgz#a187e08495a075f200ca946079c914e1a5fe962c" vscode-nls@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-3.2.1.tgz#b1f3e04e8a94a715d5a7bcbc8339c51e6d74ca51"
extensions/jake/yarn.lock
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.0001693996018730104, 0.00016934963059611619, 0.00016929965931922197, 0.00016934963059611619, 4.997127689421177e-8 ]
{ "id": 10, "code_window": [ "\t\t\t\tthis.telemetryService.publicLog('update:notAvailable', { explicit: !!context });\n", "\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t});\n", "\t}\n", "\n", "\tprivate getUpdatePackagePath(version: string): TPromise<string> {\n", "\t\treturn this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`));\n", "\t}\n", "\n", "\tprivate cleanup(exceptVersion: string = null): Promise {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected doDownloadUpdate(state: AvailableForDownload): TPromise<void> {\n", "\t\t// Use the download URL if available as we don't currently detect the package type that was\n", "\t\t// installed and the website download page is more useful than the tarball generally.\n", "\t\tif (product.downloadUrl && product.downloadUrl.length > 0) {\n", "\t\t\tshell.openExternal(product.downloadUrl);\n", "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\n", "\t\tthis.setState(State.Idle);\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 158 }
/*--------------------------------------------------------------------------------------------- * 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 fs from 'original-fs'; import * as path from 'path'; import * as pfs from 'vs/base/node/pfs'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain'; import { IRequestService } from 'vs/platform/request/node/request'; import product from 'vs/platform/node/product'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { State, IUpdate, StateType } from 'vs/platform/update/common/update'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ILogService } from 'vs/platform/log/common/log'; import { createUpdateURL, AbstractUpdateService } from 'vs/platform/update/electron-main/abstractUpdateService'; import { download, asJson } from 'vs/base/node/request'; import { checksum } from 'vs/base/node/crypto'; import { tmpdir } from 'os'; import { spawn } from 'child_process'; function pollUntil(fn: () => boolean, timeout = 1000): TPromise<void> { return new TPromise<void>(c => { const poll = () => { if (fn()) { c(null); } else { setTimeout(poll, timeout); } }; poll(); }); } interface IAvailableUpdate { packagePath: string; updateFilePath?: string; } export class Win32UpdateService extends AbstractUpdateService { _serviceBrand: any; private url: string | undefined; private availableUpdate: IAvailableUpdate | undefined; @memoize get cachePath(): TPromise<string> { const result = path.join(tmpdir(), `vscode-update-${product.target}-${process.arch}`); return pfs.mkdirp(result, null).then(() => result); } constructor( @ILifecycleService lifecycleService: ILifecycleService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private telemetryService: ITelemetryService, @IEnvironmentService environmentService: IEnvironmentService, @IRequestService private requestService: IRequestService, @ILogService logService: ILogService ) { super(lifecycleService, configurationService, environmentService, logService); } protected setUpdateFeedUrl(quality: string): boolean { if (!fs.existsSync(path.join(path.dirname(process.execPath), 'unins000.exe'))) { return false; } let platform = 'win32'; if (process.arch === 'x64') { platform += '-x64'; } if (product.target === 'user') { platform += '-user'; } this.url = createUpdateURL(platform, quality); return true; } protected doCheckForUpdates(context: any): void { if (!this.url) { return; } this.setState(State.CheckingForUpdates(context)); this.requestService.request({ url: this.url }) .then<IUpdate>(asJson) .then(update => { if (!update || !update.url || !update.version) { /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); return TPromise.as(null); } this.setState(State.Downloading(update)); return this.cleanup(update.version).then(() => { return this.getUpdatePackagePath(update.version).then(updatePackagePath => { return pfs.exists(updatePackagePath).then(exists => { if (exists) { return TPromise.as(updatePackagePath); } const url = update.url; const hash = update.hash; const downloadPath = `${updatePackagePath}.tmp`; return this.requestService.request({ url }) .then(context => download(downloadPath, context)) .then(hash ? () => checksum(downloadPath, update.hash) : () => null) .then(() => pfs.rename(downloadPath, updatePackagePath)) .then(() => updatePackagePath); }); }).then(packagePath => { const fastUpdatesEnabled = this.configurationService.getValue<boolean>('update.enableWindowsBackgroundUpdates'); this.availableUpdate = { packagePath }; if (fastUpdatesEnabled && update.supportsFastUpdate) { if (product.target === 'user') { this.doApplyUpdate(); } else { this.setState(State.Downloaded(update)); } } else { this.setState(State.Ready(update)); } }); }); }) .then(null, err => { this.logService.error(err); /* __GDPR__ "update:notAvailable" : { "explicit" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('update:notAvailable', { explicit: !!context }); this.setState(State.Idle); }); } private getUpdatePackagePath(version: string): TPromise<string> { return this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`)); } private cleanup(exceptVersion: string = null): Promise { const filter = exceptVersion ? one => !(new RegExp(`${product.quality}-${exceptVersion}\\.exe$`).test(one)) : () => true; return this.cachePath .then(cachePath => pfs.readdir(cachePath) .then(all => Promise.join(all .filter(filter) .map(one => pfs.unlink(path.join(cachePath, one)).then(null, () => null)) )) ); } protected doApplyUpdate(): TPromise<void> { if (this.state.type !== StateType.Downloaded && this.state.type !== StateType.Downloading) { return TPromise.as(null); } if (!this.availableUpdate) { return TPromise.as(null); } const update = this.state.update; this.setState(State.Updating(update)); return this.cachePath.then(cachePath => { this.availableUpdate.updateFilePath = path.join(cachePath, `CodeSetup-${product.quality}-${update.version}.flag`); return pfs.writeFile(this.availableUpdate.updateFilePath, 'flag').then(() => { const child = spawn(this.availableUpdate.packagePath, ['/verysilent', `/update="${this.availableUpdate.updateFilePath}"`, '/nocloseapplications', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'], windowsVerbatimArguments: true }); child.once('exit', () => { this.availableUpdate = undefined; this.setState(State.Idle); }); const readyMutexName = `${product.win32MutexName}-ready`; const isActive = (require.__$__nodeRequire('windows-mutex') as any).isActive; // poll for mutex-ready pollUntil(() => isActive(readyMutexName)) .then(() => this.setState(State.Ready(update))); }); }); } protected doQuitAndInstall(): void { if (this.state.type !== StateType.Ready) { return; } this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()'); if (this.state.update.supportsFastUpdate && this.availableUpdate.updateFilePath) { fs.unlinkSync(this.availableUpdate.updateFilePath); } else { spawn(this.availableUpdate.packagePath, ['/silent', '/mergetasks=runcode,!desktopicon,!quicklaunchicon'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] }); } } }
src/vs/platform/update/electron-main/updateService.win32.ts
1
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.9988555908203125, 0.10096973180770874, 0.00016422160842921585, 0.00027932142256759107, 0.28261998295783997 ]
{ "id": 10, "code_window": [ "\t\t\t\tthis.telemetryService.publicLog('update:notAvailable', { explicit: !!context });\n", "\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t});\n", "\t}\n", "\n", "\tprivate getUpdatePackagePath(version: string): TPromise<string> {\n", "\t\treturn this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`));\n", "\t}\n", "\n", "\tprivate cleanup(exceptVersion: string = null): Promise {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected doDownloadUpdate(state: AvailableForDownload): TPromise<void> {\n", "\t\t// Use the download URL if available as we don't currently detect the package type that was\n", "\t\t// installed and the website download page is more useful than the tarball generally.\n", "\t\tif (product.downloadUrl && product.downloadUrl.length > 0) {\n", "\t\t\tshell.openExternal(product.downloadUrl);\n", "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\n", "\t\tthis.setState(State.Idle);\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 158 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "editor.action.webvieweditor.showFind": "検索ウィジェットにフォーカスする", "openToolsLabel": "Webview 開発者ツールを開く", "refreshWebviewLabel": "WebView の再読み込み" }
i18n/jpn/src/vs/workbench/parts/html/browser/webviewCommands.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017812517762649804, 0.00017592257063370198, 0.00017371996364090592, 0.00017592257063370198, 0.0000022026069927960634 ]
{ "id": 10, "code_window": [ "\t\t\t\tthis.telemetryService.publicLog('update:notAvailable', { explicit: !!context });\n", "\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t});\n", "\t}\n", "\n", "\tprivate getUpdatePackagePath(version: string): TPromise<string> {\n", "\t\treturn this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`));\n", "\t}\n", "\n", "\tprivate cleanup(exceptVersion: string = null): Promise {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected doDownloadUpdate(state: AvailableForDownload): TPromise<void> {\n", "\t\t// Use the download URL if available as we don't currently detect the package type that was\n", "\t\t// installed and the website download page is more useful than the tarball generally.\n", "\t\tif (product.downloadUrl && product.downloadUrl.length > 0) {\n", "\t\t\tshell.openExternal(product.downloadUrl);\n", "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\n", "\t\tthis.setState(State.Idle);\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 158 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "missOrInvalid": "자격 증명이 없거나 잘못되었습니다." }
i18n/kor/extensions/git/out/askpass-main.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017720650066621602, 0.00017660247976891696, 0.00017599847342353314, 0.00017660247976891696, 6.040136213414371e-7 ]
{ "id": 10, "code_window": [ "\t\t\t\tthis.telemetryService.publicLog('update:notAvailable', { explicit: !!context });\n", "\t\t\t\tthis.setState(State.Idle);\n", "\t\t\t});\n", "\t}\n", "\n", "\tprivate getUpdatePackagePath(version: string): TPromise<string> {\n", "\t\treturn this.cachePath.then(cachePath => path.join(cachePath, `CodeSetup-${product.quality}-${version}.exe`));\n", "\t}\n", "\n", "\tprivate cleanup(exceptVersion: string = null): Promise {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected doDownloadUpdate(state: AvailableForDownload): TPromise<void> {\n", "\t\t// Use the download URL if available as we don't currently detect the package type that was\n", "\t\t// installed and the website download page is more useful than the tarball generally.\n", "\t\tif (product.downloadUrl && product.downloadUrl.length > 0) {\n", "\t\t\tshell.openExternal(product.downloadUrl);\n", "\t\t} else {\n", "\t\t\tshell.openExternal(state.update.url);\n", "\t\t}\n", "\n", "\t\tthis.setState(State.Idle);\n", "\t\treturn TPromise.as(null);\n", "\t}\n", "\n" ], "file_path": "src/vs/platform/update/electron-main/updateService.win32.ts", "type": "add", "edit_start_line_idx": 158 }
{ "": [ "--------------------------------------------------------------------------------------------", "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." ], "htmlserver.name": "HTML 语言服务器", "folding.start": "折叠区域开始", "folding.end": "折叠区域结束" }
i18n/chs/extensions/html-language-features/client/out/htmlMain.i18n.json
0
https://github.com/microsoft/vscode/commit/c6f2eacce8dfb9a0d8e37de0e4f9cdbcdcad2f5d
[ 0.00017777497123461217, 0.00017533599748276174, 0.00017289702373091131, 0.00017533599748276174, 0.000002438973751850426 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < r.args.length; ++i) {\n", " res += JSON.stringify(r.fixedArgs[i]);\n", " res += \" + \";\n", " res += this._localNames[r.args[i]];\n", " res += \" + \";\n", " }\n", " res += JSON.stringify(r.fixedArgs[r.args.length]);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " res += `${UTIL}.s(${this._localNames[r.args[i]]})`;\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_jit_generator.ts", "type": "replace", "edit_start_line_idx": 373 }
import { AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, IS_DARTIUM, beforeEachBindings, it, xit, containsRegexp, stringifyElement, TestComponentBuilder, fakeAsync } from 'angular2/test_lib'; import {DOM} from 'angular2/src/dom/dom_adapter'; import { Type, isPresent, BaseException, assertionsEnabled, isJsObject, global, stringify, CONST, CONST_EXPR } from 'angular2/src/facade/lang'; import {PromiseWrapper, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import { Injector, bind, Injectable, Binding, forwardRef, OpaqueToken, Inject, Ancestor, Unbounded, UnboundedMetadata } from 'angular2/di'; import { PipeFactory, Pipes, defaultPipes, Pipe, ChangeDetectorRef, ON_PUSH } from 'angular2/change_detection'; import {Directive, Component, View, Attribute, Query} from 'angular2/annotations'; import * as viewAnn from 'angular2/src/core/annotations_impl/view'; import {QueryList} from 'angular2/src/core/compiler/query_list'; import {NgIf} from 'angular2/src/directives/ng_if'; import {NgFor} from 'angular2/src/directives/ng_for'; import {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref'; import {ViewRef} from 'angular2/src/core/compiler/view_ref'; import {Compiler} from 'angular2/src/core/compiler/compiler'; import {ElementRef} from 'angular2/src/core/compiler/element_ref'; import {TemplateRef} from 'angular2/src/core/compiler/template_ref'; import {DomRenderer} from 'angular2/src/render/dom/dom_renderer'; import {AppViewManager} from 'angular2/src/core/compiler/view_manager'; const ANCHOR_ELEMENT = CONST_EXPR(new OpaqueToken('AnchorElement')); export function main() { describe('integration tests', function() { beforeEachBindings(() => [bind(ANCHOR_ELEMENT).toValue(el('<div></div>'))]); describe('react to record changes', function() { it('should consume text node changes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div>{{ctxProp}}</div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText('Hello World!'); async.done(); }); })); it('should consume element binding changes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [id]="ctxProp"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.id).toEqual('Hello World!'); async.done(); }); })); it('should consume binding to aria-* attributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [attr.aria-label]="ctxProp"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Initial aria label'; rootTC.detectChanges(); expect( DOM.getAttribute(rootTC.componentViewChildren[0].nativeElement, 'aria-label')) .toEqual('Initial aria label'); rootTC.componentInstance.ctxProp = 'Changed aria label'; rootTC.detectChanges(); expect( DOM.getAttribute(rootTC.componentViewChildren[0].nativeElement, 'aria-label')) .toEqual('Changed aria label'); async.done(); }); })); it('should consume binding to property names where attr name and property name do not match', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [tabindex]="ctxNumProp"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.tabIndex).toEqual(0); rootTC.componentInstance.ctxNumProp = 5; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.tabIndex).toEqual(5); async.done(); }); })); it('should consume binding to camel-cased properties using dash-cased syntax in templates', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<input [read-only]="ctxBoolProp">'})) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.readOnly).toBeFalsy(); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.readOnly).toBeTruthy(); async.done(); }); })); it('should consume binding to inner-html', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div inner-html="{{ctxProp}}"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Some <span>HTML</span>'; rootTC.detectChanges(); expect(DOM.getInnerHTML(rootTC.componentViewChildren[0].nativeElement)) .toEqual('Some <span>HTML</span>'); rootTC.componentInstance.ctxProp = 'Some other <div>HTML</div>'; rootTC.detectChanges(); expect(DOM.getInnerHTML(rootTC.componentViewChildren[0].nativeElement)) .toEqual('Some other <div>HTML</div>'); async.done(); }); })); it('should consume directive watch expression change.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var tpl = '<div>' + '<div my-dir [elprop]="ctxProp"></div>' + '<div my-dir elprop="Hi there!"></div>' + '<div my-dir elprop="Hi {{\'there!\'}}"></div>' + '<div my-dir elprop="One more {{ctxProp}}"></div>' + '</div>'; tcb.overrideView(MyComp, new viewAnn.View({template: tpl, directives: [MyDir]})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].inject(MyDir).dirProp) .toEqual('Hello World!'); expect(rootTC.componentViewChildren[1].inject(MyDir).dirProp).toEqual('Hi there!'); expect(rootTC.componentViewChildren[2].inject(MyDir).dirProp).toEqual('Hi there!'); expect(rootTC.componentViewChildren[3].inject(MyDir).dirProp) .toEqual('One more Hello World!'); async.done(); }); })); describe('pipes', () => { it("should support pipes in bindings", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyCompWithPipes, new viewAnn.View({ template: '<div my-dir #dir="mydir" [elprop]="ctxProp | double"></div>', directives: [MyDir] })) .createAsync(MyCompWithPipes) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'a'; rootTC.detectChanges(); var dir = rootTC.componentViewChildren[0].getLocal('dir'); expect(dir.dirProp).toEqual('aa'); async.done(); }); })); }); it('should support nested components.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View({template: '<child-cmp></child-cmp>', directives: [ChildComp]})) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText('hello'); async.done(); }); })); // GH issue 328 - https://github.com/angular/angular/issues/328 it('should support different directive types on a single node', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp my-dir [elprop]="ctxProp"></child-cmp>', directives: [MyDir, ChildComp] })) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); var tc = rootTC.componentViewChildren[0]; expect(tc.inject(MyDir).dirProp).toEqual('Hello World!'); expect(tc.inject(ChildComp).dirProp).toEqual(null); async.done(); }); })); it('should support directives where a binding attribute is not given', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ // No attribute "el-prop" specified. template: '<p my-dir></p>', directives: [MyDir] })) .createAsync(MyComp) .then((rootTC) => { async.done(); }); })); it('should execute a given directive once, even if specified multiple times', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p no-duplicate></p>', directives: [ DuplicateDir, DuplicateDir, [DuplicateDir, [DuplicateDir, bind(DuplicateDir).toClass(DuplicateDir)]] ] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.nativeElement).toHaveText('noduplicate'); async.done(); }); })); it('should use the last directive binding per directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p no-duplicate></p>', directives: [ bind(DuplicateDir) .toClass(DuplicateDir), bind(DuplicateDir).toClass(OtherDuplicateDir) ] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.nativeElement).toHaveText('othernoduplicate'); async.done(); }); })); it('should support directives where a selector matches property binding', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View( {template: '<p [id]="ctxProp"></p>', directives: [IdDir]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var idDir = tc.inject(IdDir); rootTC.componentInstance.ctxProp = 'some_id'; rootTC.detectChanges(); expect(idDir.id).toEqual('some_id'); rootTC.componentInstance.ctxProp = 'other_id'; rootTC.detectChanges(); expect(idDir.id).toEqual('other_id'); async.done(); }); })); it('should allow specifying directives as bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp></child-cmp>', directives: [bind(ChildComp).toClass(ChildComp)] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText('hello'); async.done(); }); })); it('should read directives metadata from their binding token', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div public-api><div needs-public-api></div></div>', directives: [bind(PublicApi).toClass(PrivateImpl), NeedsPublicApi] })) .createAsync(MyComp) .then((rootTC) => { async.done(); }); })); it('should support template directives via `<template>` elements.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><template some-viewport var-greeting="some-tmpl"><copy-me>{{greeting}}</copy-me></template></div>', directives: [SomeViewport] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); var childNodesOfWrapper = rootTC.componentViewChildren; // 1 template + 2 copies. expect(childNodesOfWrapper.length).toBe(3); expect(childNodesOfWrapper[1].nativeElement).toHaveText('hello'); expect(childNodesOfWrapper[2].nativeElement).toHaveText('again'); async.done(); }); })); it('should support template directives via `template` attribute.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><copy-me template="some-viewport: var greeting=some-tmpl">{{greeting}}</copy-me></div>', directives: [SomeViewport] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); var childNodesOfWrapper = rootTC.componentViewChildren; // 1 template + 2 copies. expect(childNodesOfWrapper.length).toBe(3); expect(childNodesOfWrapper[1].nativeElement).toHaveText('hello'); expect(childNodesOfWrapper[2].nativeElement).toHaveText('again'); async.done(); }); })); it('should allow to transplant embedded ProtoViews into other ViewContainers', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<some-directive><toolbar><template toolbarpart var-toolbar-prop="toolbarProp">{{ctxProp}},{{toolbarProp}},<cmp-with-ancestor></cmp-with-ancestor></template></toolbar></some-directive>', directives: [SomeDirective, CompWithAncestor, ToolbarComponent, ToolbarPart] })) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'From myComp'; rootTC.detectChanges(); expect(rootTC.nativeElement) .toHaveText( 'TOOLBAR(From myComp,From toolbar,Component with an injected ancestor)'); async.done(); }); })); describe("variable bindings", () => { it('should assign a component to a var-', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-alice></child-cmp></p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('alice')) .toBeAnInstanceOf(ChildComp); async.done(); })})); it('should assign a directive to a var-', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><div export-dir #localdir="dir"></div></p>', directives: [ExportDir] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('localdir')) .toBeAnInstanceOf(ExportDir); async.done(); }); })); it('should make the assigned component accessible in property bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-alice></child-cmp>{{alice.ctxProp}}</p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.nativeElement) .toHaveText('hellohello'); // this first one is the // component, the second one is // the text binding async.done(); })})); it('should assign two component instances each with a var-', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-alice></child-cmp><child-cmp var-bob></p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('alice')) .toBeAnInstanceOf(ChildComp); expect(rootTC.componentViewChildren[0].getLocal('bob')) .toBeAnInstanceOf(ChildComp); expect(rootTC.componentViewChildren[0].getLocal('alice')) .not.toBe(rootTC.componentViewChildren[0].getLocal('bob')); async.done(); })})); it('should assign the component instance to a var- with shorthand syntax', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp #alice></child-cmp>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('alice')) .toBeAnInstanceOf(ChildComp); async.done(); })})); it('should assign the element instance to a user-defined variable', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View( {template: '<p><div var-alice><i>Hello</i></div></p>'})) .createAsync(MyComp) .then((rootTC) => { var value = rootTC.componentViewChildren[0].getLocal('alice'); expect(value).not.toBe(null); expect(value.tagName.toLowerCase()).toEqual('div'); async.done(); })})); it('should change dash-case to camel-case', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-super-alice></child-cmp></p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('superAlice')) .toBeAnInstanceOf(ChildComp); async.done(); }); })); it('should allow to use variables in a for loop', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><div *ng-for="var i of [1]"><child-cmp-no-template #cmp></child-cmp-no-template>{{i}}-{{cmp.ctxProp}}</div></div>', directives: [ChildCompNoTemplate, NgFor] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); // Get the element at index 1, since index 0 is the <template>. expect(rootTC.componentViewChildren[1].nativeElement).toHaveText("1-hello"); async.done(); }); })); }); describe("ON_PUSH components", () => { it("should use ChangeDetectorRef to manually request a check", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<push-cmp-with-ref #cmp></push-cmp-with-ref>', directives: [[[PushCmpWithRef]]] })) .createAsync(MyComp) .then((rootTC) => { var cmp = rootTC.componentViewChildren[0].getLocal('cmp'); rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); cmp.propagate(); rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(2); async.done(); })})); it("should be checked when its bindings got updated", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<push-cmp [prop]="ctxProp" #cmp></push-cmp>', directives: [[[PushCmp]]] })) .createAsync(MyComp) .then((rootTC) => { var cmp = rootTC.componentViewChildren[0].getLocal('cmp'); rootTC.componentInstance.ctxProp = "one"; rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); rootTC.componentInstance.ctxProp = "two"; rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(2); async.done(); })})); it('should not affect updating properties on the component', inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<push-cmp-with-ref [prop]="ctxProp" #cmp></push-cmp-with-ref>', directives: [[[PushCmpWithRef]]] })) .createAsync(MyComp) .then((rootTC) => { var cmp = rootTC.componentViewChildren[0].getLocal('cmp'); rootTC.componentInstance.ctxProp = "one"; rootTC.detectChanges(); expect(cmp.prop).toEqual("one"); rootTC.componentInstance.ctxProp = "two"; rootTC.detectChanges(); expect(cmp.prop).toEqual("two"); async.done(); })})); }); it('should create a component that injects an @Ancestor', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <some-directive> <p> <cmp-with-ancestor #child></cmp-with-ancestor> </p> </some-directive>`, directives: [SomeDirective, CompWithAncestor] })) .createAsync(MyComp) .then((rootTC) => { var childComponent = rootTC.componentViewChildren[0].getLocal('child'); expect(childComponent.myAncestor).toBeAnInstanceOf(SomeDirective); async.done(); })})); it('should create a component that injects an @Ancestor through viewcontainer directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <some-directive> <p *ng-if="true"> <cmp-with-ancestor #child></cmp-with-ancestor> </p> </some-directive>`, directives: [SomeDirective, CompWithAncestor, NgIf] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); var tc = rootTC.componentViewChildren[0].children[1]; var childComponent = tc.getLocal('child'); expect(childComponent.myAncestor).toBeAnInstanceOf(SomeDirective); async.done(); }); })); it('should support events via EventEmitter', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div emitter listener></div>', directives: [DirectiveEmitingEvent, DirectiveListeningEvent] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var emitter = tc.inject(DirectiveEmitingEvent); var listener = tc.inject(DirectiveListeningEvent); expect(listener.msg).toEqual(''); ObservableWrapper.subscribe(emitter.event, (_) => { expect(listener.msg).toEqual('fired !'); async.done(); }); emitter.fireEvent('fired !'); }); })); it('should support [()] syntax', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div [(control)]="ctxProp" two-way></div>', directives: [DirectiveWithTwoWayBinding] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var dir = tc.inject(DirectiveWithTwoWayBinding); rootTC.componentInstance.ctxProp = 'one'; rootTC.detectChanges(); expect(dir.value).toEqual('one'); ObservableWrapper.subscribe(dir.control, (_) => { expect(rootTC.componentInstance.ctxProp).toEqual('two'); async.done(); }); dir.triggerChange('two'); }); })); if (DOM.supportsDOMEvents()) { it("should support invoking methods on the host element via hostActions", inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div update-host-actions></div>', directives: [DirectiveUpdatingHostActions] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var nativeElement = tc.nativeElement; var updateHost = tc.inject(DirectiveUpdatingHostActions); ObservableWrapper.subscribe(updateHost.setAttr, (_) => { expect(DOM.hasAttribute(nativeElement, 'update-host-actions')).toBe(true); async.done(); }); updateHost.triggerSetAttr('value'); }); })); } it('should support render events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<div listener></div>', directives: [DirectiveListeningDomEvent]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(tc.nativeElement, 'domEvent'); expect(listener.eventType).toEqual('domEvent'); async.done(); }); })); it('should support render global events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<div listener></div>', directives: [DirectiveListeningDomEvent]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(listener.eventType).toEqual('window_domEvent'); listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(DOM.getGlobalEventTarget("document"), 'domEvent'); expect(listener.eventType).toEqual('document_domEvent'); rootTC.destroy(); listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(DOM.getGlobalEventTarget("body"), 'domEvent'); expect(listener.eventType).toEqual(''); async.done(); }); })); it('should support updating host element via hostAttributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div update-host-attributes></div>', directives: [DirectiveUpdatingHostAttributes] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(DOM.getAttribute(rootTC.componentViewChildren[0].nativeElement, "role")) .toEqual("button"); async.done(); }); })); it('should support updating host element via hostProperties', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div update-host-properties></div>', directives: [DirectiveUpdatingHostProperties] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var updateHost = tc.inject(DirectiveUpdatingHostProperties); updateHost.id = "newId"; rootTC.detectChanges(); expect(tc.nativeElement.id).toEqual("newId"); async.done(); }); })); if (DOM.supportsDOMEvents()) { it('should support preventing default on render events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<input type="checkbox" listenerprevent></input><input type="checkbox" listenernoprevent></input>', directives: [DirectiveListeningDomEventPrevent, DirectiveListeningDomEventNoPrevent] })) .createAsync(MyComp) .then((rootTC) => { expect(DOM.getChecked(rootTC.componentViewChildren[0].nativeElement)) .toBeFalsy(); expect(DOM.getChecked(rootTC.componentViewChildren[1].nativeElement)) .toBeFalsy(); DOM.dispatchEvent(rootTC.componentViewChildren[0].nativeElement, DOM.createMouseEvent('click')); DOM.dispatchEvent(rootTC.componentViewChildren[1].nativeElement, DOM.createMouseEvent('click')); expect(DOM.getChecked(rootTC.componentViewChildren[0].nativeElement)) .toBeFalsy(); expect(DOM.getChecked(rootTC.componentViewChildren[1].nativeElement)) .toBeTruthy(); async.done(); }); })); } it('should support render global events from multiple directives', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div *ng-if="ctxBoolProp" listener listenerother></div>', directives: [NgIf, DirectiveListeningDomEvent, DirectiveListeningDomEventOther] })) .createAsync(MyComp) .then((rootTC) => { globalCounter = 0; rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); var tc = rootTC.componentViewChildren[1]; var listener = tc.inject(DirectiveListeningDomEvent); var listenerother = tc.inject(DirectiveListeningDomEventOther); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(listener.eventType).toEqual('window_domEvent'); expect(listenerother.eventType).toEqual('other_domEvent'); expect(globalCounter).toEqual(1); rootTC.componentInstance.ctxBoolProp = false; rootTC.detectChanges(); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(globalCounter).toEqual(1); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(globalCounter).toEqual(2); async.done(); }); })); describe('dynamic ViewContainers', () => { it('should allow to create a ViewContainerRef at any bound location', inject([TestComponentBuilder, AsyncTestCompleter, Compiler], (tcb: TestComponentBuilder, async, compiler) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><dynamic-vp #dynamic></dynamic-vp></div>', directives: [DynamicViewport] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var dynamicVp = tc.inject(DynamicViewport); dynamicVp.done.then((_) => { rootTC.detectChanges(); expect(rootTC.componentViewChildren[1].nativeElement) .toHaveText('dynamic greet'); async.done(); }); }); })); }); it('should support static attributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<input static type="text" title>', directives: [NeedsAttribute]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var needsAttribute = tc.inject(NeedsAttribute); expect(needsAttribute.typeAttribute).toEqual('text'); expect(needsAttribute.titleAttribute).toEqual(''); expect(needsAttribute.fooAttribute).toEqual(null); async.done(); }); })); }); describe("dependency injection", () => { it("should support hostInjector", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <directive-providing-injectable > <directive-consuming-injectable #consuming> </directive-consuming-injectable> </directive-providing-injectable> `, directives: [DirectiveProvidingInjectable, DirectiveConsumingInjectable] })) .createAsync(MyComp) .then((rootTC) => { var comp = rootTC.componentViewChildren[0].getLocal("consuming"); expect(comp.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); it("should support viewInjector", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(DirectiveProvidingInjectableInView, new viewAnn.View({ template: ` <directive-consuming-injectable #consuming> </directive-consuming-injectable> `, directives: [DirectiveConsumingInjectable] })) .createAsync(DirectiveProvidingInjectableInView) .then((rootTC) => { var comp = rootTC.componentViewChildren[0].getLocal("consuming"); expect(comp.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); it("should support unbounded lookup", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <directive-providing-injectable> <directive-containing-directive-consuming-an-injectable #dir> </directive-containing-directive-consuming-an-injectable> </directive-providing-injectable> `, directives: [ DirectiveProvidingInjectable, DirectiveContainingDirectiveConsumingAnInjectable ] })) .overrideView(DirectiveContainingDirectiveConsumingAnInjectable, new viewAnn.View({ template: ` <directive-consuming-injectable-unbounded></directive-consuming-injectable-unbounded> `, directives: [DirectiveConsumingInjectableUnbounded] })) .createAsync(MyComp) .then((rootTC) => { var comp = rootTC.componentViewChildren[0].getLocal("dir"); expect(comp.directive.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); it("should support the event-bus scenario", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <grand-parent-providing-event-bus> <parent-providing-event-bus> <child-consuming-event-bus> </child-consuming-event-bus> </parent-providing-event-bus> </grand-parent-providing-event-bus> `, directives: [ GrandParentProvidingEventBus, ParentProvidingEventBus, ChildConsumingEventBus ] })) .createAsync(MyComp) .then((rootTC) => { var gpComp = rootTC.componentViewChildren[0]; var parentComp = gpComp.children[0]; var childComp = parentComp.children[0]; var grandParent = gpComp.inject(GrandParentProvidingEventBus); var parent = parentComp.inject(ParentProvidingEventBus); var child = childComp.inject(ChildConsumingEventBus); expect(grandParent.bus.name).toEqual("grandparent"); expect(parent.bus.name).toEqual("parent"); expect(parent.grandParentBus).toBe(grandParent.bus); expect(child.bus).toBe(parent.bus); async.done(); }); })); it("should create viewInjector injectables lazily", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <component-providing-logging-injectable #providing> <directive-consuming-injectable *ng-if="ctxBoolProp"> </directive-consuming-injectable> </component-providing-logging-injectable> `, directives: [DirectiveConsumingInjectable, ComponentProvidingLoggingInjectable, NgIf] })) .createAsync(MyComp) .then((rootTC) => { var providing = rootTC.componentViewChildren[0].getLocal("providing"); expect(providing.created).toBe(false); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); expect(providing.created).toBe(true); async.done(); }); })); }); describe("error handling", () => { it('should report a meaningful error when a directive is missing annotation', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({directives: [SomeDirectiveMissingAnnotation]})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `No Directive annotation found on ${stringify(SomeDirectiveMissingAnnotation)}`); async.done(); return null; }); })); it('should report a meaningful error when a component is missing view annotation', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { PromiseWrapper.catchError(tcb.createAsync(ComponentWithoutView), (e) => { expect(e.message).toEqual( `No View annotation found on component ${stringify(ComponentWithoutView)}`); async.done(); return null; }); })); it('should report a meaningful error when a directive is null', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({directives: [[null]]})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `Unexpected directive value 'null' on the View of component '${stringify(MyComp)}'`); async.done(); return null; }); })); it('should provide an error context when an error happens in the DI', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({ directives: [DirectiveThrowingAnError], template: `<directive-throwing-error></<directive-throwing-error>` })); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(DOM.nodeName(e.context.element).toUpperCase()) .toEqual("DIRECTIVE-THROWING-ERROR"); async.done(); return null; }); })); if (!IS_DARTIUM) { it('should report a meaningful error when a directive is undefined', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var undefinedValue; tcb = tcb.overrideView(MyComp, new viewAnn.View({directives: [undefinedValue]})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `Unexpected directive value 'undefined' on the View of component '${stringify(MyComp)}'`); async.done(); return null; }); })); } it('should specify a location of an error that happened during change detection (text)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '{{a.b}}'})) .createAsync(MyComp) .then((rootTC) => { expect(() => rootTC.detectChanges()) .toThrowError(containsRegexp(`{{a.b}} in ${stringify(MyComp)}`)); async.done(); })})); it('should specify a location of an error that happened during change detection (element property)', inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [title]="a.b"></div>'})) .createAsync(MyComp) .then((rootTC) => { expect(() => rootTC.detectChanges()) .toThrowError(containsRegexp(`a.b in ${stringify(MyComp)}`)); async.done(); })})); it('should specify a location of an error that happened during change detection (directive property)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp [title]="a.b"></child-cmp>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(() => rootTC.detectChanges()) .toThrowError(containsRegexp(`a.b in ${stringify(MyComp)}`)); async.done(); })})); }); it('should support imperative views', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<simple-imp-cmp></simple-imp-cmp>', directives: [SimpleImperativeViewComponent] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.nativeElement).toHaveText('hello imp view'); async.done(); }); })); it('should support moving embedded views around', inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT], (tcb, async, anchorElement) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><div *some-impvp="ctxBoolProp">hello</div></div>', directives: [SomeImperativeViewport] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(anchorElement).toHaveText(''); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); expect(anchorElement).toHaveText('hello'); rootTC.componentInstance.ctxBoolProp = false; rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText(''); async.done(); }); })); if (!IS_DARTIUM) { describe('Missing property bindings', () => { it('should throw on bindings to unknown properties', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({template: '<div unknown="{{ctxProp}}"></div>'})) PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `Can't bind to 'unknown' since it isn't a known property of the '<div>' element and there are no matching directives with a corresponding property`); async.done(); return null; }); })); it('should not throw for property binding to a non-existing property when there is a matching directive property', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<div my-dir [elprop]="ctxProp"></div>', directives: [MyDir]})) .createAsync(MyComp) .then((val) => { async.done(); }); })); }); } // Disabled until a solution is found, refs: // - https://github.com/angular/angular/issues/776 // - https://github.com/angular/angular/commit/81f3f32 xdescribe('Missing directive checks', () => { function expectCompileError(tcb, inlineTpl, errMessage, done) { tcb = tcb.overrideView(MyComp, new viewAnn.View({template: inlineTpl})); PromiseWrapper.then( tcb.createAsync(MyComp), (value) => { throw new BaseException( "Test failure: should not have come here as an exception was expected"); }, (err) => { expect(err.message).toEqual(errMessage); done(); }); } if (assertionsEnabled()) { it('should raise an error if no directive is registered for a template with template bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError(tcb, '<div><div template="if: foo"></div></div>', 'Missing directive to handle \'if\' in <div template="if: foo">', () => async.done()); })); it('should raise an error for missing template directive (1)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError(tcb, '<div><template foo></template></div>', 'Missing directive to handle: <template foo>', () => async.done()); })); it('should raise an error for missing template directive (2)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError(tcb, '<div><template *ng-if="condition"></template></div>', 'Missing directive to handle: <template *ng-if="condition">', () => async.done()); })); it('should raise an error for missing template directive (3)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError( tcb, '<div *ng-if="condition"></div>', 'Missing directive to handle \'if\' in MyComp: <div *ng-if="condition">', () => async.done()); })); } }); }); } @Injectable() class MyService { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'simple-imp-cmp'}) @View({renderer: 'simple-imp-cmp-renderer', template: ''}) @Injectable() class SimpleImperativeViewComponent { done; constructor(self: ElementRef, viewManager: AppViewManager, renderer: DomRenderer) { var hostElement = renderer.getNativeElementSync(self); DOM.appendChild(hostElement, el('hello imp view')); } } @Directive({selector: 'dynamic-vp'}) @Injectable() class DynamicViewport { done; constructor(vc: ViewContainerRef, compiler: Compiler) { var myService = new MyService(); myService.greeting = 'dynamic greet'; var bindings = Injector.resolve([bind(MyService).toValue(myService)]); this.done = compiler.compileInHost(ChildCompUsingService) .then((hostPv) => {vc.createHostView(hostPv, 0, bindings)}); } } @Directive({selector: '[my-dir]', properties: ['dirProp: elprop'], exportAs: 'mydir'}) @Injectable() class MyDir { dirProp: string; constructor() { this.dirProp = ''; } } @Component({selector: 'push-cmp', properties: ['prop'], changeDetection: ON_PUSH}) @View({template: '{{field}}'}) @Injectable() class PushCmp { numberOfChecks: number; prop; constructor() { this.numberOfChecks = 0; } get field() { this.numberOfChecks++; return "fixed"; } } @Component({selector: 'push-cmp-with-ref', properties: ['prop'], changeDetection: ON_PUSH}) @View({template: '{{field}}'}) @Injectable() class PushCmpWithRef { numberOfChecks: number; ref: ChangeDetectorRef; prop; constructor(ref: ChangeDetectorRef) { this.numberOfChecks = 0; this.ref = ref; } get field() { this.numberOfChecks++; return "fixed"; } propagate() { this.ref.requestCheck(); } } @Injectable() class PipesWithDouble extends Pipes { constructor() { super({"double": [new DoublePipeFactory()]}); } } @Component({ selector: 'my-comp-with-pipes', viewInjector: [new Binding(Pipes, {toClass: PipesWithDouble})] }) @View({directives: []}) @Injectable() class MyCompWithPipes { ctxProp: string = "initial value"; } @Component({selector: 'my-comp'}) @View({directives: []}) @Injectable() class MyComp { ctxProp: string; ctxNumProp; ctxBoolProp; constructor() { this.ctxProp = 'initial value'; this.ctxNumProp = 0; this.ctxBoolProp = false; } } @Component({selector: 'child-cmp', properties: ['dirProp'], viewInjector: [MyService]}) @View({directives: [MyDir], template: '{{ctxProp}}'}) @Injectable() class ChildComp { ctxProp: string; dirProp: string; constructor(service: MyService) { this.ctxProp = service.greeting; this.dirProp = null; } } @Component({selector: 'child-cmp-no-template'}) @View({directives: [], template: ''}) @Injectable() class ChildCompNoTemplate { ctxProp: string = 'hello'; } @Component({selector: 'child-cmp-svc'}) @View({template: '{{ctxProp}}'}) @Injectable() class ChildCompUsingService { ctxProp: string; constructor(service: MyService) { this.ctxProp = service.greeting; } } @Directive({selector: 'some-directive'}) @Injectable() class SomeDirective { } class SomeDirectiveMissingAnnotation {} @Component({selector: 'cmp-with-ancestor'}) @View({template: '<p>Component with an injected ancestor</p>', directives: [SomeDirective]}) @Injectable() class CompWithAncestor { myAncestor: SomeDirective; constructor(@Ancestor() someComp: SomeDirective) { this.myAncestor = someComp; } } @Component({selector: '[child-cmp2]', viewInjector: [MyService]}) @Injectable() class ChildComp2 { ctxProp: string; dirProp: string; constructor(service: MyService) { this.ctxProp = service.greeting; this.dirProp = null; } } @Directive({selector: '[some-viewport]'}) @Injectable() class SomeViewport { constructor(container: ViewContainerRef, templateRef: TemplateRef) { container.createEmbeddedView(templateRef).setLocal('some-tmpl', 'hello'); container.createEmbeddedView(templateRef).setLocal('some-tmpl', 'again'); } } @Injectable() class DoublePipe implements Pipe { onDestroy() {} supports(obj) { return true; } transform(value, args = null) { return `${value}${value}`; } } @Injectable() class DoublePipeFactory implements PipeFactory { supports(obj) { return true; } create(cdRef) { return new DoublePipe(); } } @Directive({selector: '[emitter]', events: ['event']}) @Injectable() class DirectiveEmitingEvent { msg: string; event: EventEmitter; constructor() { this.msg = ''; this.event = new EventEmitter(); } fireEvent(msg: string) { ObservableWrapper.callNext(this.event, msg); } } @Directive({selector: '[update-host-attributes]', host: {'role': 'button'}}) @Injectable() class DirectiveUpdatingHostAttributes { } @Directive({selector: '[update-host-properties]', host: {'[id]': 'id'}}) @Injectable() class DirectiveUpdatingHostProperties { id: string; constructor() { this.id = "one"; } } @Directive({selector: '[update-host-actions]', host: {'@setAttr': 'setAttribute'}}) @Injectable() class DirectiveUpdatingHostActions { setAttr: EventEmitter; constructor() { this.setAttr = new EventEmitter(); } triggerSetAttr(attrValue) { ObservableWrapper.callNext(this.setAttr, ["key", attrValue]); } } @Directive({selector: '[listener]', host: {'(event)': 'onEvent($event)'}}) @Injectable() class DirectiveListeningEvent { msg: string; constructor() { this.msg = ''; } onEvent(msg: string) { this.msg = msg; } } @Directive({ selector: '[listener]', host: { '(domEvent)': 'onEvent($event.type)', '(window:domEvent)': 'onWindowEvent($event.type)', '(document:domEvent)': 'onDocumentEvent($event.type)', '(body:domEvent)': 'onBodyEvent($event.type)' } }) @Injectable() class DirectiveListeningDomEvent { eventType: string; constructor() { this.eventType = ''; } onEvent(eventType: string) { this.eventType = eventType; } onWindowEvent(eventType: string) { this.eventType = "window_" + eventType; } onDocumentEvent(eventType: string) { this.eventType = "document_" + eventType; } onBodyEvent(eventType: string) { this.eventType = "body_" + eventType; } } var globalCounter = 0; @Directive({selector: '[listenerother]', host: {'(window:domEvent)': 'onEvent($event.type)'}}) @Injectable() class DirectiveListeningDomEventOther { eventType: string; counter: int; constructor() { this.eventType = ''; } onEvent(eventType: string) { globalCounter++; this.eventType = "other_" + eventType; } } @Directive({selector: '[listenerprevent]', host: {'(click)': 'onEvent($event)'}}) @Injectable() class DirectiveListeningDomEventPrevent { onEvent(event) { return false; } } @Directive({selector: '[listenernoprevent]', host: {'(click)': 'onEvent($event)'}}) @Injectable() class DirectiveListeningDomEventNoPrevent { onEvent(event) { return true; } } @Directive({selector: '[id]', properties: ['id']}) @Injectable() class IdDir { id: string; } @Directive({selector: '[static]'}) @Injectable() class NeedsAttribute { typeAttribute; titleAttribute; fooAttribute; constructor(@Attribute('type') typeAttribute: String, @Attribute('title') titleAttribute: String, @Attribute('foo') fooAttribute: String) { this.typeAttribute = typeAttribute; this.titleAttribute = titleAttribute; this.fooAttribute = fooAttribute; } } @Directive({selector: '[public-api]'}) @Injectable() class PublicApi { } @Directive({selector: '[private-impl]'}) @Injectable() class PrivateImpl extends PublicApi { } @Directive({selector: '[needs-public-api]'}) @Injectable() class NeedsPublicApi { constructor(@Ancestor() api: PublicApi) { expect(api instanceof PrivateImpl).toBe(true); } } @Directive({selector: '[toolbarpart]'}) @Injectable() class ToolbarPart { templateRef: TemplateRef; constructor(templateRef: TemplateRef) { this.templateRef = templateRef; } } @Directive({selector: '[toolbar-vc]', properties: ['toolbarVc']}) @Injectable() class ToolbarViewContainer { vc: ViewContainerRef; constructor(vc: ViewContainerRef) { this.vc = vc; } set toolbarVc(part: ToolbarPart) { var view = this.vc.createEmbeddedView(part.templateRef, 0); view.setLocal('toolbarProp', 'From toolbar'); } } @Component({selector: 'toolbar'}) @View({ template: 'TOOLBAR(<div *ng-for="var part of query" [toolbar-vc]="part"></div>)', directives: [ToolbarViewContainer, NgFor] }) @Injectable() class ToolbarComponent { query: QueryList<ToolbarPart>; ctxProp: string; constructor(@Query(ToolbarPart) query: QueryList<ToolbarPart>) { this.ctxProp = 'hello world'; this.query = query; } } @Directive({selector: '[two-way]', properties: ['value: control'], events: ['control']}) @Injectable() class DirectiveWithTwoWayBinding { control: EventEmitter; value: any; constructor() { this.control = new EventEmitter(); } triggerChange(value) { ObservableWrapper.callNext(this.control, value); } } @Injectable() class InjectableService { } function createInjectableWithLogging(inj: Injector) { inj.get(ComponentProvidingLoggingInjectable).created = true; return new InjectableService(); } @Component({ selector: 'component-providing-logging-injectable', hostInjector: [new Binding(InjectableService, {toFactory: createInjectableWithLogging, deps: [Injector]})] }) @View({template: ''}) @Injectable() class ComponentProvidingLoggingInjectable { created: boolean = false; } @Directive({selector: 'directive-providing-injectable', hostInjector: [[InjectableService]]}) @Injectable() class DirectiveProvidingInjectable { } @Component({selector: 'directive-providing-injectable', viewInjector: [[InjectableService]]}) @View({template: ''}) @Injectable() class DirectiveProvidingInjectableInView { } @Component({ selector: 'directive-providing-injectable', hostInjector: [new Binding(InjectableService, {toValue: 'host'})], viewInjector: [new Binding(InjectableService, {toValue: 'view'})] }) @View({template: ''}) @Injectable() class DirectiveProvidingInjectableInHostAndView { } @Component({selector: 'directive-consuming-injectable'}) @View({template: ''}) @Injectable() class DirectiveConsumingInjectable { injectable; constructor(@Ancestor() @Inject(InjectableService) injectable) { this.injectable = injectable; } } @Component({selector: 'directive-containing-directive-consuming-an-injectable'}) @Injectable() class DirectiveContainingDirectiveConsumingAnInjectable { directive; } @Component({selector: 'directive-consuming-injectable-unbounded'}) @View({template: ''}) @Injectable() class DirectiveConsumingInjectableUnbounded { injectable; constructor(@Unbounded() injectable: InjectableService, @Ancestor() parent: DirectiveContainingDirectiveConsumingAnInjectable) { this.injectable = injectable; parent.directive = this; } } @CONST() class EventBus { parentEventBus: EventBus; name: string; constructor(parentEventBus: EventBus, name: string) { this.parentEventBus = parentEventBus; this.name = name; } } @Directive({ selector: 'grand-parent-providing-event-bus', hostInjector: [new Binding(EventBus, {toValue: new EventBus(null, "grandparent")})] }) class GrandParentProvidingEventBus { bus: EventBus; constructor(bus: EventBus) { this.bus = bus; } } function createParentBus(peb) { return new EventBus(peb, "parent"); } @Component({ selector: 'parent-providing-event-bus', hostInjector: [ new Binding(EventBus, {toFactory: createParentBus, deps: [[EventBus, new UnboundedMetadata()]]}) ] }) @View({ directives: [forwardRef(() => ChildConsumingEventBus)], template: ` <child-consuming-event-bus></child-consuming-event-bus> ` }) class ParentProvidingEventBus { bus: EventBus; grandParentBus: EventBus; constructor(bus: EventBus, @Unbounded() grandParentBus: EventBus) { this.bus = bus; this.grandParentBus = grandParentBus; } } @Directive({selector: 'child-consuming-event-bus'}) class ChildConsumingEventBus { bus: EventBus; constructor(@Unbounded() bus: EventBus) { this.bus = bus; } } @Directive({selector: '[some-impvp]', properties: ['someImpvp']}) @Injectable() class SomeImperativeViewport { view: ViewRef; anchor; constructor(public vc: ViewContainerRef, public templateRef: TemplateRef, public renderer: DomRenderer, @Inject(ANCHOR_ELEMENT) anchor) { this.view = null; this.anchor = anchor; } set someImpvp(value: boolean) { if (isPresent(this.view)) { this.vc.clear(); this.view = null; } if (value) { this.view = this.vc.createEmbeddedView(this.templateRef); var nodes = this.renderer.getRootNodes(this.view.renderFragment); for (var i = 0; i < nodes.length; i++) { DOM.appendChild(this.anchor, nodes[i]); } } } } @Directive({selector: '[export-dir]', exportAs: 'dir'}) class ExportDir { } @Component({selector: 'comp'}) class ComponentWithoutView { } @Directive({selector: '[no-duplicate]'}) class DuplicateDir { constructor(renderer: DomRenderer, private elRef: ElementRef) { DOM.setText(elRef.nativeElement, DOM.getText(elRef.nativeElement) + 'noduplicate'); } } @Directive({selector: '[no-duplicate]'}) class OtherDuplicateDir { constructor(renderer: DomRenderer, private elRef: ElementRef) { DOM.setText(elRef.nativeElement, DOM.getText(elRef.nativeElement) + 'othernoduplicate'); } } @Directive({selector: 'directive-throwing-error'}) class DirectiveThrowingAnError { constructor() { throw new BaseException("BOOM"); ; } }
modules/angular2/test/core/compiler/integration_spec.ts
1
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0002676736330613494, 0.00017137535905931145, 0.00016362126916646957, 0.00016986785340122879, 0.000010531595762586221 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < r.args.length; ++i) {\n", " res += JSON.stringify(r.fixedArgs[i]);\n", " res += \" + \";\n", " res += this._localNames[r.args[i]];\n", " res += \" + \";\n", " }\n", " res += JSON.stringify(r.fixedArgs[r.args.length]);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " res += `${UTIL}.s(${this._localNames[r.args[i]]})`;\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_jit_generator.ts", "type": "replace", "edit_start_line_idx": 373 }
library benchmarks.e2e_test.di_perf; main() { }
modules/benchmarks/e2e_test/di_perf.dart
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0001679807755863294, 0.0001679807755863294, 0.0001679807755863294, 0.0001679807755863294, 0 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < r.args.length; ++i) {\n", " res += JSON.stringify(r.fixedArgs[i]);\n", " res += \" + \";\n", " res += this._localNames[r.args[i]];\n", " res += \" + \";\n", " }\n", " res += JSON.stringify(r.fixedArgs[r.args.length]);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " res += `${UTIL}.s(${this._localNames[r.args[i]]})`;\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_jit_generator.ts", "type": "replace", "edit_start_line_idx": 373 }
import {RouteConfig as RouteConfigAnnotation} from './route_config_impl'; import {makeDecorator} from 'angular2/src/util/decorators'; export {Route, Redirect, AsyncRoute, RouteDefinition} from './route_config_impl'; export var RouteConfig = makeDecorator(RouteConfigAnnotation);
modules/angular2/src/router/route_config_decorator.ts
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.00017398883937858045, 0.00017398883937858045, 0.00017398883937858045, 0.00017398883937858045, 0 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < r.args.length; ++i) {\n", " res += JSON.stringify(r.fixedArgs[i]);\n", " res += \" + \";\n", " res += this._localNames[r.args[i]];\n", " res += \" + \";\n", " }\n", " res += JSON.stringify(r.fixedArgs[r.args.length]);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " res += `${UTIL}.s(${this._localNames[r.args[i]]})`;\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_jit_generator.ts", "type": "replace", "edit_start_line_idx": 373 }
library bar.ng_deps.dart; import 'bar.dart'; import 'package:angular2/src/core/annotations_impl/annotations.dart'; var _visited = false; void initReflector(reflector) { if (_visited) return; _visited = true; reflector ..registerType(ToolTip, { 'factory': () => new ToolTip(), 'parameters': const [], 'annotations': const [ const Directive( selector: '[tool-tip]', events: const ['onOpen', 'close: onClose']) ] }); }
modules/angular2/test/transform/bind_generator/events_files/bar.ng_deps.dart
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0001745060581015423, 0.00017361773643642664, 0.0001727294293232262, 0.00017361773643642664, 8.883143891580403e-7 ]
{ "id": 1, "code_window": [ " return changes;\n", " }\n", "\n", " static isValueBlank(value: any): boolean { return isBlank(value); }\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " static s(value: any): string { return isPresent(value) ? `${value}` : ''; }\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_util.ts", "type": "add", "edit_start_line_idx": 153 }
///<reference path="../../src/change_detection/pipes/pipe.ts"/> import { ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, IS_DARTIUM } from 'angular2/test_lib'; import { CONST_EXPR, isPresent, isBlank, isJsObject, BaseException, FunctionWrapper } from 'angular2/src/facade/lang'; import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import { ChangeDispatcher, DehydratedException, DynamicChangeDetector, ChangeDetectionError, BindingRecord, DirectiveRecord, DirectiveIndex, Pipes, Pipe, CHECK_ALWAYS, CHECK_ONCE, CHECKED, DETACHED, ON_PUSH, DEFAULT, WrappedValue, DynamicProtoChangeDetector, ChangeDetectorDefinition, Lexer, Parser, Locals, ProtoChangeDetector } from 'angular2/change_detection'; import {JitProtoChangeDetector} from 'angular2/src/change_detection/jit_proto_change_detector'; import {getDefinition} from './change_detector_config'; import {getFactoryById} from './generated/change_detector_classes'; const _DEFAULT_CONTEXT = CONST_EXPR(new Object()); /** * Tests in this spec run against three different implementations of `AbstractChangeDetector`, * `dynamic` (which use reflection to inspect objects), `JIT` (which are generated only for * Javascript at runtime using `eval`) and `Pregen` (which are generated only for Dart prior * to app deploy to avoid the need for reflection). * * Pre-generated classes require knowledge of the shape of the change detector at the time of Dart * transformation, so in these tests we abstract a `ChangeDetectorDefinition` out into the * change_detector_config library and define a build step which pre-generates the necessary change * detectors to execute these tests. Once that built step has run, those generated change detectors * can be found in the generated/change_detector_classes library. */ export function main() { ListWrapper.forEach(['dynamic', 'JIT', 'Pregen'], (cdType) => { if (cdType == "JIT" && IS_DARTIUM) return; if (cdType == "Pregen" && !IS_DARTIUM) return; describe(`${cdType} Change Detector`, () => { function _getProtoChangeDetector(def: ChangeDetectorDefinition) { switch (cdType) { case 'dynamic': return new DynamicProtoChangeDetector(def); case 'JIT': return new JitProtoChangeDetector(def); case 'Pregen': return getFactoryById(def.id)(def); default: return null; } } function _createWithoutHydrate(expression: string) { var dispatcher = new TestDispatcher(); var cd = _getProtoChangeDetector(getDefinition(expression).cdDef).instantiate(dispatcher); return new _ChangeDetectorAndDispatcher(cd, dispatcher); } function _createChangeDetector(expression: string, context = _DEFAULT_CONTEXT, registry = null) { var dispatcher = new TestDispatcher(); var testDef = getDefinition(expression); var protoCd = _getProtoChangeDetector(testDef.cdDef); var cd = protoCd.instantiate(dispatcher); cd.hydrate(context, testDef.locals, null, registry); return new _ChangeDetectorAndDispatcher(cd, dispatcher); } function _bindSimpleValue(expression: string, context = _DEFAULT_CONTEXT) { var val = _createChangeDetector(expression, context); val.changeDetector.detectChanges(); return val.dispatcher.log; } it('should support literals', () => { expect(_bindSimpleValue('10')).toEqual(['propName=10']); }); it('should strip quotes from literals', () => { expect(_bindSimpleValue('"str"')).toEqual(['propName=str']); }); it('should support newlines in literals', () => { expect(_bindSimpleValue('"a\n\nb"')).toEqual(['propName=a\n\nb']); }); it('should support + operations', () => { expect(_bindSimpleValue('10 + 2')).toEqual(['propName=12']); }); it('should support - operations', () => { expect(_bindSimpleValue('10 - 2')).toEqual(['propName=8']); }); it('should support * operations', () => { expect(_bindSimpleValue('10 * 2')).toEqual(['propName=20']); }); it('should support / operations', () => { expect(_bindSimpleValue('10 / 2')).toEqual([`propName=${5.0}`]); }); // dart exp=5.0, js exp=5 it('should support % operations', () => { expect(_bindSimpleValue('11 % 2')).toEqual(['propName=1']); }); it('should support == operations on identical', () => { expect(_bindSimpleValue('1 == 1')).toEqual(['propName=true']); }); it('should support != operations', () => { expect(_bindSimpleValue('1 != 1')).toEqual(['propName=false']); }); it('should support == operations on coerceible', () => { var expectedValue = IS_DARTIUM ? 'false' : 'true'; expect(_bindSimpleValue('1 == true')).toEqual([`propName=${expectedValue}`]); }); it('should support === operations on identical', () => { expect(_bindSimpleValue('1 === 1')).toEqual(['propName=true']); }); it('should support !== operations', () => { expect(_bindSimpleValue('1 !== 1')).toEqual(['propName=false']); }); it('should support === operations on coerceible', () => { expect(_bindSimpleValue('1 === true')).toEqual(['propName=false']); }); it('should support true < operations', () => { expect(_bindSimpleValue('1 < 2')).toEqual(['propName=true']); }); it('should support false < operations', () => { expect(_bindSimpleValue('2 < 1')).toEqual(['propName=false']); }); it('should support false > operations', () => { expect(_bindSimpleValue('1 > 2')).toEqual(['propName=false']); }); it('should support true > operations', () => { expect(_bindSimpleValue('2 > 1')).toEqual(['propName=true']); }); it('should support true <= operations', () => { expect(_bindSimpleValue('1 <= 2')).toEqual(['propName=true']); }); it('should support equal <= operations', () => { expect(_bindSimpleValue('2 <= 2')).toEqual(['propName=true']); }); it('should support false <= operations', () => { expect(_bindSimpleValue('2 <= 1')).toEqual(['propName=false']); }); it('should support true >= operations', () => { expect(_bindSimpleValue('2 >= 1')).toEqual(['propName=true']); }); it('should support equal >= operations', () => { expect(_bindSimpleValue('2 >= 2')).toEqual(['propName=true']); }); it('should support false >= operations', () => { expect(_bindSimpleValue('1 >= 2')).toEqual(['propName=false']); }); it('should support true && operations', () => { expect(_bindSimpleValue('true && true')).toEqual(['propName=true']); }); it('should support false && operations', () => { expect(_bindSimpleValue('true && false')).toEqual(['propName=false']); }); it('should support true || operations', () => { expect(_bindSimpleValue('true || false')).toEqual(['propName=true']); }); it('should support false || operations', () => { expect(_bindSimpleValue('false || false')).toEqual(['propName=false']); }); it('should support negate', () => { expect(_bindSimpleValue('!true')).toEqual(['propName=false']); }); it('should support double negate', () => { expect(_bindSimpleValue('!!true')).toEqual(['propName=true']); }); it('should support true conditionals', () => { expect(_bindSimpleValue('1 < 2 ? 1 : 2')).toEqual(['propName=1']); }); it('should support false conditionals', () => { expect(_bindSimpleValue('1 > 2 ? 1 : 2')).toEqual(['propName=2']); }); it('should support keyed access to a list item', () => { expect(_bindSimpleValue('["foo", "bar"][0]')).toEqual(['propName=foo']); }); it('should support keyed access to a map item', () => { expect(_bindSimpleValue('{"foo": "bar"}["foo"]')).toEqual(['propName=bar']); }); it('should report all changes on the first run including uninitialized values', () => { expect(_bindSimpleValue('value', new Uninitialized())).toEqual(['propName=null']); }); it('should report all changes on the first run including null values', () => { var td = new TestData(null); expect(_bindSimpleValue('a', td)).toEqual(['propName=null']); }); it('should support simple chained property access', () => { var address = new Address('Grenoble'); var person = new Person('Victor', address); expect(_bindSimpleValue('address.city', person)).toEqual(['propName=Grenoble']); }); it('should support the safe navigation operator', () => { var person = new Person('Victor', null); expect(_bindSimpleValue('address?.city', person)).toEqual(['propName=null']); expect(_bindSimpleValue('address?.toString()', person)).toEqual(['propName=null']); person.address = new Address('MTV'); expect(_bindSimpleValue('address?.city', person)).toEqual(['propName=MTV']); expect(_bindSimpleValue('address?.toString()', person)).toEqual(['propName=MTV']); }); it('should support method calls', () => { var person = new Person('Victor'); expect(_bindSimpleValue('sayHi("Jim")', person)).toEqual(['propName=Hi, Jim']); }); it('should support function calls', () => { var td = new TestData(() => (a) => a); expect(_bindSimpleValue('a()(99)', td)).toEqual(['propName=99']); }); it('should support chained method calls', () => { var person = new Person('Victor'); var td = new TestData(person); expect(_bindSimpleValue('a.sayHi("Jim")', td)).toEqual(['propName=Hi, Jim']); }); it('should do simple watching', () => { var person = new Person('misko'); var val = _createChangeDetector('name', person); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=misko']); val.dispatcher.clear(); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); val.dispatcher.clear(); person.name = 'Misko'; val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Misko']); }); it('should support literal array', () => { var val = _createChangeDetector('[1, 2]'); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([[1, 2]]); val = _createChangeDetector('[1, a]', new TestData(2)); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([[1, 2]]); }); it('should support literal maps', () => { var val = _createChangeDetector('{z: 1}'); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues[0]['z']).toEqual(1); val = _createChangeDetector('{z: a}', new TestData(1)); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues[0]['z']).toEqual(1); }); it('should support interpolation', () => { var val = _createChangeDetector('interpolation', new TestData('value')); val.changeDetector.hydrate(new TestData('value'), null, null, null); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=BvalueA']); }); it('should escape values in literals that indicate interpolation', () => { expect(_bindSimpleValue('"$"')).toEqual(['propName=$']); }); describe('pure functions', () => { it('should preserve memoized result', () => { var person = new Person('bob'); var val = _createChangeDetector('passThrough([12])', person); val.changeDetector.detectChanges(); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([[12]]); }); }); describe('change notification', () => { describe('simple checks', () => { it('should pass a change record to the dispatcher', () => { var person = new Person('bob'); var val = _createChangeDetector('name', person); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['bob']); }); }); describe('pipes', () => { it('should pass a change record to the dispatcher', () => { var registry = new FakePipes('pipe', () => new CountingPipe()); var person = new Person('bob'); var val = _createChangeDetector('name | pipe', person, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['bob state:0']); }); it('should support arguments in pipes', () => { var registry = new FakePipes('pipe', () => new MultiArgPipe()); var address = new Address('two'); var person = new Person('value', address); var val = _createChangeDetector("name | pipe:'one':address.city", person, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['value one two default']); }); }); it('should notify the dispatcher on all changes done', () => { var val = _createChangeDetector('name', new Person('bob')); val.changeDetector.detectChanges(); expect(val.dispatcher.onAllChangesDoneCalled).toEqual(true); }); describe('updating directives', () => { var directive1; var directive2; beforeEach(() => { directive1 = new TestDirective(); directive2 = new TestDirective(); }); it('should happen directly, without invoking the dispatcher', () => { var val = _createWithoutHydrate('directNoDispatcher'); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([]); expect(directive1.a).toEqual(42); }); describe('onChange', () => { it('should notify the directive when a group of records changes', () => { var cd = _createWithoutHydrate('groupChanges').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1, directive2], []), null); cd.detectChanges(); expect(directive1.changes).toEqual({'a': 1, 'b': 2}); expect(directive2.changes).toEqual({'a': 3}); }); }); describe('onCheck', () => { it('should notify the directive when it is checked', () => { var cd = _createWithoutHydrate('directiveOnCheck').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.detectChanges(); expect(directive1.onCheckCalled).toBe(true); directive1.onCheckCalled = false; cd.detectChanges(); expect(directive1.onCheckCalled).toBe(true); }); it('should not call onCheck in detectNoChanges', () => { var cd = _createWithoutHydrate('directiveOnCheck').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.checkNoChanges(); expect(directive1.onCheckCalled).toBe(false); }); }); describe('onInit', () => { it('should notify the directive after it has been checked the first time', () => { var cd = _createWithoutHydrate('directiveOnInit').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.detectChanges(); expect(directive1.onInitCalled).toBe(true); directive1.onInitCalled = false; cd.detectChanges(); expect(directive1.onInitCalled).toBe(false); }); it('should not call onInit in detectNoChanges', () => { var cd = _createWithoutHydrate('directiveOnInit').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.checkNoChanges(); expect(directive1.onInitCalled).toBe(false); }); }); describe('onAllChangesDone', () => { it('should be called after processing all the children', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1, directive2], []), null); cd.detectChanges(); expect(directive1.onChangesDoneCalled).toBe(true); expect(directive2.onChangesDoneCalled).toBe(true); // reset directives directive1.onChangesDoneCalled = false; directive2.onChangesDoneCalled = false; // Verify that checking should not call them. cd.checkNoChanges(); expect(directive1.onChangesDoneCalled).toBe(false); expect(directive2.onChangesDoneCalled).toBe(false); // re-verify that changes are still detected cd.detectChanges(); expect(directive1.onChangesDoneCalled).toBe(true); expect(directive2.onChangesDoneCalled).toBe(true); }); it('should not be called when onAllChangesDone is false', () => { var cd = _createWithoutHydrate('noCallbacks').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.detectChanges(); expect(directive1.onChangesDoneCalled).toEqual(false); }); it('should be called in reverse order so the child is always notified before the parent', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; var onChangesDoneCalls = []; var td1; td1 = new TestDirective(() => onChangesDoneCalls.push(td1)); var td2; td2 = new TestDirective(() => onChangesDoneCalls.push(td2)); cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([td1, td2], []), null); cd.detectChanges(); expect(onChangesDoneCalls).toEqual([td2, td1]); }); it('should be called before processing shadow dom children', () => { var parent = _createWithoutHydrate('directNoDispatcher').changeDetector; var child = _createWithoutHydrate('directNoDispatcher').changeDetector; parent.addShadowDomChild(child); var orderOfOperations = []; var directiveInShadowDom = null; directiveInShadowDom = new TestDirective(() => { orderOfOperations.push(directiveInShadowDom); }); var parentDirective = null; parentDirective = new TestDirective(() => { orderOfOperations.push(parentDirective); }); parent.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([parentDirective], []), null); child.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directiveInShadowDom], []), null); parent.detectChanges(); expect(orderOfOperations).toEqual([parentDirective, directiveInShadowDom]); }); }); }); }); describe('reading directives', () => { it('should read directive properties', () => { var directive = new TestDirective(); directive.a = 'aaa'; var val = _createWithoutHydrate('readingDirectives'); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive], []), null); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['aaa']); }); }); describe('enforce no new changes', () => { it('should throw when a record gets changed after it has been checked', () => { var val = _createChangeDetector('a', new TestData('value')); expect(() => { val.changeDetector.checkNoChanges(); }) .toThrowError(new RegExp( 'Expression [\'"]a in location[\'"] has changed after it was checked')); }); it('should not break the next run', () => { var val = _createChangeDetector('a', new TestData('value')); expect(() => val.changeDetector.checkNoChanges()) .toThrowError(new RegExp( 'Expression [\'"]a in location[\'"] has changed after it was checked.')); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['value']); }); }); describe('error handling', () => { it('should wrap exceptions into ChangeDetectionError', () => { var val = _createChangeDetector('invalidFn(1)'); try { val.changeDetector.detectChanges(); throw new BaseException('fail'); } catch (e) { expect(e).toBeAnInstanceOf(ChangeDetectionError); expect(e.location).toEqual('invalidFn(1) in location'); } }); }); describe('Locals', () => { it('should read a value from locals', () => { expect(_bindSimpleValue('valueFromLocals')).toEqual(['propName=value']); }); it('should invoke a function from local', () => { expect(_bindSimpleValue('functionFromLocals')).toEqual(['propName=value']); }); it('should handle nested locals', () => { expect(_bindSimpleValue('nestedLocals')).toEqual(['propName=value']); }); it('should fall back to a regular field read when the locals map' + 'does not have the requested field', () => { expect(_bindSimpleValue('fallbackLocals', new Person('Jim'))) .toEqual(['propName=Jim']); }); it('should correctly handle nested properties', () => { var address = new Address('Grenoble'); var person = new Person('Victor', address); expect(_bindSimpleValue('contextNestedPropertyWithLocals', person)) .toEqual(['propName=Grenoble']); expect(_bindSimpleValue('localPropertyWithSimilarContext', person)) .toEqual(['propName=MTV']); }); }); describe('handle children', () => { var parent, child; beforeEach(() => { parent = _createChangeDetector('10').changeDetector; child = _createChangeDetector('"str"').changeDetector; }); it('should add light dom children', () => { parent.addChild(child); expect(parent.lightDomChildren.length).toEqual(1); expect(parent.lightDomChildren[0]).toBe(child); }); it('should add shadow dom children', () => { parent.addShadowDomChild(child); expect(parent.shadowDomChildren.length).toEqual(1); expect(parent.shadowDomChildren[0]).toBe(child); }); it('should remove light dom children', () => { parent.addChild(child); parent.removeChild(child); expect(parent.lightDomChildren).toEqual([]); }); it('should remove shadow dom children', () => { parent.addShadowDomChild(child); parent.removeShadowDomChild(child); expect(parent.shadowDomChildren.length).toEqual(0); }); }); describe('mode', () => { it('should set the mode to CHECK_ALWAYS when the default change detection is used', () => { var cd = _createWithoutHydrate('emptyUsingDefaultStrategy').changeDetector; expect(cd.mode).toEqual(null); cd.hydrate(_DEFAULT_CONTEXT, null, null, null); expect(cd.mode).toEqual(CHECK_ALWAYS); }); it('should set the mode to CHECK_ONCE when the push change detection is used', () => { var cd = _createWithoutHydrate('emptyUsingOnPushStrategy').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, null, null); expect(cd.mode).toEqual(CHECK_ONCE); }); it('should not check a detached change detector', () => { var val = _createChangeDetector('a', new TestData('value')); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, null, null); val.changeDetector.mode = DETACHED; val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); }); it('should not check a checked change detector', () => { var val = _createChangeDetector('a', new TestData('value')); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, null, null); val.changeDetector.mode = CHECKED; val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); }); it('should change CHECK_ONCE to CHECKED', () => { var cd = _createChangeDetector('10').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, null, null); cd.mode = CHECK_ONCE; cd.detectChanges(); expect(cd.mode).toEqual(CHECKED); }); it('should not change the CHECK_ALWAYS', () => { var cd = _createChangeDetector('10').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, null, null); cd.mode = CHECK_ALWAYS; cd.detectChanges(); expect(cd.mode).toEqual(CHECK_ALWAYS); }); describe('marking ON_PUSH detectors as CHECK_ONCE after an update', () => { var checkedDetector; var directives; beforeEach(() => { checkedDetector = _createWithoutHydrate('emptyUsingOnPushStrategy').changeDetector; checkedDetector.hydrate(_DEFAULT_CONTEXT, null, null, null); checkedDetector.mode = CHECKED; var targetDirective = new TestData(null); directives = new FakeDirectives([targetDirective], [checkedDetector]); }); it('should set the mode to CHECK_ONCE when a binding is updated', () => { var cd = _createWithoutHydrate('onPushRecordsUsingDefaultStrategy').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, directives, null); expect(checkedDetector.mode).toEqual(CHECKED); // evaluate the record, update the targetDirective, and mark its detector as // CHECK_ONCE cd.detectChanges(); expect(checkedDetector.mode).toEqual(CHECK_ONCE); }); }); }); describe('markPathToRootAsCheckOnce', () => { function changeDetector(mode, parent) { var val = _createChangeDetector('10'); val.changeDetector.mode = mode; if (isPresent(parent)) parent.addChild(val.changeDetector); return val.changeDetector; } it('should mark all checked detectors as CHECK_ONCE until reaching a detached one', () => { var root = changeDetector(CHECK_ALWAYS, null); var disabled = changeDetector(DETACHED, root); var parent = changeDetector(CHECKED, disabled); var checkAlwaysChild = changeDetector(CHECK_ALWAYS, parent); var checkOnceChild = changeDetector(CHECK_ONCE, checkAlwaysChild); var checkedChild = changeDetector(CHECKED, checkOnceChild); checkedChild.markPathToRootAsCheckOnce(); expect(root.mode).toEqual(CHECK_ALWAYS); expect(disabled.mode).toEqual(DETACHED); expect(parent.mode).toEqual(CHECK_ONCE); expect(checkAlwaysChild.mode).toEqual(CHECK_ALWAYS); expect(checkOnceChild.mode).toEqual(CHECK_ONCE); expect(checkedChild.mode).toEqual(CHECK_ONCE); }); }); describe('hydration', () => { it('should be able to rehydrate a change detector', () => { var cd = _createChangeDetector('name').changeDetector; cd.hydrate('some context', null, null, null); expect(cd.hydrated()).toBe(true); cd.dehydrate(); expect(cd.hydrated()).toBe(false); cd.hydrate('other context', null, null, null); expect(cd.hydrated()).toBe(true); }); it('should destroy all active pipes during dehyration', () => { var pipe = new OncePipe(); var registry = new FakePipes('pipe', () => pipe); var cd = _createChangeDetector('name | pipe', new Person('bob'), registry).changeDetector; cd.detectChanges(); cd.dehydrate(); expect(pipe.destroyCalled).toBe(true); }); it('should throw when detectChanges is called on a dehydrated detector', () => { var context = new Person('Bob'); var val = _createChangeDetector('name', context); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Bob']); val.changeDetector.dehydrate(); var dehydratedException = new DehydratedException(); expect(() => {val.changeDetector.detectChanges()}) .toThrowError(dehydratedException.toString()); expect(val.dispatcher.log).toEqual(['propName=Bob']); }); }); describe('pipes', () => { it('should support pipes', () => { var registry = new FakePipes('pipe', () => new CountingPipe()); var ctx = new Person('Megatron'); var val = _createChangeDetector('name | pipe', ctx, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron state:0']); val.dispatcher.clear(); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron state:1']); }); it('should lookup pipes in the registry when the context is not supported', () => { var registry = new FakePipes('pipe', () => new OncePipe()); var ctx = new Person('Megatron'); var cd = _createChangeDetector('name | pipe', ctx, registry).changeDetector; cd.detectChanges(); expect(registry.numberOfLookups).toEqual(1); ctx.name = 'Optimus Prime'; cd.detectChanges(); expect(registry.numberOfLookups).toEqual(2); }); it('should invoke onDestroy on a pipe before switching to another one', () => { var pipe = new OncePipe(); var registry = new FakePipes('pipe', () => pipe); var ctx = new Person('Megatron'); var cd = _createChangeDetector('name | pipe', ctx, registry).changeDetector; cd.detectChanges(); ctx.name = 'Optimus Prime'; cd.detectChanges(); expect(pipe.destroyCalled).toEqual(true); }); it('should inject the ChangeDetectorRef ' + 'of the encompassing component into a pipe', () => { var registry = new FakePipes('pipe', () => new IdentityPipe()); var cd = _createChangeDetector('name | pipe', new Person('bob'), registry).changeDetector; cd.detectChanges(); expect(registry.cdRef).toBe(cd.ref); }); }); it('should do nothing when no change', () => { var registry = new FakePipes('pipe', () => new IdentityPipe()); var ctx = new Person('Megatron'); var val = _createChangeDetector('name | pipe', ctx, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron']); val.dispatcher.clear(); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); }); it('should unwrap the wrapped value', () => { var registry = new FakePipes('pipe', () => new WrappedPipe()); var ctx = new Person('Megatron'); var val = _createChangeDetector('name | pipe', ctx, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron']); }); }); }); } class CountingPipe implements Pipe { state: number = 0; onDestroy() {} supports(newValue) { return true; } transform(value, args = null) { return `${value} state:${this.state ++}`; } } class OncePipe implements Pipe { called: boolean = false; destroyCalled: boolean = false; supports(newValue) { return !this.called; } onDestroy() { this.destroyCalled = true; } transform(value, args = null) { this.called = true; return value; } } class IdentityPipe implements Pipe { supports(obj): boolean { return true; } onDestroy() {} transform(value, args = null) { return value; } } class WrappedPipe implements Pipe { supports(obj): boolean { return true; } onDestroy() {} transform(value, args = null) { return WrappedValue.wrap(value); } } class MultiArgPipe implements Pipe { transform(value, args = null) { var arg1 = args[0]; var arg2 = args[1]; var arg3 = args.length > 2 ? args[2] : 'default'; return `${value} ${arg1} ${arg2} ${arg3}`; } supports(obj): boolean { return true; } onDestroy(): void {} } class FakePipes extends Pipes { numberOfLookups: number; pipeType: string; factory: Function; cdRef: any; constructor(pipeType, factory) { super({}); this.pipeType = pipeType; this.factory = factory; this.numberOfLookups = 0; } get(type: string, obj, cdRef?, existingPipe?) { if (type != this.pipeType) return null; this.numberOfLookups++; this.cdRef = cdRef; return this.factory(); } } class TestDirective { a; b; changes; onChangesDoneCalled; onChangesDoneSpy; onCheckCalled; onInitCalled; constructor(onChangesDoneSpy = null) { this.onChangesDoneCalled = false; this.onCheckCalled = false; this.onInitCalled = false; this.onChangesDoneSpy = onChangesDoneSpy; this.a = null; this.b = null; this.changes = null; } onCheck() { this.onCheckCalled = true; } onInit() { this.onInitCalled = true; } onChange(changes) { var r = {}; StringMapWrapper.forEach(changes, (c, key) => r[key] = c.currentValue); this.changes = r; } onAllChangesDone() { this.onChangesDoneCalled = true; if (isPresent(this.onChangesDoneSpy)) { this.onChangesDoneSpy(); } } } class Person { age: number; constructor(public name: string, public address: Address = null) {} sayHi(m) { return `Hi, ${m}`; } passThrough(val) { return val; } toString(): string { var address = this.address == null ? '' : ' address=' + this.address.toString(); return 'name=' + this.name + address; } } class Address { constructor(public city: string) {} toString(): string { return isBlank(this.city) ? '-' : this.city } } class Uninitialized { value: any; } class TestData { constructor(public a: any) {} } class FakeDirectives { constructor(public directives: List<TestData | TestDirective>, public detectors: List<ProtoChangeDetector>) {} getDirectiveFor(di: DirectiveIndex) { return this.directives[di.directiveIndex]; } getDetectorFor(di: DirectiveIndex) { return this.detectors[di.directiveIndex]; } } class TestDispatcher implements ChangeDispatcher { log: List<string>; loggedValues: List<any>; onAllChangesDoneCalled: boolean = false; constructor() { this.clear(); } clear() { this.log = []; this.loggedValues = []; this.onAllChangesDoneCalled = true; } notifyOnBinding(binding, value) { this.log.push(`${binding.propertyName}=${this._asString(value)}`); this.loggedValues.push(value); } notifyOnAllChangesDone() { this.onAllChangesDoneCalled = true; } _asString(value) { return (isBlank(value) ? 'null' : value.toString()); } } class _ChangeDetectorAndDispatcher { constructor(public changeDetector: any, public dispatcher: TestDispatcher) {} }
modules/angular2/test/change_detection/change_detector_spec.ts
1
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.9970845580101013, 0.01858823373913765, 0.00016356620471924543, 0.00017251117969863117, 0.13073405623435974 ]
{ "id": 1, "code_window": [ " return changes;\n", " }\n", "\n", " static isValueBlank(value: any): boolean { return isBlank(value); }\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " static s(value: any): string { return isPresent(value) ? `${value}` : ''; }\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_util.ts", "type": "add", "edit_start_line_idx": 153 }
/// <reference path="../typings/node/node.d.ts" /> import fs = require('fs'); import path = require('path'); function tryStatSync(path) { try { return fs.statSync(path); } catch (e) { if (e.code === "ENOENT") return null; throw e; } } export class TreeDiffer { private fingerprints: {[key: string]: string} = Object.create(null); private nextFingerprints: {[key: string]: string} = Object.create(null); private rootDirName: string; private include: RegExp = null; private exclude: RegExp = null; constructor(private label: string, private rootPath: string, includeExtensions?: string[], excludeExtensions?: string[]) { this.rootDirName = path.basename(rootPath); let buildRegexp = (arr) => new RegExp(`(${arr.reduce(combine, "")})$`, "i"); this.include = (includeExtensions || []).length ? buildRegexp(includeExtensions) : null; this.exclude = (excludeExtensions || []).length ? buildRegexp(excludeExtensions) : null; function combine(prev, curr) { if (curr.charAt(0) !== ".") { throw new Error(`Extension must begin with '.'. Was: '${curr}'`); } let kSpecialRegexpChars = /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g; curr = '(' + curr.replace(kSpecialRegexpChars, '\\$&') + ')'; return prev ? (prev + '|' + curr) : curr; } } public diffTree(): DiffResult { let result = new DirtyCheckingDiffResult(this.label, this.rootDirName); this.dirtyCheckPath(this.rootPath, result); this.detectDeletionsAndUpdateFingerprints(result); result.endTime = Date.now(); return result; } private dirtyCheckPath(rootDir: string, result: DirtyCheckingDiffResult) { fs.readdirSync(rootDir).forEach((segment) => { let absolutePath = path.join(rootDir, segment); let pathStat = fs.lstatSync(absolutePath); if (pathStat.isSymbolicLink()) { pathStat = tryStatSync(absolutePath); if (pathStat === null) return; } if (pathStat.isDirectory()) { result.directoriesChecked++; this.dirtyCheckPath(absolutePath, result); } else { if (!(this.include && !absolutePath.match(this.include)) && !(this.exclude && absolutePath.match(this.exclude))) { result.filesChecked++; let relativeFilePath = path.relative(this.rootPath, absolutePath); switch (this.isFileDirty(absolutePath, pathStat)) { case FileStatus.ADDED: result.addedPaths.push(relativeFilePath); break; case FileStatus.CHANGED: result.changedPaths.push(relativeFilePath); } } } }); return result; } private isFileDirty(path: string, stat: fs.Stats): FileStatus { let oldFingerprint = this.fingerprints[path]; let newFingerprint = `${stat.mtime.getTime()} # ${stat.size}`; this.nextFingerprints[path] = newFingerprint; if (oldFingerprint) { this.fingerprints[path] = null; if (oldFingerprint === newFingerprint) { // nothing changed return FileStatus.UNCHANGED; } return FileStatus.CHANGED; } return FileStatus.ADDED; } private detectDeletionsAndUpdateFingerprints(result: DiffResult) { for (let absolutePath in this.fingerprints) { if (!(this.include && !absolutePath.match(this.include)) && !(this.exclude && absolutePath.match(this.exclude))) { if (this.fingerprints[absolutePath] !== null) { let relativePath = path.relative(this.rootPath, absolutePath); result.removedPaths.push(relativePath); } } } this.fingerprints = this.nextFingerprints; this.nextFingerprints = Object.create(null); } } export class DiffResult { public addedPaths: string[] = []; public changedPaths: string[] = []; public removedPaths: string[] = []; constructor(public label: string = '') {} log(verbose: boolean): void {} toString(): string { // TODO(@caitp): more meaningful logging return ''; } } class DirtyCheckingDiffResult extends DiffResult { public filesChecked: number = 0; public directoriesChecked: number = 0; public startTime: number = Date.now(); public endTime: number = null; constructor(label: string, public directoryName: string) { super(label); } toString() { return `${pad(this.label, 30)}, ${pad(this.endTime - this.startTime, 5)}ms, ` + `${pad(this.addedPaths.length + this.changedPaths.length + this.removedPaths.length, 5)} changes ` + `(files: ${pad(this.filesChecked, 5)}, dirs: ${pad(this.directoriesChecked, 4)})`; } log(verbose) { let prefixedPaths = this.addedPaths.map(p => `+ ${p}`) .concat(this.changedPaths.map(p => `* ${p}`)) .concat(this.removedPaths.map(p => `- ${p}`)); console.log(`Tree diff: ${this}` + ((verbose && prefixedPaths.length) ? ` [\n ${prefixedPaths.join('\n ')}\n]` : '')); } } function pad(value, length) { value = '' + value; let whitespaceLength = (value.length < length) ? length - value.length : 0; whitespaceLength = whitespaceLength + 1; return new Array(whitespaceLength).join(' ') + value; } enum FileStatus { ADDED, UNCHANGED, CHANGED }
tools/broccoli/tree-differ.ts
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0009763369453139603, 0.00023696926655247808, 0.00016804099141154438, 0.00017237785505130887, 0.00019061849161516875 ]
{ "id": 1, "code_window": [ " return changes;\n", " }\n", "\n", " static isValueBlank(value: any): boolean { return isBlank(value); }\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " static s(value: any): string { return isPresent(value) ? `${value}` : ''; }\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_util.ts", "type": "add", "edit_start_line_idx": 153 }
library web_foo; import 'package:angular2/bootstrap.dart'; import 'package:angular2/src/reflection/reflection_capabilities.dart'; import 'bar.dart'; void main() { reflector.reflectionCapabilities = new ReflectionCapabilities(); bootstrap(MyComponent); }
modules/angular2/test/transform/integration/two_annotations_files/index.dart
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.00018172625277657062, 0.00017920856771524996, 0.0001766908826539293, 0.00017920856771524996, 0.0000025176850613206625 ]
{ "id": 1, "code_window": [ " return changes;\n", " }\n", "\n", " static isValueBlank(value: any): boolean { return isBlank(value); }\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " static s(value: any): string { return isPresent(value) ? `${value}` : ''; }\n" ], "file_path": "modules/angular2/src/change_detection/change_detection_util.ts", "type": "add", "edit_start_line_idx": 153 }
import {bind, Binding} from 'angular2/di'; import {isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {WebDriverExtension, PerfLogFeatures} from '../web_driver_extension'; import {WebDriverAdapter} from '../web_driver_adapter'; import {Promise} from 'angular2/src/facade/async'; export class FirefoxDriverExtension extends WebDriverExtension { static get BINDINGS(): List<Binding> { return _BINDINGS; } private _profilerStarted: boolean; constructor(private _driver: WebDriverAdapter) { super(); this._profilerStarted = false; } gc() { return this._driver.executeScript('window.forceGC()'); } timeBegin(name: string): Promise<any> { if (!this._profilerStarted) { this._profilerStarted = true; this._driver.executeScript('window.startProfiler();'); } return this._driver.executeScript('window.markStart("' + name + '");'); } timeEnd(name: string, restartName: string = null): Promise<any> { var script = 'window.markEnd("' + name + '");'; if (isPresent(restartName)) { script += 'window.markStart("' + restartName + '");'; } return this._driver.executeScript(script); } readPerfLog(): Promise<any> { return this._driver.executeAsyncScript('var cb = arguments[0]; window.getProfile(cb);'); } perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true, gc: true}); } supports(capabilities: StringMap<string, any>): boolean { return StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'firefox'); } } var _BINDINGS = [ bind(FirefoxDriverExtension) .toFactory((driver) => new FirefoxDriverExtension(driver), [WebDriverAdapter]) ];
modules/benchpress/src/webdriver/firefox_driver_extension.ts
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.00038535098428837955, 0.00023464905098080635, 0.0001881693460745737, 0.00019327654445078224, 0.00007585522689623758 ]
{ "id": 2, "code_window": [ " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BvalueA']);\n", " });\n", "\n", " it('should escape values in literals that indicate interpolation',\n", " () => { expect(_bindSimpleValue('\"$\"')).toEqual(['propName=$']); });\n", "\n", " describe('pure functions', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should output empty strings for null values in interpolation', () => {\n", " var val = _createChangeDetector('interpolation', new TestData('value'));\n", " val.changeDetector.hydrate(new TestData(null), null, null, null);\n", "\n", " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BA']);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/change_detection/change_detector_spec.ts", "type": "add", "edit_start_line_idx": 304 }
import { AsyncTestCompleter, beforeEach, ddescribe, xdescribe, describe, el, dispatchEvent, expect, iit, inject, IS_DARTIUM, beforeEachBindings, it, xit, containsRegexp, stringifyElement, TestComponentBuilder, fakeAsync } from 'angular2/test_lib'; import {DOM} from 'angular2/src/dom/dom_adapter'; import { Type, isPresent, BaseException, assertionsEnabled, isJsObject, global, stringify, CONST, CONST_EXPR } from 'angular2/src/facade/lang'; import {PromiseWrapper, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import { Injector, bind, Injectable, Binding, forwardRef, OpaqueToken, Inject, Ancestor, Unbounded, UnboundedMetadata } from 'angular2/di'; import { PipeFactory, Pipes, defaultPipes, Pipe, ChangeDetectorRef, ON_PUSH } from 'angular2/change_detection'; import {Directive, Component, View, Attribute, Query} from 'angular2/annotations'; import * as viewAnn from 'angular2/src/core/annotations_impl/view'; import {QueryList} from 'angular2/src/core/compiler/query_list'; import {NgIf} from 'angular2/src/directives/ng_if'; import {NgFor} from 'angular2/src/directives/ng_for'; import {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref'; import {ViewRef} from 'angular2/src/core/compiler/view_ref'; import {Compiler} from 'angular2/src/core/compiler/compiler'; import {ElementRef} from 'angular2/src/core/compiler/element_ref'; import {TemplateRef} from 'angular2/src/core/compiler/template_ref'; import {DomRenderer} from 'angular2/src/render/dom/dom_renderer'; import {AppViewManager} from 'angular2/src/core/compiler/view_manager'; const ANCHOR_ELEMENT = CONST_EXPR(new OpaqueToken('AnchorElement')); export function main() { describe('integration tests', function() { beforeEachBindings(() => [bind(ANCHOR_ELEMENT).toValue(el('<div></div>'))]); describe('react to record changes', function() { it('should consume text node changes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div>{{ctxProp}}</div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText('Hello World!'); async.done(); }); })); it('should consume element binding changes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [id]="ctxProp"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.id).toEqual('Hello World!'); async.done(); }); })); it('should consume binding to aria-* attributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [attr.aria-label]="ctxProp"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Initial aria label'; rootTC.detectChanges(); expect( DOM.getAttribute(rootTC.componentViewChildren[0].nativeElement, 'aria-label')) .toEqual('Initial aria label'); rootTC.componentInstance.ctxProp = 'Changed aria label'; rootTC.detectChanges(); expect( DOM.getAttribute(rootTC.componentViewChildren[0].nativeElement, 'aria-label')) .toEqual('Changed aria label'); async.done(); }); })); it('should consume binding to property names where attr name and property name do not match', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [tabindex]="ctxNumProp"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.tabIndex).toEqual(0); rootTC.componentInstance.ctxNumProp = 5; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.tabIndex).toEqual(5); async.done(); }); })); it('should consume binding to camel-cased properties using dash-cased syntax in templates', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<input [read-only]="ctxBoolProp">'})) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.readOnly).toBeFalsy(); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].nativeElement.readOnly).toBeTruthy(); async.done(); }); })); it('should consume binding to inner-html', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div inner-html="{{ctxProp}}"></div>'})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Some <span>HTML</span>'; rootTC.detectChanges(); expect(DOM.getInnerHTML(rootTC.componentViewChildren[0].nativeElement)) .toEqual('Some <span>HTML</span>'); rootTC.componentInstance.ctxProp = 'Some other <div>HTML</div>'; rootTC.detectChanges(); expect(DOM.getInnerHTML(rootTC.componentViewChildren[0].nativeElement)) .toEqual('Some other <div>HTML</div>'); async.done(); }); })); it('should consume directive watch expression change.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var tpl = '<div>' + '<div my-dir [elprop]="ctxProp"></div>' + '<div my-dir elprop="Hi there!"></div>' + '<div my-dir elprop="Hi {{\'there!\'}}"></div>' + '<div my-dir elprop="One more {{ctxProp}}"></div>' + '</div>'; tcb.overrideView(MyComp, new viewAnn.View({template: tpl, directives: [MyDir]})) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); expect(rootTC.componentViewChildren[0].inject(MyDir).dirProp) .toEqual('Hello World!'); expect(rootTC.componentViewChildren[1].inject(MyDir).dirProp).toEqual('Hi there!'); expect(rootTC.componentViewChildren[2].inject(MyDir).dirProp).toEqual('Hi there!'); expect(rootTC.componentViewChildren[3].inject(MyDir).dirProp) .toEqual('One more Hello World!'); async.done(); }); })); describe('pipes', () => { it("should support pipes in bindings", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyCompWithPipes, new viewAnn.View({ template: '<div my-dir #dir="mydir" [elprop]="ctxProp | double"></div>', directives: [MyDir] })) .createAsync(MyCompWithPipes) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'a'; rootTC.detectChanges(); var dir = rootTC.componentViewChildren[0].getLocal('dir'); expect(dir.dirProp).toEqual('aa'); async.done(); }); })); }); it('should support nested components.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View({template: '<child-cmp></child-cmp>', directives: [ChildComp]})) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText('hello'); async.done(); }); })); // GH issue 328 - https://github.com/angular/angular/issues/328 it('should support different directive types on a single node', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp my-dir [elprop]="ctxProp"></child-cmp>', directives: [MyDir, ChildComp] })) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'Hello World!'; rootTC.detectChanges(); var tc = rootTC.componentViewChildren[0]; expect(tc.inject(MyDir).dirProp).toEqual('Hello World!'); expect(tc.inject(ChildComp).dirProp).toEqual(null); async.done(); }); })); it('should support directives where a binding attribute is not given', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ // No attribute "el-prop" specified. template: '<p my-dir></p>', directives: [MyDir] })) .createAsync(MyComp) .then((rootTC) => { async.done(); }); })); it('should execute a given directive once, even if specified multiple times', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p no-duplicate></p>', directives: [ DuplicateDir, DuplicateDir, [DuplicateDir, [DuplicateDir, bind(DuplicateDir).toClass(DuplicateDir)]] ] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.nativeElement).toHaveText('noduplicate'); async.done(); }); })); it('should use the last directive binding per directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p no-duplicate></p>', directives: [ bind(DuplicateDir) .toClass(DuplicateDir), bind(DuplicateDir).toClass(OtherDuplicateDir) ] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.nativeElement).toHaveText('othernoduplicate'); async.done(); }); })); it('should support directives where a selector matches property binding', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View( {template: '<p [id]="ctxProp"></p>', directives: [IdDir]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var idDir = tc.inject(IdDir); rootTC.componentInstance.ctxProp = 'some_id'; rootTC.detectChanges(); expect(idDir.id).toEqual('some_id'); rootTC.componentInstance.ctxProp = 'other_id'; rootTC.detectChanges(); expect(idDir.id).toEqual('other_id'); async.done(); }); })); it('should allow specifying directives as bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp></child-cmp>', directives: [bind(ChildComp).toClass(ChildComp)] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText('hello'); async.done(); }); })); it('should read directives metadata from their binding token', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div public-api><div needs-public-api></div></div>', directives: [bind(PublicApi).toClass(PrivateImpl), NeedsPublicApi] })) .createAsync(MyComp) .then((rootTC) => { async.done(); }); })); it('should support template directives via `<template>` elements.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><template some-viewport var-greeting="some-tmpl"><copy-me>{{greeting}}</copy-me></template></div>', directives: [SomeViewport] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); var childNodesOfWrapper = rootTC.componentViewChildren; // 1 template + 2 copies. expect(childNodesOfWrapper.length).toBe(3); expect(childNodesOfWrapper[1].nativeElement).toHaveText('hello'); expect(childNodesOfWrapper[2].nativeElement).toHaveText('again'); async.done(); }); })); it('should support template directives via `template` attribute.', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><copy-me template="some-viewport: var greeting=some-tmpl">{{greeting}}</copy-me></div>', directives: [SomeViewport] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); var childNodesOfWrapper = rootTC.componentViewChildren; // 1 template + 2 copies. expect(childNodesOfWrapper.length).toBe(3); expect(childNodesOfWrapper[1].nativeElement).toHaveText('hello'); expect(childNodesOfWrapper[2].nativeElement).toHaveText('again'); async.done(); }); })); it('should allow to transplant embedded ProtoViews into other ViewContainers', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<some-directive><toolbar><template toolbarpart var-toolbar-prop="toolbarProp">{{ctxProp}},{{toolbarProp}},<cmp-with-ancestor></cmp-with-ancestor></template></toolbar></some-directive>', directives: [SomeDirective, CompWithAncestor, ToolbarComponent, ToolbarPart] })) .createAsync(MyComp) .then((rootTC) => { rootTC.componentInstance.ctxProp = 'From myComp'; rootTC.detectChanges(); expect(rootTC.nativeElement) .toHaveText( 'TOOLBAR(From myComp,From toolbar,Component with an injected ancestor)'); async.done(); }); })); describe("variable bindings", () => { it('should assign a component to a var-', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-alice></child-cmp></p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('alice')) .toBeAnInstanceOf(ChildComp); async.done(); })})); it('should assign a directive to a var-', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><div export-dir #localdir="dir"></div></p>', directives: [ExportDir] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('localdir')) .toBeAnInstanceOf(ExportDir); async.done(); }); })); it('should make the assigned component accessible in property bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-alice></child-cmp>{{alice.ctxProp}}</p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(rootTC.nativeElement) .toHaveText('hellohello'); // this first one is the // component, the second one is // the text binding async.done(); })})); it('should assign two component instances each with a var-', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-alice></child-cmp><child-cmp var-bob></p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('alice')) .toBeAnInstanceOf(ChildComp); expect(rootTC.componentViewChildren[0].getLocal('bob')) .toBeAnInstanceOf(ChildComp); expect(rootTC.componentViewChildren[0].getLocal('alice')) .not.toBe(rootTC.componentViewChildren[0].getLocal('bob')); async.done(); })})); it('should assign the component instance to a var- with shorthand syntax', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp #alice></child-cmp>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('alice')) .toBeAnInstanceOf(ChildComp); async.done(); })})); it('should assign the element instance to a user-defined variable', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View( {template: '<p><div var-alice><i>Hello</i></div></p>'})) .createAsync(MyComp) .then((rootTC) => { var value = rootTC.componentViewChildren[0].getLocal('alice'); expect(value).not.toBe(null); expect(value.tagName.toLowerCase()).toEqual('div'); async.done(); })})); it('should change dash-case to camel-case', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<p><child-cmp var-super-alice></child-cmp></p>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.componentViewChildren[0].getLocal('superAlice')) .toBeAnInstanceOf(ChildComp); async.done(); }); })); it('should allow to use variables in a for loop', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><div *ng-for="var i of [1]"><child-cmp-no-template #cmp></child-cmp-no-template>{{i}}-{{cmp.ctxProp}}</div></div>', directives: [ChildCompNoTemplate, NgFor] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); // Get the element at index 1, since index 0 is the <template>. expect(rootTC.componentViewChildren[1].nativeElement).toHaveText("1-hello"); async.done(); }); })); }); describe("ON_PUSH components", () => { it("should use ChangeDetectorRef to manually request a check", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<push-cmp-with-ref #cmp></push-cmp-with-ref>', directives: [[[PushCmpWithRef]]] })) .createAsync(MyComp) .then((rootTC) => { var cmp = rootTC.componentViewChildren[0].getLocal('cmp'); rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); cmp.propagate(); rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(2); async.done(); })})); it("should be checked when its bindings got updated", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<push-cmp [prop]="ctxProp" #cmp></push-cmp>', directives: [[[PushCmp]]] })) .createAsync(MyComp) .then((rootTC) => { var cmp = rootTC.componentViewChildren[0].getLocal('cmp'); rootTC.componentInstance.ctxProp = "one"; rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); rootTC.componentInstance.ctxProp = "two"; rootTC.detectChanges(); expect(cmp.numberOfChecks).toEqual(2); async.done(); })})); it('should not affect updating properties on the component', inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<push-cmp-with-ref [prop]="ctxProp" #cmp></push-cmp-with-ref>', directives: [[[PushCmpWithRef]]] })) .createAsync(MyComp) .then((rootTC) => { var cmp = rootTC.componentViewChildren[0].getLocal('cmp'); rootTC.componentInstance.ctxProp = "one"; rootTC.detectChanges(); expect(cmp.prop).toEqual("one"); rootTC.componentInstance.ctxProp = "two"; rootTC.detectChanges(); expect(cmp.prop).toEqual("two"); async.done(); })})); }); it('should create a component that injects an @Ancestor', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <some-directive> <p> <cmp-with-ancestor #child></cmp-with-ancestor> </p> </some-directive>`, directives: [SomeDirective, CompWithAncestor] })) .createAsync(MyComp) .then((rootTC) => { var childComponent = rootTC.componentViewChildren[0].getLocal('child'); expect(childComponent.myAncestor).toBeAnInstanceOf(SomeDirective); async.done(); })})); it('should create a component that injects an @Ancestor through viewcontainer directive', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <some-directive> <p *ng-if="true"> <cmp-with-ancestor #child></cmp-with-ancestor> </p> </some-directive>`, directives: [SomeDirective, CompWithAncestor, NgIf] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); var tc = rootTC.componentViewChildren[0].children[1]; var childComponent = tc.getLocal('child'); expect(childComponent.myAncestor).toBeAnInstanceOf(SomeDirective); async.done(); }); })); it('should support events via EventEmitter', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div emitter listener></div>', directives: [DirectiveEmitingEvent, DirectiveListeningEvent] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var emitter = tc.inject(DirectiveEmitingEvent); var listener = tc.inject(DirectiveListeningEvent); expect(listener.msg).toEqual(''); ObservableWrapper.subscribe(emitter.event, (_) => { expect(listener.msg).toEqual('fired !'); async.done(); }); emitter.fireEvent('fired !'); }); })); it('should support [()] syntax', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div [(control)]="ctxProp" two-way></div>', directives: [DirectiveWithTwoWayBinding] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var dir = tc.inject(DirectiveWithTwoWayBinding); rootTC.componentInstance.ctxProp = 'one'; rootTC.detectChanges(); expect(dir.value).toEqual('one'); ObservableWrapper.subscribe(dir.control, (_) => { expect(rootTC.componentInstance.ctxProp).toEqual('two'); async.done(); }); dir.triggerChange('two'); }); })); if (DOM.supportsDOMEvents()) { it("should support invoking methods on the host element via hostActions", inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div update-host-actions></div>', directives: [DirectiveUpdatingHostActions] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var nativeElement = tc.nativeElement; var updateHost = tc.inject(DirectiveUpdatingHostActions); ObservableWrapper.subscribe(updateHost.setAttr, (_) => { expect(DOM.hasAttribute(nativeElement, 'update-host-actions')).toBe(true); async.done(); }); updateHost.triggerSetAttr('value'); }); })); } it('should support render events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<div listener></div>', directives: [DirectiveListeningDomEvent]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(tc.nativeElement, 'domEvent'); expect(listener.eventType).toEqual('domEvent'); async.done(); }); })); it('should support render global events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<div listener></div>', directives: [DirectiveListeningDomEvent]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(listener.eventType).toEqual('window_domEvent'); listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(DOM.getGlobalEventTarget("document"), 'domEvent'); expect(listener.eventType).toEqual('document_domEvent'); rootTC.destroy(); listener = tc.inject(DirectiveListeningDomEvent); dispatchEvent(DOM.getGlobalEventTarget("body"), 'domEvent'); expect(listener.eventType).toEqual(''); async.done(); }); })); it('should support updating host element via hostAttributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div update-host-attributes></div>', directives: [DirectiveUpdatingHostAttributes] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(DOM.getAttribute(rootTC.componentViewChildren[0].nativeElement, "role")) .toEqual("button"); async.done(); }); })); it('should support updating host element via hostProperties', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div update-host-properties></div>', directives: [DirectiveUpdatingHostProperties] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var updateHost = tc.inject(DirectiveUpdatingHostProperties); updateHost.id = "newId"; rootTC.detectChanges(); expect(tc.nativeElement.id).toEqual("newId"); async.done(); }); })); if (DOM.supportsDOMEvents()) { it('should support preventing default on render events', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<input type="checkbox" listenerprevent></input><input type="checkbox" listenernoprevent></input>', directives: [DirectiveListeningDomEventPrevent, DirectiveListeningDomEventNoPrevent] })) .createAsync(MyComp) .then((rootTC) => { expect(DOM.getChecked(rootTC.componentViewChildren[0].nativeElement)) .toBeFalsy(); expect(DOM.getChecked(rootTC.componentViewChildren[1].nativeElement)) .toBeFalsy(); DOM.dispatchEvent(rootTC.componentViewChildren[0].nativeElement, DOM.createMouseEvent('click')); DOM.dispatchEvent(rootTC.componentViewChildren[1].nativeElement, DOM.createMouseEvent('click')); expect(DOM.getChecked(rootTC.componentViewChildren[0].nativeElement)) .toBeFalsy(); expect(DOM.getChecked(rootTC.componentViewChildren[1].nativeElement)) .toBeTruthy(); async.done(); }); })); } it('should support render global events from multiple directives', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div *ng-if="ctxBoolProp" listener listenerother></div>', directives: [NgIf, DirectiveListeningDomEvent, DirectiveListeningDomEventOther] })) .createAsync(MyComp) .then((rootTC) => { globalCounter = 0; rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); var tc = rootTC.componentViewChildren[1]; var listener = tc.inject(DirectiveListeningDomEvent); var listenerother = tc.inject(DirectiveListeningDomEventOther); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(listener.eventType).toEqual('window_domEvent'); expect(listenerother.eventType).toEqual('other_domEvent'); expect(globalCounter).toEqual(1); rootTC.componentInstance.ctxBoolProp = false; rootTC.detectChanges(); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(globalCounter).toEqual(1); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); dispatchEvent(DOM.getGlobalEventTarget("window"), 'domEvent'); expect(globalCounter).toEqual(2); async.done(); }); })); describe('dynamic ViewContainers', () => { it('should allow to create a ViewContainerRef at any bound location', inject([TestComponentBuilder, AsyncTestCompleter, Compiler], (tcb: TestComponentBuilder, async, compiler) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><dynamic-vp #dynamic></dynamic-vp></div>', directives: [DynamicViewport] })) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var dynamicVp = tc.inject(DynamicViewport); dynamicVp.done.then((_) => { rootTC.detectChanges(); expect(rootTC.componentViewChildren[1].nativeElement) .toHaveText('dynamic greet'); async.done(); }); }); })); }); it('should support static attributes', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<input static type="text" title>', directives: [NeedsAttribute]})) .createAsync(MyComp) .then((rootTC) => { var tc = rootTC.componentViewChildren[0]; var needsAttribute = tc.inject(NeedsAttribute); expect(needsAttribute.typeAttribute).toEqual('text'); expect(needsAttribute.titleAttribute).toEqual(''); expect(needsAttribute.fooAttribute).toEqual(null); async.done(); }); })); }); describe("dependency injection", () => { it("should support hostInjector", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <directive-providing-injectable > <directive-consuming-injectable #consuming> </directive-consuming-injectable> </directive-providing-injectable> `, directives: [DirectiveProvidingInjectable, DirectiveConsumingInjectable] })) .createAsync(MyComp) .then((rootTC) => { var comp = rootTC.componentViewChildren[0].getLocal("consuming"); expect(comp.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); it("should support viewInjector", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(DirectiveProvidingInjectableInView, new viewAnn.View({ template: ` <directive-consuming-injectable #consuming> </directive-consuming-injectable> `, directives: [DirectiveConsumingInjectable] })) .createAsync(DirectiveProvidingInjectableInView) .then((rootTC) => { var comp = rootTC.componentViewChildren[0].getLocal("consuming"); expect(comp.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); it("should support unbounded lookup", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <directive-providing-injectable> <directive-containing-directive-consuming-an-injectable #dir> </directive-containing-directive-consuming-an-injectable> </directive-providing-injectable> `, directives: [ DirectiveProvidingInjectable, DirectiveContainingDirectiveConsumingAnInjectable ] })) .overrideView(DirectiveContainingDirectiveConsumingAnInjectable, new viewAnn.View({ template: ` <directive-consuming-injectable-unbounded></directive-consuming-injectable-unbounded> `, directives: [DirectiveConsumingInjectableUnbounded] })) .createAsync(MyComp) .then((rootTC) => { var comp = rootTC.componentViewChildren[0].getLocal("dir"); expect(comp.directive.injectable).toBeAnInstanceOf(InjectableService); async.done(); }); })); it("should support the event-bus scenario", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <grand-parent-providing-event-bus> <parent-providing-event-bus> <child-consuming-event-bus> </child-consuming-event-bus> </parent-providing-event-bus> </grand-parent-providing-event-bus> `, directives: [ GrandParentProvidingEventBus, ParentProvidingEventBus, ChildConsumingEventBus ] })) .createAsync(MyComp) .then((rootTC) => { var gpComp = rootTC.componentViewChildren[0]; var parentComp = gpComp.children[0]; var childComp = parentComp.children[0]; var grandParent = gpComp.inject(GrandParentProvidingEventBus); var parent = parentComp.inject(ParentProvidingEventBus); var child = childComp.inject(ChildConsumingEventBus); expect(grandParent.bus.name).toEqual("grandparent"); expect(parent.bus.name).toEqual("parent"); expect(parent.grandParentBus).toBe(grandParent.bus); expect(child.bus).toBe(parent.bus); async.done(); }); })); it("should create viewInjector injectables lazily", inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: ` <component-providing-logging-injectable #providing> <directive-consuming-injectable *ng-if="ctxBoolProp"> </directive-consuming-injectable> </component-providing-logging-injectable> `, directives: [DirectiveConsumingInjectable, ComponentProvidingLoggingInjectable, NgIf] })) .createAsync(MyComp) .then((rootTC) => { var providing = rootTC.componentViewChildren[0].getLocal("providing"); expect(providing.created).toBe(false); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); expect(providing.created).toBe(true); async.done(); }); })); }); describe("error handling", () => { it('should report a meaningful error when a directive is missing annotation', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({directives: [SomeDirectiveMissingAnnotation]})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `No Directive annotation found on ${stringify(SomeDirectiveMissingAnnotation)}`); async.done(); return null; }); })); it('should report a meaningful error when a component is missing view annotation', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { PromiseWrapper.catchError(tcb.createAsync(ComponentWithoutView), (e) => { expect(e.message).toEqual( `No View annotation found on component ${stringify(ComponentWithoutView)}`); async.done(); return null; }); })); it('should report a meaningful error when a directive is null', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({directives: [[null]]})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `Unexpected directive value 'null' on the View of component '${stringify(MyComp)}'`); async.done(); return null; }); })); it('should provide an error context when an error happens in the DI', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({ directives: [DirectiveThrowingAnError], template: `<directive-throwing-error></<directive-throwing-error>` })); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(DOM.nodeName(e.context.element).toUpperCase()) .toEqual("DIRECTIVE-THROWING-ERROR"); async.done(); return null; }); })); if (!IS_DARTIUM) { it('should report a meaningful error when a directive is undefined', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { var undefinedValue; tcb = tcb.overrideView(MyComp, new viewAnn.View({directives: [undefinedValue]})); PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `Unexpected directive value 'undefined' on the View of component '${stringify(MyComp)}'`); async.done(); return null; }); })); } it('should specify a location of an error that happened during change detection (text)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '{{a.b}}'})) .createAsync(MyComp) .then((rootTC) => { expect(() => rootTC.detectChanges()) .toThrowError(containsRegexp(`{{a.b}} in ${stringify(MyComp)}`)); async.done(); })})); it('should specify a location of an error that happened during change detection (element property)', inject( [TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({template: '<div [title]="a.b"></div>'})) .createAsync(MyComp) .then((rootTC) => { expect(() => rootTC.detectChanges()) .toThrowError(containsRegexp(`a.b in ${stringify(MyComp)}`)); async.done(); })})); it('should specify a location of an error that happened during change detection (directive property)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<child-cmp [title]="a.b"></child-cmp>', directives: [ChildComp] })) .createAsync(MyComp) .then((rootTC) => { expect(() => rootTC.detectChanges()) .toThrowError(containsRegexp(`a.b in ${stringify(MyComp)}`)); async.done(); })})); }); it('should support imperative views', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<simple-imp-cmp></simple-imp-cmp>', directives: [SimpleImperativeViewComponent] })) .createAsync(MyComp) .then((rootTC) => { expect(rootTC.nativeElement).toHaveText('hello imp view'); async.done(); }); })); it('should support moving embedded views around', inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT], (tcb, async, anchorElement) => { tcb.overrideView(MyComp, new viewAnn.View({ template: '<div><div *some-impvp="ctxBoolProp">hello</div></div>', directives: [SomeImperativeViewport] })) .createAsync(MyComp) .then((rootTC) => { rootTC.detectChanges(); expect(anchorElement).toHaveText(''); rootTC.componentInstance.ctxBoolProp = true; rootTC.detectChanges(); expect(anchorElement).toHaveText('hello'); rootTC.componentInstance.ctxBoolProp = false; rootTC.detectChanges(); expect(rootTC.nativeElement).toHaveText(''); async.done(); }); })); if (!IS_DARTIUM) { describe('Missing property bindings', () => { it('should throw on bindings to unknown properties', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb = tcb.overrideView(MyComp, new viewAnn.View({template: '<div unknown="{{ctxProp}}"></div>'})) PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => { expect(e.message).toEqual( `Can't bind to 'unknown' since it isn't a known property of the '<div>' element and there are no matching directives with a corresponding property`); async.done(); return null; }); })); it('should not throw for property binding to a non-existing property when there is a matching directive property', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new viewAnn.View( {template: '<div my-dir [elprop]="ctxProp"></div>', directives: [MyDir]})) .createAsync(MyComp) .then((val) => { async.done(); }); })); }); } // Disabled until a solution is found, refs: // - https://github.com/angular/angular/issues/776 // - https://github.com/angular/angular/commit/81f3f32 xdescribe('Missing directive checks', () => { function expectCompileError(tcb, inlineTpl, errMessage, done) { tcb = tcb.overrideView(MyComp, new viewAnn.View({template: inlineTpl})); PromiseWrapper.then( tcb.createAsync(MyComp), (value) => { throw new BaseException( "Test failure: should not have come here as an exception was expected"); }, (err) => { expect(err.message).toEqual(errMessage); done(); }); } if (assertionsEnabled()) { it('should raise an error if no directive is registered for a template with template bindings', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError(tcb, '<div><div template="if: foo"></div></div>', 'Missing directive to handle \'if\' in <div template="if: foo">', () => async.done()); })); it('should raise an error for missing template directive (1)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError(tcb, '<div><template foo></template></div>', 'Missing directive to handle: <template foo>', () => async.done()); })); it('should raise an error for missing template directive (2)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError(tcb, '<div><template *ng-if="condition"></template></div>', 'Missing directive to handle: <template *ng-if="condition">', () => async.done()); })); it('should raise an error for missing template directive (3)', inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { expectCompileError( tcb, '<div *ng-if="condition"></div>', 'Missing directive to handle \'if\' in MyComp: <div *ng-if="condition">', () => async.done()); })); } }); }); } @Injectable() class MyService { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'simple-imp-cmp'}) @View({renderer: 'simple-imp-cmp-renderer', template: ''}) @Injectable() class SimpleImperativeViewComponent { done; constructor(self: ElementRef, viewManager: AppViewManager, renderer: DomRenderer) { var hostElement = renderer.getNativeElementSync(self); DOM.appendChild(hostElement, el('hello imp view')); } } @Directive({selector: 'dynamic-vp'}) @Injectable() class DynamicViewport { done; constructor(vc: ViewContainerRef, compiler: Compiler) { var myService = new MyService(); myService.greeting = 'dynamic greet'; var bindings = Injector.resolve([bind(MyService).toValue(myService)]); this.done = compiler.compileInHost(ChildCompUsingService) .then((hostPv) => {vc.createHostView(hostPv, 0, bindings)}); } } @Directive({selector: '[my-dir]', properties: ['dirProp: elprop'], exportAs: 'mydir'}) @Injectable() class MyDir { dirProp: string; constructor() { this.dirProp = ''; } } @Component({selector: 'push-cmp', properties: ['prop'], changeDetection: ON_PUSH}) @View({template: '{{field}}'}) @Injectable() class PushCmp { numberOfChecks: number; prop; constructor() { this.numberOfChecks = 0; } get field() { this.numberOfChecks++; return "fixed"; } } @Component({selector: 'push-cmp-with-ref', properties: ['prop'], changeDetection: ON_PUSH}) @View({template: '{{field}}'}) @Injectable() class PushCmpWithRef { numberOfChecks: number; ref: ChangeDetectorRef; prop; constructor(ref: ChangeDetectorRef) { this.numberOfChecks = 0; this.ref = ref; } get field() { this.numberOfChecks++; return "fixed"; } propagate() { this.ref.requestCheck(); } } @Injectable() class PipesWithDouble extends Pipes { constructor() { super({"double": [new DoublePipeFactory()]}); } } @Component({ selector: 'my-comp-with-pipes', viewInjector: [new Binding(Pipes, {toClass: PipesWithDouble})] }) @View({directives: []}) @Injectable() class MyCompWithPipes { ctxProp: string = "initial value"; } @Component({selector: 'my-comp'}) @View({directives: []}) @Injectable() class MyComp { ctxProp: string; ctxNumProp; ctxBoolProp; constructor() { this.ctxProp = 'initial value'; this.ctxNumProp = 0; this.ctxBoolProp = false; } } @Component({selector: 'child-cmp', properties: ['dirProp'], viewInjector: [MyService]}) @View({directives: [MyDir], template: '{{ctxProp}}'}) @Injectable() class ChildComp { ctxProp: string; dirProp: string; constructor(service: MyService) { this.ctxProp = service.greeting; this.dirProp = null; } } @Component({selector: 'child-cmp-no-template'}) @View({directives: [], template: ''}) @Injectable() class ChildCompNoTemplate { ctxProp: string = 'hello'; } @Component({selector: 'child-cmp-svc'}) @View({template: '{{ctxProp}}'}) @Injectable() class ChildCompUsingService { ctxProp: string; constructor(service: MyService) { this.ctxProp = service.greeting; } } @Directive({selector: 'some-directive'}) @Injectable() class SomeDirective { } class SomeDirectiveMissingAnnotation {} @Component({selector: 'cmp-with-ancestor'}) @View({template: '<p>Component with an injected ancestor</p>', directives: [SomeDirective]}) @Injectable() class CompWithAncestor { myAncestor: SomeDirective; constructor(@Ancestor() someComp: SomeDirective) { this.myAncestor = someComp; } } @Component({selector: '[child-cmp2]', viewInjector: [MyService]}) @Injectable() class ChildComp2 { ctxProp: string; dirProp: string; constructor(service: MyService) { this.ctxProp = service.greeting; this.dirProp = null; } } @Directive({selector: '[some-viewport]'}) @Injectable() class SomeViewport { constructor(container: ViewContainerRef, templateRef: TemplateRef) { container.createEmbeddedView(templateRef).setLocal('some-tmpl', 'hello'); container.createEmbeddedView(templateRef).setLocal('some-tmpl', 'again'); } } @Injectable() class DoublePipe implements Pipe { onDestroy() {} supports(obj) { return true; } transform(value, args = null) { return `${value}${value}`; } } @Injectable() class DoublePipeFactory implements PipeFactory { supports(obj) { return true; } create(cdRef) { return new DoublePipe(); } } @Directive({selector: '[emitter]', events: ['event']}) @Injectable() class DirectiveEmitingEvent { msg: string; event: EventEmitter; constructor() { this.msg = ''; this.event = new EventEmitter(); } fireEvent(msg: string) { ObservableWrapper.callNext(this.event, msg); } } @Directive({selector: '[update-host-attributes]', host: {'role': 'button'}}) @Injectable() class DirectiveUpdatingHostAttributes { } @Directive({selector: '[update-host-properties]', host: {'[id]': 'id'}}) @Injectable() class DirectiveUpdatingHostProperties { id: string; constructor() { this.id = "one"; } } @Directive({selector: '[update-host-actions]', host: {'@setAttr': 'setAttribute'}}) @Injectable() class DirectiveUpdatingHostActions { setAttr: EventEmitter; constructor() { this.setAttr = new EventEmitter(); } triggerSetAttr(attrValue) { ObservableWrapper.callNext(this.setAttr, ["key", attrValue]); } } @Directive({selector: '[listener]', host: {'(event)': 'onEvent($event)'}}) @Injectable() class DirectiveListeningEvent { msg: string; constructor() { this.msg = ''; } onEvent(msg: string) { this.msg = msg; } } @Directive({ selector: '[listener]', host: { '(domEvent)': 'onEvent($event.type)', '(window:domEvent)': 'onWindowEvent($event.type)', '(document:domEvent)': 'onDocumentEvent($event.type)', '(body:domEvent)': 'onBodyEvent($event.type)' } }) @Injectable() class DirectiveListeningDomEvent { eventType: string; constructor() { this.eventType = ''; } onEvent(eventType: string) { this.eventType = eventType; } onWindowEvent(eventType: string) { this.eventType = "window_" + eventType; } onDocumentEvent(eventType: string) { this.eventType = "document_" + eventType; } onBodyEvent(eventType: string) { this.eventType = "body_" + eventType; } } var globalCounter = 0; @Directive({selector: '[listenerother]', host: {'(window:domEvent)': 'onEvent($event.type)'}}) @Injectable() class DirectiveListeningDomEventOther { eventType: string; counter: int; constructor() { this.eventType = ''; } onEvent(eventType: string) { globalCounter++; this.eventType = "other_" + eventType; } } @Directive({selector: '[listenerprevent]', host: {'(click)': 'onEvent($event)'}}) @Injectable() class DirectiveListeningDomEventPrevent { onEvent(event) { return false; } } @Directive({selector: '[listenernoprevent]', host: {'(click)': 'onEvent($event)'}}) @Injectable() class DirectiveListeningDomEventNoPrevent { onEvent(event) { return true; } } @Directive({selector: '[id]', properties: ['id']}) @Injectable() class IdDir { id: string; } @Directive({selector: '[static]'}) @Injectable() class NeedsAttribute { typeAttribute; titleAttribute; fooAttribute; constructor(@Attribute('type') typeAttribute: String, @Attribute('title') titleAttribute: String, @Attribute('foo') fooAttribute: String) { this.typeAttribute = typeAttribute; this.titleAttribute = titleAttribute; this.fooAttribute = fooAttribute; } } @Directive({selector: '[public-api]'}) @Injectable() class PublicApi { } @Directive({selector: '[private-impl]'}) @Injectable() class PrivateImpl extends PublicApi { } @Directive({selector: '[needs-public-api]'}) @Injectable() class NeedsPublicApi { constructor(@Ancestor() api: PublicApi) { expect(api instanceof PrivateImpl).toBe(true); } } @Directive({selector: '[toolbarpart]'}) @Injectable() class ToolbarPart { templateRef: TemplateRef; constructor(templateRef: TemplateRef) { this.templateRef = templateRef; } } @Directive({selector: '[toolbar-vc]', properties: ['toolbarVc']}) @Injectable() class ToolbarViewContainer { vc: ViewContainerRef; constructor(vc: ViewContainerRef) { this.vc = vc; } set toolbarVc(part: ToolbarPart) { var view = this.vc.createEmbeddedView(part.templateRef, 0); view.setLocal('toolbarProp', 'From toolbar'); } } @Component({selector: 'toolbar'}) @View({ template: 'TOOLBAR(<div *ng-for="var part of query" [toolbar-vc]="part"></div>)', directives: [ToolbarViewContainer, NgFor] }) @Injectable() class ToolbarComponent { query: QueryList<ToolbarPart>; ctxProp: string; constructor(@Query(ToolbarPart) query: QueryList<ToolbarPart>) { this.ctxProp = 'hello world'; this.query = query; } } @Directive({selector: '[two-way]', properties: ['value: control'], events: ['control']}) @Injectable() class DirectiveWithTwoWayBinding { control: EventEmitter; value: any; constructor() { this.control = new EventEmitter(); } triggerChange(value) { ObservableWrapper.callNext(this.control, value); } } @Injectable() class InjectableService { } function createInjectableWithLogging(inj: Injector) { inj.get(ComponentProvidingLoggingInjectable).created = true; return new InjectableService(); } @Component({ selector: 'component-providing-logging-injectable', hostInjector: [new Binding(InjectableService, {toFactory: createInjectableWithLogging, deps: [Injector]})] }) @View({template: ''}) @Injectable() class ComponentProvidingLoggingInjectable { created: boolean = false; } @Directive({selector: 'directive-providing-injectable', hostInjector: [[InjectableService]]}) @Injectable() class DirectiveProvidingInjectable { } @Component({selector: 'directive-providing-injectable', viewInjector: [[InjectableService]]}) @View({template: ''}) @Injectable() class DirectiveProvidingInjectableInView { } @Component({ selector: 'directive-providing-injectable', hostInjector: [new Binding(InjectableService, {toValue: 'host'})], viewInjector: [new Binding(InjectableService, {toValue: 'view'})] }) @View({template: ''}) @Injectable() class DirectiveProvidingInjectableInHostAndView { } @Component({selector: 'directive-consuming-injectable'}) @View({template: ''}) @Injectable() class DirectiveConsumingInjectable { injectable; constructor(@Ancestor() @Inject(InjectableService) injectable) { this.injectable = injectable; } } @Component({selector: 'directive-containing-directive-consuming-an-injectable'}) @Injectable() class DirectiveContainingDirectiveConsumingAnInjectable { directive; } @Component({selector: 'directive-consuming-injectable-unbounded'}) @View({template: ''}) @Injectable() class DirectiveConsumingInjectableUnbounded { injectable; constructor(@Unbounded() injectable: InjectableService, @Ancestor() parent: DirectiveContainingDirectiveConsumingAnInjectable) { this.injectable = injectable; parent.directive = this; } } @CONST() class EventBus { parentEventBus: EventBus; name: string; constructor(parentEventBus: EventBus, name: string) { this.parentEventBus = parentEventBus; this.name = name; } } @Directive({ selector: 'grand-parent-providing-event-bus', hostInjector: [new Binding(EventBus, {toValue: new EventBus(null, "grandparent")})] }) class GrandParentProvidingEventBus { bus: EventBus; constructor(bus: EventBus) { this.bus = bus; } } function createParentBus(peb) { return new EventBus(peb, "parent"); } @Component({ selector: 'parent-providing-event-bus', hostInjector: [ new Binding(EventBus, {toFactory: createParentBus, deps: [[EventBus, new UnboundedMetadata()]]}) ] }) @View({ directives: [forwardRef(() => ChildConsumingEventBus)], template: ` <child-consuming-event-bus></child-consuming-event-bus> ` }) class ParentProvidingEventBus { bus: EventBus; grandParentBus: EventBus; constructor(bus: EventBus, @Unbounded() grandParentBus: EventBus) { this.bus = bus; this.grandParentBus = grandParentBus; } } @Directive({selector: 'child-consuming-event-bus'}) class ChildConsumingEventBus { bus: EventBus; constructor(@Unbounded() bus: EventBus) { this.bus = bus; } } @Directive({selector: '[some-impvp]', properties: ['someImpvp']}) @Injectable() class SomeImperativeViewport { view: ViewRef; anchor; constructor(public vc: ViewContainerRef, public templateRef: TemplateRef, public renderer: DomRenderer, @Inject(ANCHOR_ELEMENT) anchor) { this.view = null; this.anchor = anchor; } set someImpvp(value: boolean) { if (isPresent(this.view)) { this.vc.clear(); this.view = null; } if (value) { this.view = this.vc.createEmbeddedView(this.templateRef); var nodes = this.renderer.getRootNodes(this.view.renderFragment); for (var i = 0; i < nodes.length; i++) { DOM.appendChild(this.anchor, nodes[i]); } } } } @Directive({selector: '[export-dir]', exportAs: 'dir'}) class ExportDir { } @Component({selector: 'comp'}) class ComponentWithoutView { } @Directive({selector: '[no-duplicate]'}) class DuplicateDir { constructor(renderer: DomRenderer, private elRef: ElementRef) { DOM.setText(elRef.nativeElement, DOM.getText(elRef.nativeElement) + 'noduplicate'); } } @Directive({selector: '[no-duplicate]'}) class OtherDuplicateDir { constructor(renderer: DomRenderer, private elRef: ElementRef) { DOM.setText(elRef.nativeElement, DOM.getText(elRef.nativeElement) + 'othernoduplicate'); } } @Directive({selector: 'directive-throwing-error'}) class DirectiveThrowingAnError { constructor() { throw new BaseException("BOOM"); ; } }
modules/angular2/test/core/compiler/integration_spec.ts
1
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0005592539091594517, 0.0001812243863241747, 0.0001625999138923362, 0.00017462058167438954, 0.000035052013117820024 ]
{ "id": 2, "code_window": [ " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BvalueA']);\n", " });\n", "\n", " it('should escape values in literals that indicate interpolation',\n", " () => { expect(_bindSimpleValue('\"$\"')).toEqual(['propName=$']); });\n", "\n", " describe('pure functions', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should output empty strings for null values in interpolation', () => {\n", " var val = _createChangeDetector('interpolation', new TestData('value'));\n", " val.changeDetector.hydrate(new TestData(null), null, null, null);\n", "\n", " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BA']);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/change_detection/change_detector_spec.ts", "type": "add", "edit_start_line_idx": 304 }
/// <reference path="../../globals.d.ts" /> var _global: BrowserNodeGlobal = <any>(typeof window === 'undefined' ? global : window); export {_global as global}; export var Type = Function; export type Type = new (...args: any[]) => any; export function getTypeNameForDebugging(type: Type): string { return type['name']; } export class BaseException extends Error { stack; constructor(public message?: string, private _originalException?, private _originalStack?, private _context?) { super(message); this.stack = (<any>new Error(message)).stack; } get originalException(): any { return this._originalException; } get originalStack(): any { return this._originalStack; } get context(): any { return this._context; } toString(): string { return this.message; } } export function makeTypeError(message?: string): Error { return new TypeError(message); } export var Math = _global.Math; export var Date = _global.Date; var assertionsEnabled_ = typeof _global['assert'] !== 'undefined'; export function assertionsEnabled(): boolean { return assertionsEnabled_; } // TODO: remove calls to assert in production environment // Note: Can't just export this and import in in other files // as `assert` is a reserved keyword in Dart _global.assert = function assert(condition) { if (assertionsEnabled_) { _global['assert'].call(condition); } }; export function ENUM_INDEX(value: int): int { return value; } // This function is needed only to properly support Dart's const expressions // see https://github.com/angular/ts2dart/pull/151 for more info export function CONST_EXPR<T>(expr: T): T { return expr; } export function CONST():<T>(target: T) => T { return (target) => target; } export function ABSTRACT():<T>(target: T) => T { return (t) => t; } // Note: This is only a marker annotation needed for ts2dart. // This is written so that is can be used as a Traceur annotation // or a Typescript decorator. export function IMPLEMENTS(_):<T>(target: T) => T { return (t) => t; } export function isPresent(obj: any): boolean { return obj !== undefined && obj !== null; } export function isBlank(obj: any): boolean { return obj === undefined || obj === null; } export function isString(obj: any): boolean { return typeof obj === "string"; } export function isFunction(obj: any): boolean { return typeof obj === "function"; } export function isType(obj: any): boolean { return isFunction(obj); } export function isStringMap(obj: any): boolean { return typeof obj === 'object' && obj !== null; } export function isPromise(obj: any): boolean { return obj instanceof (<any>_global).Promise; } export function isArray(obj: any): boolean { return Array.isArray(obj); } export function isNumber(obj): boolean { return typeof obj === 'number'; } export function isDate(obj): boolean { return obj instanceof Date && !isNaN(obj.valueOf()); } export function stringify(token): string { if (typeof token === 'string') { return token; } if (token === undefined || token === null) { return '' + token; } if (token.name) { return token.name; } var res = token.toString(); var newLineIndex = res.indexOf("\n"); return (newLineIndex === -1) ? res : res.substring(0, newLineIndex); } // serialize / deserialize enum exist only for consistency with dart API // enums in typescript don't need to be serialized export function serializeEnum(val): int { return val; } export function deserializeEnum(val, values: Map<int, any>): any { return val; } export class StringWrapper { static fromCharCode(code: int): string { return String.fromCharCode(code); } static charCodeAt(s: string, index: int): number { return s.charCodeAt(index); } static split(s: string, regExp: RegExp): List<string> { return s.split(regExp); } static equals(s: string, s2: string): boolean { return s === s2; } static replace(s: string, from: string, replace: string): string { return s.replace(from, replace); } static replaceAll(s: string, from: RegExp, replace: string): string { return s.replace(from, replace); } static toUpperCase(s: string): string { return s.toUpperCase(); } static toLowerCase(s: string): string { return s.toLowerCase(); } static startsWith(s: string, start: string): boolean { return s.startsWith(start); } static substring(s: string, start: int, end: int = null): string { return s.substring(start, end === null ? undefined : end); } static replaceAllMapped(s: string, from: RegExp, cb: Function): string { return s.replace(from, function(...matches) { // Remove offset & string from the result array matches.splice(-2, 2); // The callback receives match, p1, ..., pn return cb(matches); }); } static contains(s: string, substr: string): boolean { return s.indexOf(substr) != -1; } static compare(a: string, b: string): int { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } } export class StringJoiner { constructor(public parts = []) {} add(part: string): void { this.parts.push(part); } toString(): string { return this.parts.join(""); } } export class NumberParseError extends BaseException { name: string; constructor(public message: string) { super(); } toString(): string { return this.message; } } export class NumberWrapper { static toFixed(n: number, fractionDigits: int): string { return n.toFixed(fractionDigits); } static equal(a: number, b: number): boolean { return a === b; } static parseIntAutoRadix(text: string): int { var result: int = parseInt(text); if (isNaN(result)) { throw new NumberParseError("Invalid integer literal when parsing " + text); } return result; } static parseInt(text: string, radix: int): int { if (radix == 10) { if (/^(\-|\+)?[0-9]+$/.test(text)) { return parseInt(text, radix); } } else if (radix == 16) { if (/^(\-|\+)?[0-9ABCDEFabcdef]+$/.test(text)) { return parseInt(text, radix); } } else { var result: int = parseInt(text, radix); if (!isNaN(result)) { return result; } } throw new NumberParseError("Invalid integer literal when parsing " + text + " in base " + radix); } // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. static parseFloat(text: string): number { return parseFloat(text); } static get NaN(): number { return NaN; } static isNaN(value: any): boolean { return isNaN(value); } static isInteger(value: any): boolean { return Number.isInteger(value); } } export var RegExp = _global.RegExp; export class RegExpWrapper { static create(regExpStr: string, flags: string = ''): RegExp { flags = flags.replace(/g/g, ''); return new _global.RegExp(regExpStr, flags + 'g'); } static firstMatch(regExp: RegExp, input: string): List<string> { // Reset multimatch regex state regExp.lastIndex = 0; return regExp.exec(input); } static test(regExp: RegExp, input: string): boolean { return regExp.test(input); } static matcher(regExp: RegExp, input: string): { re: RegExp; input: string } { // Reset regex state for the case // someone did not loop over all matches // last time. regExp.lastIndex = 0; return {re: regExp, input: input}; } } export class RegExpMatcherWrapper { static next(matcher: { re: RegExp; input: string }): string[] { return matcher.re.exec(matcher.input); } } export class FunctionWrapper { static apply(fn: Function, posArgs: any): any { return fn.apply(null, posArgs); } } // JS has NaN !== NaN export function looseIdentical(a, b): boolean { return a === b || typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b); } // JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise) // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map export function getMapKey<T>(value: T): T { return value; } export function normalizeBlank(obj: Object): any { return isBlank(obj) ? null : obj; } export function normalizeBool(obj: boolean): boolean { return isBlank(obj) ? false : obj; } export function isJsObject(o: any): boolean { return o !== null && (typeof o === "function" || typeof o === "object"); } export function print(obj: Error | Object) { if (obj instanceof BaseException) { console.log(obj.stack); } else { console.log(obj); } } // Can't be all uppercase as our transpiler would think it is a special directive... export class Json { static parse(s: string): Object { return _global.JSON.parse(s); } static stringify(data: Object): string { // Dart doesn't take 3 arguments return _global.JSON.stringify(data, null, 2); } } export class DateWrapper { static create(year: int, month: int = 1, day: int = 1, hour: int = 0, minutes: int = 0, seconds: int = 0, milliseconds: int = 0): Date { return new Date(year, month - 1, day, hour, minutes, seconds, milliseconds); } static fromMillis(ms: int): Date { return new Date(ms); } static toMillis(date: Date): int { return date.getTime(); } static now(): Date { return new Date(); } static toJson(date: Date): string { return date.toJSON(); } }
modules/angular2/src/facade/lang.ts
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0005815382464788854, 0.00018659145280253142, 0.0001649575133342296, 0.00017489369201939553, 0.00006813972140662372 ]
{ "id": 2, "code_window": [ " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BvalueA']);\n", " });\n", "\n", " it('should escape values in literals that indicate interpolation',\n", " () => { expect(_bindSimpleValue('\"$\"')).toEqual(['propName=$']); });\n", "\n", " describe('pure functions', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should output empty strings for null values in interpolation', () => {\n", " var val = _createChangeDetector('interpolation', new TestData('value'));\n", " val.changeDetector.hydrate(new TestData(null), null, null, null);\n", "\n", " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BA']);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/change_detection/change_detector_spec.ts", "type": "add", "edit_start_line_idx": 304 }
import { AST, AstVisitor, AccessMember, Assignment, Binary, Chain, Conditional, EmptyExpr, If, BindingPipe, FunctionCall, ImplicitReceiver, Interpolation, KeyedAccess, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, SafeAccessMember, SafeMethodCall } from 'angular2/src/change_detection/parser/ast'; import {StringWrapper, isPresent, isString} from 'angular2/src/facade/lang'; export class Unparser implements AstVisitor { private static _quoteRegExp = /"/g; private _expression: string; unparse(ast: AST) { this._expression = ''; this._visit(ast); return this._expression; } visitAccessMember(ast: AccessMember) { this._visit(ast.receiver); this._expression += ast.receiver instanceof ImplicitReceiver ? `${ast.name}` : `.${ast.name}`; } visitAssignment(ast: Assignment) { this._visit(ast.target); this._expression += ' = '; this._visit(ast.value); } visitBinary(ast: Binary) { this._visit(ast.left); this._expression += ` ${ast.operation} `; this._visit(ast.right); } visitChain(ast: Chain) { var len = ast.expressions.length; for (let i = 0; i < len; i++) { this._visit(ast.expressions[i]); this._expression += i == len - 1 ? ';' : '; '; } } visitConditional(ast: Conditional) { this._visit(ast.condition); this._expression += ' ? '; this._visit(ast.trueExp); this._expression += ' : '; this._visit(ast.falseExp); } visitIf(ast: If) { this._expression += 'if ('; this._visit(ast.condition); this._expression += ') '; this._visitExpOrBlock(ast.trueExp); if (isPresent(ast.falseExp)) { this._expression += ' else '; this._visitExpOrBlock(ast.falseExp); } } visitPipe(ast: BindingPipe) { this._expression += '('; this._visit(ast.exp); this._expression += ` | ${ast.name}`; ast.args.forEach(arg => { this._expression += ':'; this._visit(arg); }); this._expression += ')'; } visitFunctionCall(ast: FunctionCall) { this._visit(ast.target); this._expression += '('; var isFirst = true; ast.args.forEach(arg => { if (!isFirst) this._expression += ', '; isFirst = false; this._visit(arg); }); this._expression += ')'; } visitImplicitReceiver(ast: ImplicitReceiver) {} visitInterpolation(ast: Interpolation) { for (let i = 0; i < ast.strings.length; i++) { this._expression += ast.strings[i]; if (i < ast.expressions.length) { this._expression += '{{ '; this._visit(ast.expressions[i]); this._expression += ' }}'; } } } visitKeyedAccess(ast: KeyedAccess) { this._visit(ast.obj); this._expression += '['; this._visit(ast.key); this._expression += ']'; } visitLiteralArray(ast: LiteralArray) { this._expression += '['; var isFirst = true; ast.expressions.forEach(expression => { if (!isFirst) this._expression += ', '; isFirst = false; this._visit(expression); }); this._expression += ']'; } visitLiteralMap(ast: LiteralMap) { this._expression += '{'; var isFirst = true; for (let i = 0; i < ast.keys.length; i++) { if (!isFirst) this._expression += ', '; isFirst = false; this._expression += `${ast.keys[i]}: `; this._visit(ast.values[i]); } this._expression += '}'; } visitLiteralPrimitive(ast: LiteralPrimitive) { if (isString(ast.value)) { this._expression += `"${StringWrapper.replaceAll(ast.value, Unparser._quoteRegExp, '\"')}"`; } else { this._expression += `${ast.value}`; } } visitMethodCall(ast: MethodCall) { this._visit(ast.receiver); this._expression += ast.receiver instanceof ImplicitReceiver ? `${ast.name}(` : `.${ast.name}(`; var isFirst = true; ast.args.forEach(arg => { if (!isFirst) this._expression += ', '; isFirst = false; this._visit(arg); }); this._expression += ')'; } visitPrefixNot(ast: PrefixNot) { this._expression += '!'; this._visit(ast.expression); } visitSafeAccessMember(ast: SafeAccessMember) { this._visit(ast.receiver); this._expression += `?.${ast.name}`; } visitSafeMethodCall(ast: SafeMethodCall) { this._visit(ast.receiver); this._expression += `?.${ast.name}(`; var isFirst = true; ast.args.forEach(arg => { if (!isFirst) this._expression += ', '; isFirst = false; this._visit(arg); }); this._expression += ')'; } private _visit(ast: AST) { ast.visit(this); } private _visitExpOrBlock(ast: AST) { var isBlock = ast instanceof Chain || ast instanceof EmptyExpr; if (isBlock) this._expression += '{ '; this._visit(ast); if (isBlock) this._expression += ' }'; } }
modules/angular2/test/change_detection/parser/unparser.ts
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0002705934166442603, 0.00018030998762696981, 0.00016494224837515503, 0.00017515670333523303, 0.00002178618888137862 ]
{ "id": 2, "code_window": [ " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BvalueA']);\n", " });\n", "\n", " it('should escape values in literals that indicate interpolation',\n", " () => { expect(_bindSimpleValue('\"$\"')).toEqual(['propName=$']); });\n", "\n", " describe('pure functions', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should output empty strings for null values in interpolation', () => {\n", " var val = _createChangeDetector('interpolation', new TestData('value'));\n", " val.changeDetector.hydrate(new TestData(null), null, null, null);\n", "\n", " val.changeDetector.detectChanges();\n", "\n", " expect(val.dispatcher.log).toEqual(['propName=BA']);\n", " });\n", "\n" ], "file_path": "modules/angular2/test/change_detection/change_detector_spec.ts", "type": "add", "edit_start_line_idx": 304 }
// tree benchmark in AngularDart 1.x library tree_benchmark_ng10; import 'package:angular/angular.dart'; import 'package:angular/application_factory.dart'; import 'package:angular2/src/test_lib/benchmark_util.dart'; setup() { var m = new Module() ..bind(CompilerConfig, toValue: new CompilerConfig.withOptions(elementProbeEnabled: false)) ..bind(ScopeDigestTTL, toFactory: () => new ScopeDigestTTL.value(15), inject: []) ..bind(TreeComponent); final injector = applicationFactory().addModule(m).run(); return injector; } main() { var maxDepth = getIntParameter('depth'); final injector = setup(); final zone = injector.get(VmTurnZone); final rootScope = injector.get(Scope); var count = 0; destroyDom() { zone.run(() { rootScope.context['initData'] = new TreeNode(''); }); } createDom() { zone.run(() { var values = count++ % 2 == 0 ? ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-']; rootScope.context['initData'] = buildTree(maxDepth, values, 0); }); } bindAction('#destroyDom', destroyDom); bindAction('#createDom', createDom); } @Component( selector: 'tree', map: const {'data': '=>data'}, template: '<span> {{data.value}}' '<span ng-if="data.right != null"><tree data=data.right></span>' '<span ng-if="data.left != null"><tree data=data.left></span>' '</span>') class TreeComponent { var data; } buildTree(maxDepth, values, curDepth) { if (maxDepth == curDepth) return new TreeNode(''); return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1), buildTree(maxDepth, values, curDepth + 1)); } class TreeNode { var value; TreeNode left; TreeNode right; TreeNode([this.value, this.left, this.right]); }
modules/benchmarks_external/src/tree/tree_benchmark.dart
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0001777054712874815, 0.00017452461179345846, 0.00016706915630493313, 0.00017563049914315343, 0.000003336971531098243 ]
{ "id": 3, "code_window": [ " expect(rootTC.nativeElement).toHaveText('Hello World!');\n", " async.done();\n", " });\n", " }));\n", "\n", " it('should consume element binding changes',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div [id]=\"ctxProp\"></div>'}))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should update text node with a blank string when interpolation evaluates to null',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div>{{null}}{{ctxProp}}</div>'}))\n", " .createAsync(MyComp)\n", " .then((rootTC) => {\n", " rootTC.componentInstance.ctxProp = null;\n", "\n", " rootTC.detectChanges();\n", " expect(rootTC.nativeElement).toHaveText('');\n", " async.done();\n", " });\n", " }));\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/integration_spec.ts", "type": "add", "edit_start_line_idx": 96 }
///<reference path="../../src/change_detection/pipes/pipe.ts"/> import { ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, IS_DARTIUM } from 'angular2/test_lib'; import { CONST_EXPR, isPresent, isBlank, isJsObject, BaseException, FunctionWrapper } from 'angular2/src/facade/lang'; import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import { ChangeDispatcher, DehydratedException, DynamicChangeDetector, ChangeDetectionError, BindingRecord, DirectiveRecord, DirectiveIndex, Pipes, Pipe, CHECK_ALWAYS, CHECK_ONCE, CHECKED, DETACHED, ON_PUSH, DEFAULT, WrappedValue, DynamicProtoChangeDetector, ChangeDetectorDefinition, Lexer, Parser, Locals, ProtoChangeDetector } from 'angular2/change_detection'; import {JitProtoChangeDetector} from 'angular2/src/change_detection/jit_proto_change_detector'; import {getDefinition} from './change_detector_config'; import {getFactoryById} from './generated/change_detector_classes'; const _DEFAULT_CONTEXT = CONST_EXPR(new Object()); /** * Tests in this spec run against three different implementations of `AbstractChangeDetector`, * `dynamic` (which use reflection to inspect objects), `JIT` (which are generated only for * Javascript at runtime using `eval`) and `Pregen` (which are generated only for Dart prior * to app deploy to avoid the need for reflection). * * Pre-generated classes require knowledge of the shape of the change detector at the time of Dart * transformation, so in these tests we abstract a `ChangeDetectorDefinition` out into the * change_detector_config library and define a build step which pre-generates the necessary change * detectors to execute these tests. Once that built step has run, those generated change detectors * can be found in the generated/change_detector_classes library. */ export function main() { ListWrapper.forEach(['dynamic', 'JIT', 'Pregen'], (cdType) => { if (cdType == "JIT" && IS_DARTIUM) return; if (cdType == "Pregen" && !IS_DARTIUM) return; describe(`${cdType} Change Detector`, () => { function _getProtoChangeDetector(def: ChangeDetectorDefinition) { switch (cdType) { case 'dynamic': return new DynamicProtoChangeDetector(def); case 'JIT': return new JitProtoChangeDetector(def); case 'Pregen': return getFactoryById(def.id)(def); default: return null; } } function _createWithoutHydrate(expression: string) { var dispatcher = new TestDispatcher(); var cd = _getProtoChangeDetector(getDefinition(expression).cdDef).instantiate(dispatcher); return new _ChangeDetectorAndDispatcher(cd, dispatcher); } function _createChangeDetector(expression: string, context = _DEFAULT_CONTEXT, registry = null) { var dispatcher = new TestDispatcher(); var testDef = getDefinition(expression); var protoCd = _getProtoChangeDetector(testDef.cdDef); var cd = protoCd.instantiate(dispatcher); cd.hydrate(context, testDef.locals, null, registry); return new _ChangeDetectorAndDispatcher(cd, dispatcher); } function _bindSimpleValue(expression: string, context = _DEFAULT_CONTEXT) { var val = _createChangeDetector(expression, context); val.changeDetector.detectChanges(); return val.dispatcher.log; } it('should support literals', () => { expect(_bindSimpleValue('10')).toEqual(['propName=10']); }); it('should strip quotes from literals', () => { expect(_bindSimpleValue('"str"')).toEqual(['propName=str']); }); it('should support newlines in literals', () => { expect(_bindSimpleValue('"a\n\nb"')).toEqual(['propName=a\n\nb']); }); it('should support + operations', () => { expect(_bindSimpleValue('10 + 2')).toEqual(['propName=12']); }); it('should support - operations', () => { expect(_bindSimpleValue('10 - 2')).toEqual(['propName=8']); }); it('should support * operations', () => { expect(_bindSimpleValue('10 * 2')).toEqual(['propName=20']); }); it('should support / operations', () => { expect(_bindSimpleValue('10 / 2')).toEqual([`propName=${5.0}`]); }); // dart exp=5.0, js exp=5 it('should support % operations', () => { expect(_bindSimpleValue('11 % 2')).toEqual(['propName=1']); }); it('should support == operations on identical', () => { expect(_bindSimpleValue('1 == 1')).toEqual(['propName=true']); }); it('should support != operations', () => { expect(_bindSimpleValue('1 != 1')).toEqual(['propName=false']); }); it('should support == operations on coerceible', () => { var expectedValue = IS_DARTIUM ? 'false' : 'true'; expect(_bindSimpleValue('1 == true')).toEqual([`propName=${expectedValue}`]); }); it('should support === operations on identical', () => { expect(_bindSimpleValue('1 === 1')).toEqual(['propName=true']); }); it('should support !== operations', () => { expect(_bindSimpleValue('1 !== 1')).toEqual(['propName=false']); }); it('should support === operations on coerceible', () => { expect(_bindSimpleValue('1 === true')).toEqual(['propName=false']); }); it('should support true < operations', () => { expect(_bindSimpleValue('1 < 2')).toEqual(['propName=true']); }); it('should support false < operations', () => { expect(_bindSimpleValue('2 < 1')).toEqual(['propName=false']); }); it('should support false > operations', () => { expect(_bindSimpleValue('1 > 2')).toEqual(['propName=false']); }); it('should support true > operations', () => { expect(_bindSimpleValue('2 > 1')).toEqual(['propName=true']); }); it('should support true <= operations', () => { expect(_bindSimpleValue('1 <= 2')).toEqual(['propName=true']); }); it('should support equal <= operations', () => { expect(_bindSimpleValue('2 <= 2')).toEqual(['propName=true']); }); it('should support false <= operations', () => { expect(_bindSimpleValue('2 <= 1')).toEqual(['propName=false']); }); it('should support true >= operations', () => { expect(_bindSimpleValue('2 >= 1')).toEqual(['propName=true']); }); it('should support equal >= operations', () => { expect(_bindSimpleValue('2 >= 2')).toEqual(['propName=true']); }); it('should support false >= operations', () => { expect(_bindSimpleValue('1 >= 2')).toEqual(['propName=false']); }); it('should support true && operations', () => { expect(_bindSimpleValue('true && true')).toEqual(['propName=true']); }); it('should support false && operations', () => { expect(_bindSimpleValue('true && false')).toEqual(['propName=false']); }); it('should support true || operations', () => { expect(_bindSimpleValue('true || false')).toEqual(['propName=true']); }); it('should support false || operations', () => { expect(_bindSimpleValue('false || false')).toEqual(['propName=false']); }); it('should support negate', () => { expect(_bindSimpleValue('!true')).toEqual(['propName=false']); }); it('should support double negate', () => { expect(_bindSimpleValue('!!true')).toEqual(['propName=true']); }); it('should support true conditionals', () => { expect(_bindSimpleValue('1 < 2 ? 1 : 2')).toEqual(['propName=1']); }); it('should support false conditionals', () => { expect(_bindSimpleValue('1 > 2 ? 1 : 2')).toEqual(['propName=2']); }); it('should support keyed access to a list item', () => { expect(_bindSimpleValue('["foo", "bar"][0]')).toEqual(['propName=foo']); }); it('should support keyed access to a map item', () => { expect(_bindSimpleValue('{"foo": "bar"}["foo"]')).toEqual(['propName=bar']); }); it('should report all changes on the first run including uninitialized values', () => { expect(_bindSimpleValue('value', new Uninitialized())).toEqual(['propName=null']); }); it('should report all changes on the first run including null values', () => { var td = new TestData(null); expect(_bindSimpleValue('a', td)).toEqual(['propName=null']); }); it('should support simple chained property access', () => { var address = new Address('Grenoble'); var person = new Person('Victor', address); expect(_bindSimpleValue('address.city', person)).toEqual(['propName=Grenoble']); }); it('should support the safe navigation operator', () => { var person = new Person('Victor', null); expect(_bindSimpleValue('address?.city', person)).toEqual(['propName=null']); expect(_bindSimpleValue('address?.toString()', person)).toEqual(['propName=null']); person.address = new Address('MTV'); expect(_bindSimpleValue('address?.city', person)).toEqual(['propName=MTV']); expect(_bindSimpleValue('address?.toString()', person)).toEqual(['propName=MTV']); }); it('should support method calls', () => { var person = new Person('Victor'); expect(_bindSimpleValue('sayHi("Jim")', person)).toEqual(['propName=Hi, Jim']); }); it('should support function calls', () => { var td = new TestData(() => (a) => a); expect(_bindSimpleValue('a()(99)', td)).toEqual(['propName=99']); }); it('should support chained method calls', () => { var person = new Person('Victor'); var td = new TestData(person); expect(_bindSimpleValue('a.sayHi("Jim")', td)).toEqual(['propName=Hi, Jim']); }); it('should do simple watching', () => { var person = new Person('misko'); var val = _createChangeDetector('name', person); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=misko']); val.dispatcher.clear(); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); val.dispatcher.clear(); person.name = 'Misko'; val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Misko']); }); it('should support literal array', () => { var val = _createChangeDetector('[1, 2]'); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([[1, 2]]); val = _createChangeDetector('[1, a]', new TestData(2)); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([[1, 2]]); }); it('should support literal maps', () => { var val = _createChangeDetector('{z: 1}'); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues[0]['z']).toEqual(1); val = _createChangeDetector('{z: a}', new TestData(1)); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues[0]['z']).toEqual(1); }); it('should support interpolation', () => { var val = _createChangeDetector('interpolation', new TestData('value')); val.changeDetector.hydrate(new TestData('value'), null, null, null); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=BvalueA']); }); it('should escape values in literals that indicate interpolation', () => { expect(_bindSimpleValue('"$"')).toEqual(['propName=$']); }); describe('pure functions', () => { it('should preserve memoized result', () => { var person = new Person('bob'); var val = _createChangeDetector('passThrough([12])', person); val.changeDetector.detectChanges(); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([[12]]); }); }); describe('change notification', () => { describe('simple checks', () => { it('should pass a change record to the dispatcher', () => { var person = new Person('bob'); var val = _createChangeDetector('name', person); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['bob']); }); }); describe('pipes', () => { it('should pass a change record to the dispatcher', () => { var registry = new FakePipes('pipe', () => new CountingPipe()); var person = new Person('bob'); var val = _createChangeDetector('name | pipe', person, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['bob state:0']); }); it('should support arguments in pipes', () => { var registry = new FakePipes('pipe', () => new MultiArgPipe()); var address = new Address('two'); var person = new Person('value', address); var val = _createChangeDetector("name | pipe:'one':address.city", person, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['value one two default']); }); }); it('should notify the dispatcher on all changes done', () => { var val = _createChangeDetector('name', new Person('bob')); val.changeDetector.detectChanges(); expect(val.dispatcher.onAllChangesDoneCalled).toEqual(true); }); describe('updating directives', () => { var directive1; var directive2; beforeEach(() => { directive1 = new TestDirective(); directive2 = new TestDirective(); }); it('should happen directly, without invoking the dispatcher', () => { var val = _createWithoutHydrate('directNoDispatcher'); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual([]); expect(directive1.a).toEqual(42); }); describe('onChange', () => { it('should notify the directive when a group of records changes', () => { var cd = _createWithoutHydrate('groupChanges').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1, directive2], []), null); cd.detectChanges(); expect(directive1.changes).toEqual({'a': 1, 'b': 2}); expect(directive2.changes).toEqual({'a': 3}); }); }); describe('onCheck', () => { it('should notify the directive when it is checked', () => { var cd = _createWithoutHydrate('directiveOnCheck').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.detectChanges(); expect(directive1.onCheckCalled).toBe(true); directive1.onCheckCalled = false; cd.detectChanges(); expect(directive1.onCheckCalled).toBe(true); }); it('should not call onCheck in detectNoChanges', () => { var cd = _createWithoutHydrate('directiveOnCheck').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.checkNoChanges(); expect(directive1.onCheckCalled).toBe(false); }); }); describe('onInit', () => { it('should notify the directive after it has been checked the first time', () => { var cd = _createWithoutHydrate('directiveOnInit').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.detectChanges(); expect(directive1.onInitCalled).toBe(true); directive1.onInitCalled = false; cd.detectChanges(); expect(directive1.onInitCalled).toBe(false); }); it('should not call onInit in detectNoChanges', () => { var cd = _createWithoutHydrate('directiveOnInit').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.checkNoChanges(); expect(directive1.onInitCalled).toBe(false); }); }); describe('onAllChangesDone', () => { it('should be called after processing all the children', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1, directive2], []), null); cd.detectChanges(); expect(directive1.onChangesDoneCalled).toBe(true); expect(directive2.onChangesDoneCalled).toBe(true); // reset directives directive1.onChangesDoneCalled = false; directive2.onChangesDoneCalled = false; // Verify that checking should not call them. cd.checkNoChanges(); expect(directive1.onChangesDoneCalled).toBe(false); expect(directive2.onChangesDoneCalled).toBe(false); // re-verify that changes are still detected cd.detectChanges(); expect(directive1.onChangesDoneCalled).toBe(true); expect(directive2.onChangesDoneCalled).toBe(true); }); it('should not be called when onAllChangesDone is false', () => { var cd = _createWithoutHydrate('noCallbacks').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive1], []), null); cd.detectChanges(); expect(directive1.onChangesDoneCalled).toEqual(false); }); it('should be called in reverse order so the child is always notified before the parent', () => { var cd = _createWithoutHydrate('emptyWithDirectiveRecords').changeDetector; var onChangesDoneCalls = []; var td1; td1 = new TestDirective(() => onChangesDoneCalls.push(td1)); var td2; td2 = new TestDirective(() => onChangesDoneCalls.push(td2)); cd.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([td1, td2], []), null); cd.detectChanges(); expect(onChangesDoneCalls).toEqual([td2, td1]); }); it('should be called before processing shadow dom children', () => { var parent = _createWithoutHydrate('directNoDispatcher').changeDetector; var child = _createWithoutHydrate('directNoDispatcher').changeDetector; parent.addShadowDomChild(child); var orderOfOperations = []; var directiveInShadowDom = null; directiveInShadowDom = new TestDirective(() => { orderOfOperations.push(directiveInShadowDom); }); var parentDirective = null; parentDirective = new TestDirective(() => { orderOfOperations.push(parentDirective); }); parent.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([parentDirective], []), null); child.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directiveInShadowDom], []), null); parent.detectChanges(); expect(orderOfOperations).toEqual([parentDirective, directiveInShadowDom]); }); }); }); }); describe('reading directives', () => { it('should read directive properties', () => { var directive = new TestDirective(); directive.a = 'aaa'; var val = _createWithoutHydrate('readingDirectives'); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, new FakeDirectives([directive], []), null); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['aaa']); }); }); describe('enforce no new changes', () => { it('should throw when a record gets changed after it has been checked', () => { var val = _createChangeDetector('a', new TestData('value')); expect(() => { val.changeDetector.checkNoChanges(); }) .toThrowError(new RegExp( 'Expression [\'"]a in location[\'"] has changed after it was checked')); }); it('should not break the next run', () => { var val = _createChangeDetector('a', new TestData('value')); expect(() => val.changeDetector.checkNoChanges()) .toThrowError(new RegExp( 'Expression [\'"]a in location[\'"] has changed after it was checked.')); val.changeDetector.detectChanges(); expect(val.dispatcher.loggedValues).toEqual(['value']); }); }); describe('error handling', () => { it('should wrap exceptions into ChangeDetectionError', () => { var val = _createChangeDetector('invalidFn(1)'); try { val.changeDetector.detectChanges(); throw new BaseException('fail'); } catch (e) { expect(e).toBeAnInstanceOf(ChangeDetectionError); expect(e.location).toEqual('invalidFn(1) in location'); } }); }); describe('Locals', () => { it('should read a value from locals', () => { expect(_bindSimpleValue('valueFromLocals')).toEqual(['propName=value']); }); it('should invoke a function from local', () => { expect(_bindSimpleValue('functionFromLocals')).toEqual(['propName=value']); }); it('should handle nested locals', () => { expect(_bindSimpleValue('nestedLocals')).toEqual(['propName=value']); }); it('should fall back to a regular field read when the locals map' + 'does not have the requested field', () => { expect(_bindSimpleValue('fallbackLocals', new Person('Jim'))) .toEqual(['propName=Jim']); }); it('should correctly handle nested properties', () => { var address = new Address('Grenoble'); var person = new Person('Victor', address); expect(_bindSimpleValue('contextNestedPropertyWithLocals', person)) .toEqual(['propName=Grenoble']); expect(_bindSimpleValue('localPropertyWithSimilarContext', person)) .toEqual(['propName=MTV']); }); }); describe('handle children', () => { var parent, child; beforeEach(() => { parent = _createChangeDetector('10').changeDetector; child = _createChangeDetector('"str"').changeDetector; }); it('should add light dom children', () => { parent.addChild(child); expect(parent.lightDomChildren.length).toEqual(1); expect(parent.lightDomChildren[0]).toBe(child); }); it('should add shadow dom children', () => { parent.addShadowDomChild(child); expect(parent.shadowDomChildren.length).toEqual(1); expect(parent.shadowDomChildren[0]).toBe(child); }); it('should remove light dom children', () => { parent.addChild(child); parent.removeChild(child); expect(parent.lightDomChildren).toEqual([]); }); it('should remove shadow dom children', () => { parent.addShadowDomChild(child); parent.removeShadowDomChild(child); expect(parent.shadowDomChildren.length).toEqual(0); }); }); describe('mode', () => { it('should set the mode to CHECK_ALWAYS when the default change detection is used', () => { var cd = _createWithoutHydrate('emptyUsingDefaultStrategy').changeDetector; expect(cd.mode).toEqual(null); cd.hydrate(_DEFAULT_CONTEXT, null, null, null); expect(cd.mode).toEqual(CHECK_ALWAYS); }); it('should set the mode to CHECK_ONCE when the push change detection is used', () => { var cd = _createWithoutHydrate('emptyUsingOnPushStrategy').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, null, null); expect(cd.mode).toEqual(CHECK_ONCE); }); it('should not check a detached change detector', () => { var val = _createChangeDetector('a', new TestData('value')); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, null, null); val.changeDetector.mode = DETACHED; val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); }); it('should not check a checked change detector', () => { var val = _createChangeDetector('a', new TestData('value')); val.changeDetector.hydrate(_DEFAULT_CONTEXT, null, null, null); val.changeDetector.mode = CHECKED; val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); }); it('should change CHECK_ONCE to CHECKED', () => { var cd = _createChangeDetector('10').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, null, null); cd.mode = CHECK_ONCE; cd.detectChanges(); expect(cd.mode).toEqual(CHECKED); }); it('should not change the CHECK_ALWAYS', () => { var cd = _createChangeDetector('10').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, null, null); cd.mode = CHECK_ALWAYS; cd.detectChanges(); expect(cd.mode).toEqual(CHECK_ALWAYS); }); describe('marking ON_PUSH detectors as CHECK_ONCE after an update', () => { var checkedDetector; var directives; beforeEach(() => { checkedDetector = _createWithoutHydrate('emptyUsingOnPushStrategy').changeDetector; checkedDetector.hydrate(_DEFAULT_CONTEXT, null, null, null); checkedDetector.mode = CHECKED; var targetDirective = new TestData(null); directives = new FakeDirectives([targetDirective], [checkedDetector]); }); it('should set the mode to CHECK_ONCE when a binding is updated', () => { var cd = _createWithoutHydrate('onPushRecordsUsingDefaultStrategy').changeDetector; cd.hydrate(_DEFAULT_CONTEXT, null, directives, null); expect(checkedDetector.mode).toEqual(CHECKED); // evaluate the record, update the targetDirective, and mark its detector as // CHECK_ONCE cd.detectChanges(); expect(checkedDetector.mode).toEqual(CHECK_ONCE); }); }); }); describe('markPathToRootAsCheckOnce', () => { function changeDetector(mode, parent) { var val = _createChangeDetector('10'); val.changeDetector.mode = mode; if (isPresent(parent)) parent.addChild(val.changeDetector); return val.changeDetector; } it('should mark all checked detectors as CHECK_ONCE until reaching a detached one', () => { var root = changeDetector(CHECK_ALWAYS, null); var disabled = changeDetector(DETACHED, root); var parent = changeDetector(CHECKED, disabled); var checkAlwaysChild = changeDetector(CHECK_ALWAYS, parent); var checkOnceChild = changeDetector(CHECK_ONCE, checkAlwaysChild); var checkedChild = changeDetector(CHECKED, checkOnceChild); checkedChild.markPathToRootAsCheckOnce(); expect(root.mode).toEqual(CHECK_ALWAYS); expect(disabled.mode).toEqual(DETACHED); expect(parent.mode).toEqual(CHECK_ONCE); expect(checkAlwaysChild.mode).toEqual(CHECK_ALWAYS); expect(checkOnceChild.mode).toEqual(CHECK_ONCE); expect(checkedChild.mode).toEqual(CHECK_ONCE); }); }); describe('hydration', () => { it('should be able to rehydrate a change detector', () => { var cd = _createChangeDetector('name').changeDetector; cd.hydrate('some context', null, null, null); expect(cd.hydrated()).toBe(true); cd.dehydrate(); expect(cd.hydrated()).toBe(false); cd.hydrate('other context', null, null, null); expect(cd.hydrated()).toBe(true); }); it('should destroy all active pipes during dehyration', () => { var pipe = new OncePipe(); var registry = new FakePipes('pipe', () => pipe); var cd = _createChangeDetector('name | pipe', new Person('bob'), registry).changeDetector; cd.detectChanges(); cd.dehydrate(); expect(pipe.destroyCalled).toBe(true); }); it('should throw when detectChanges is called on a dehydrated detector', () => { var context = new Person('Bob'); var val = _createChangeDetector('name', context); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Bob']); val.changeDetector.dehydrate(); var dehydratedException = new DehydratedException(); expect(() => {val.changeDetector.detectChanges()}) .toThrowError(dehydratedException.toString()); expect(val.dispatcher.log).toEqual(['propName=Bob']); }); }); describe('pipes', () => { it('should support pipes', () => { var registry = new FakePipes('pipe', () => new CountingPipe()); var ctx = new Person('Megatron'); var val = _createChangeDetector('name | pipe', ctx, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron state:0']); val.dispatcher.clear(); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron state:1']); }); it('should lookup pipes in the registry when the context is not supported', () => { var registry = new FakePipes('pipe', () => new OncePipe()); var ctx = new Person('Megatron'); var cd = _createChangeDetector('name | pipe', ctx, registry).changeDetector; cd.detectChanges(); expect(registry.numberOfLookups).toEqual(1); ctx.name = 'Optimus Prime'; cd.detectChanges(); expect(registry.numberOfLookups).toEqual(2); }); it('should invoke onDestroy on a pipe before switching to another one', () => { var pipe = new OncePipe(); var registry = new FakePipes('pipe', () => pipe); var ctx = new Person('Megatron'); var cd = _createChangeDetector('name | pipe', ctx, registry).changeDetector; cd.detectChanges(); ctx.name = 'Optimus Prime'; cd.detectChanges(); expect(pipe.destroyCalled).toEqual(true); }); it('should inject the ChangeDetectorRef ' + 'of the encompassing component into a pipe', () => { var registry = new FakePipes('pipe', () => new IdentityPipe()); var cd = _createChangeDetector('name | pipe', new Person('bob'), registry).changeDetector; cd.detectChanges(); expect(registry.cdRef).toBe(cd.ref); }); }); it('should do nothing when no change', () => { var registry = new FakePipes('pipe', () => new IdentityPipe()); var ctx = new Person('Megatron'); var val = _createChangeDetector('name | pipe', ctx, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron']); val.dispatcher.clear(); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual([]); }); it('should unwrap the wrapped value', () => { var registry = new FakePipes('pipe', () => new WrappedPipe()); var ctx = new Person('Megatron'); var val = _createChangeDetector('name | pipe', ctx, registry); val.changeDetector.detectChanges(); expect(val.dispatcher.log).toEqual(['propName=Megatron']); }); }); }); } class CountingPipe implements Pipe { state: number = 0; onDestroy() {} supports(newValue) { return true; } transform(value, args = null) { return `${value} state:${this.state ++}`; } } class OncePipe implements Pipe { called: boolean = false; destroyCalled: boolean = false; supports(newValue) { return !this.called; } onDestroy() { this.destroyCalled = true; } transform(value, args = null) { this.called = true; return value; } } class IdentityPipe implements Pipe { supports(obj): boolean { return true; } onDestroy() {} transform(value, args = null) { return value; } } class WrappedPipe implements Pipe { supports(obj): boolean { return true; } onDestroy() {} transform(value, args = null) { return WrappedValue.wrap(value); } } class MultiArgPipe implements Pipe { transform(value, args = null) { var arg1 = args[0]; var arg2 = args[1]; var arg3 = args.length > 2 ? args[2] : 'default'; return `${value} ${arg1} ${arg2} ${arg3}`; } supports(obj): boolean { return true; } onDestroy(): void {} } class FakePipes extends Pipes { numberOfLookups: number; pipeType: string; factory: Function; cdRef: any; constructor(pipeType, factory) { super({}); this.pipeType = pipeType; this.factory = factory; this.numberOfLookups = 0; } get(type: string, obj, cdRef?, existingPipe?) { if (type != this.pipeType) return null; this.numberOfLookups++; this.cdRef = cdRef; return this.factory(); } } class TestDirective { a; b; changes; onChangesDoneCalled; onChangesDoneSpy; onCheckCalled; onInitCalled; constructor(onChangesDoneSpy = null) { this.onChangesDoneCalled = false; this.onCheckCalled = false; this.onInitCalled = false; this.onChangesDoneSpy = onChangesDoneSpy; this.a = null; this.b = null; this.changes = null; } onCheck() { this.onCheckCalled = true; } onInit() { this.onInitCalled = true; } onChange(changes) { var r = {}; StringMapWrapper.forEach(changes, (c, key) => r[key] = c.currentValue); this.changes = r; } onAllChangesDone() { this.onChangesDoneCalled = true; if (isPresent(this.onChangesDoneSpy)) { this.onChangesDoneSpy(); } } } class Person { age: number; constructor(public name: string, public address: Address = null) {} sayHi(m) { return `Hi, ${m}`; } passThrough(val) { return val; } toString(): string { var address = this.address == null ? '' : ' address=' + this.address.toString(); return 'name=' + this.name + address; } } class Address { constructor(public city: string) {} toString(): string { return isBlank(this.city) ? '-' : this.city } } class Uninitialized { value: any; } class TestData { constructor(public a: any) {} } class FakeDirectives { constructor(public directives: List<TestData | TestDirective>, public detectors: List<ProtoChangeDetector>) {} getDirectiveFor(di: DirectiveIndex) { return this.directives[di.directiveIndex]; } getDetectorFor(di: DirectiveIndex) { return this.detectors[di.directiveIndex]; } } class TestDispatcher implements ChangeDispatcher { log: List<string>; loggedValues: List<any>; onAllChangesDoneCalled: boolean = false; constructor() { this.clear(); } clear() { this.log = []; this.loggedValues = []; this.onAllChangesDoneCalled = true; } notifyOnBinding(binding, value) { this.log.push(`${binding.propertyName}=${this._asString(value)}`); this.loggedValues.push(value); } notifyOnAllChangesDone() { this.onAllChangesDoneCalled = true; } _asString(value) { return (isBlank(value) ? 'null' : value.toString()); } } class _ChangeDetectorAndDispatcher { constructor(public changeDetector: any, public dispatcher: TestDispatcher) {} }
modules/angular2/test/change_detection/change_detector_spec.ts
1
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0036203162744641304, 0.0002080159174511209, 0.00016163378313649446, 0.00017067394219338894, 0.00033547618659213185 ]
{ "id": 3, "code_window": [ " expect(rootTC.nativeElement).toHaveText('Hello World!');\n", " async.done();\n", " });\n", " }));\n", "\n", " it('should consume element binding changes',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div [id]=\"ctxProp\"></div>'}))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should update text node with a blank string when interpolation evaluates to null',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div>{{null}}{{ctxProp}}</div>'}))\n", " .createAsync(MyComp)\n", " .then((rootTC) => {\n", " rootTC.componentInstance.ctxProp = null;\n", "\n", " rootTC.detectChanges();\n", " expect(rootTC.nativeElement).toHaveText('');\n", " async.done();\n", " });\n", " }));\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/integration_spec.ts", "type": "add", "edit_start_line_idx": 96 }
var parse5 = require('parse5'); var parser = new parse5.Parser(parse5.TreeAdapters.htmlparser2); var serializer = new parse5.Serializer(parse5.TreeAdapters.htmlparser2); var treeAdapter = parser.treeAdapter; var cssParse = require('css').parse; var url = require('url'); import {List, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {DomAdapter, setRootDomAdapter} from './dom_adapter'; import {BaseException, isPresent, isBlank, global} from 'angular2/src/facade/lang'; import {SelectorMatcher, CssSelector} from 'angular2/src/render/dom/compiler/selector'; var _attrToPropMap = { 'innerHtml': 'innerHTML', 'readonly': 'readOnly', 'tabindex': 'tabIndex', }; var defDoc = null; var mapProps = ['attribs', 'x-attribsNamespace', 'x-attribsPrefix']; function _notImplemented(methodName) { return new BaseException('This method is not implemented in Parse5DomAdapter: ' + methodName); } /* tslint:disable:requireParameterType */ export class Parse5DomAdapter extends DomAdapter { static makeCurrent() { setRootDomAdapter(new Parse5DomAdapter()); } hasProperty(element, name: string): boolean { return _HTMLElementPropertyList.indexOf(name) > -1; } // TODO(tbosch): don't even call this method when we run the tests on server side // by not using the DomRenderer in tests. Keeping this for now to make tests happy... setProperty(el: /*element*/ any, name: string, value: any) { if (name === 'innerHTML') { this.setInnerHTML(el, value); } else { el[name] = value; } } // TODO(tbosch): don't even call this method when we run the tests on server side // by not using the DomRenderer in tests. Keeping this for now to make tests happy... getProperty(el: /*element*/ any, name: string): any { return el[name]; } logError(error) { console.error(error); } get attrToPropMap() { return _attrToPropMap; } query(selector) { throw _notImplemented('query'); } querySelector(el, selector: string): any { return this.querySelectorAll(el, selector)[0]; } querySelectorAll(el, selector: string): List<any> { var res = []; var _recursive = (result, node, selector, matcher) => { var cNodes = node.childNodes; if (cNodes && cNodes.length > 0) { for (var i = 0; i < cNodes.length; i++) { var childNode = cNodes[i]; if (this.elementMatches(childNode, selector, matcher)) { result.push(childNode); } _recursive(result, childNode, selector, matcher); } } }; var matcher = new SelectorMatcher(); matcher.addSelectables(CssSelector.parse(selector)); _recursive(res, el, selector, matcher); return res; } elementMatches(node, selector: string, matcher = null): boolean { var result = false; if (selector && selector.charAt(0) == "#") { result = this.getAttribute(node, 'id') == selector.substring(1); } else if (selector) { var result = false; if (matcher == null) { matcher = new SelectorMatcher(); matcher.addSelectables(CssSelector.parse(selector)); } var cssSelector = new CssSelector(); cssSelector.setElement(this.tagName(node)); if (node.attribs) { for (var attrName in node.attribs) { cssSelector.addAttribute(attrName, node.attribs[attrName]); } } var classList = this.classList(node); for (var i = 0; i < classList.length; i++) { cssSelector.addClassName(classList[i]); } matcher.match(cssSelector, function(selector, cb) { result = true; }); } return result; } on(el, evt, listener) { var listenersMap: StringMap<any, any> = el._eventListenersMap; if (isBlank(listenersMap)) { var listenersMap: StringMap<any, any> = StringMapWrapper.create(); el._eventListenersMap = listenersMap; } var listeners = StringMapWrapper.get(listenersMap, evt); if (isBlank(listeners)) { listeners = []; } listeners.push(listener); StringMapWrapper.set(listenersMap, evt, listeners); } onAndCancel(el, evt, listener): Function { this.on(el, evt, listener); return () => { ListWrapper.remove(StringMapWrapper.get<List<any>>(el._eventListenersMap, evt), listener); }; } dispatchEvent(el, evt) { if (isBlank(evt.target)) { evt.target = el; } if (isPresent(el._eventListenersMap)) { var listeners: any = StringMapWrapper.get(el._eventListenersMap, evt.type); if (isPresent(listeners)) { for (var i = 0; i < listeners.length; i++) { listeners[i](evt); } } } if (isPresent(el.parent)) { this.dispatchEvent(el.parent, evt); } if (isPresent(el._window)) { this.dispatchEvent(el._window, evt); } } createMouseEvent(eventType): Event { return this.createEvent(eventType); } createEvent(eventType: string): Event { var evt = <Event>{ type: eventType, defaultPrevented: false, preventDefault: () => { evt.defaultPrevented = true; } }; return evt; } preventDefault(evt) { evt.returnValue = false; } getInnerHTML(el): string { return serializer.serialize(this.templateAwareRoot(el)); } getOuterHTML(el): string { serializer.html = ''; serializer._serializeElement(el); return serializer.html; } nodeName(node): string { return node.tagName; } nodeValue(node): string { return node.nodeValue; } type(node: any): string { throw _notImplemented('type'); } content(node): string { return node.childNodes[0]; } firstChild(el): Node { return el.firstChild; } nextSibling(el): Node { return el.nextSibling; } parentElement(el): Node { return el.parent; } childNodes(el): Node[] { return el.childNodes; } childNodesAsList(el): List<any> { var childNodes = el.childNodes; var res = ListWrapper.createFixedSize(childNodes.length); for (var i = 0; i < childNodes.length; i++) { res[i] = childNodes[i]; } return res; } clearNodes(el) { while (el.childNodes.length > 0) { this.remove(el.childNodes[0]); } } appendChild(el, node) { this.remove(node); treeAdapter.appendChild(this.templateAwareRoot(el), node); } removeChild(el, node) { if (ListWrapper.contains(el.childNodes, node)) { this.remove(node); } } remove(el): HTMLElement { var parent = el.parent; if (parent) { var index = parent.childNodes.indexOf(el); parent.childNodes.splice(index, 1); } var prev = el.previousSibling; var next = el.nextSibling; if (prev) { prev.next = next; } if (next) { next.prev = prev; } el.prev = null; el.next = null; el.parent = null; return el; } insertBefore(el, node) { this.remove(node); treeAdapter.insertBefore(el.parent, node, el); } insertAllBefore(el, nodes) { ListWrapper.forEach(nodes, (n) => { this.insertBefore(el, n); }); } insertAfter(el, node) { if (el.nextSibling) { this.insertBefore(el.nextSibling, node); } else { this.appendChild(el.parent, node); } } setInnerHTML(el, value) { this.clearNodes(el); var content = parser.parseFragment(value); for (var i = 0; i < content.childNodes.length; i++) { treeAdapter.appendChild(el, content.childNodes[i]); } } getText(el): string { if (this.isTextNode(el)) { return el.data; } else if (isBlank(el.childNodes) || el.childNodes.length == 0) { return ""; } else { var textContent = ""; for (var i = 0; i < el.childNodes.length; i++) { textContent += this.getText(el.childNodes[i]); } return textContent; } } setText(el, value: string) { if (this.isTextNode(el)) { el.data = value; } else { this.clearNodes(el); if (value !== '') treeAdapter.insertText(el, value); } } getValue(el): string { return el.value; } setValue(el, value: string) { el.value = value; } getChecked(el): boolean { return el.checked; } setChecked(el, value: boolean) { el.checked = value; } createTemplate(html): HTMLElement { var template = treeAdapter.createElement("template", 'http://www.w3.org/1999/xhtml', []); var content = parser.parseFragment(html); treeAdapter.appendChild(template, content); return template; } createElement(tagName): HTMLElement { return treeAdapter.createElement(tagName, 'http://www.w3.org/1999/xhtml', []); } createTextNode(text: string): Text { throw _notImplemented('createTextNode'); } createScriptTag(attrName: string, attrValue: string): HTMLElement { return treeAdapter.createElement("script", 'http://www.w3.org/1999/xhtml', [{name: attrName, value: attrValue}]); } createStyleElement(css: string): HTMLStyleElement { var style = this.createElement('style'); this.setText(style, css); return <HTMLStyleElement>style; } createShadowRoot(el): HTMLElement { el.shadowRoot = treeAdapter.createDocumentFragment(); el.shadowRoot.parent = el; return el.shadowRoot; } getShadowRoot(el): Element { return el.shadowRoot; } getHost(el): string { return el.host; } getDistributedNodes(el: any): List<Node> { throw _notImplemented('getDistributedNodes'); } clone(node: Node): Node { var _recursive = (node) => { var nodeClone = Object.create(Object.getPrototypeOf(node)); for (var prop in node) { var desc = Object.getOwnPropertyDescriptor(node, prop); if (desc && 'value' in desc && typeof desc.value !== 'object') { nodeClone[prop] = node[prop]; } } nodeClone.parent = null; nodeClone.prev = null; nodeClone.next = null; nodeClone.children = null; mapProps.forEach(mapName => { if (isPresent(node[mapName])) { nodeClone[mapName] = {}; for (var prop in node[mapName]) { nodeClone[mapName][prop] = node[mapName][prop]; } } }); var cNodes = node.children; if (cNodes) { var cNodesClone = new Array(cNodes.length); for (var i = 0; i < cNodes.length; i++) { var childNode = cNodes[i]; var childNodeClone = _recursive(childNode); cNodesClone[i] = childNodeClone; if (i > 0) { childNodeClone.prev = cNodesClone[i - 1]; cNodesClone[i - 1].next = childNodeClone; } childNodeClone.parent = nodeClone; } nodeClone.children = cNodesClone; } return nodeClone; }; return _recursive(node); } getElementsByClassName(element, name: string): List<HTMLElement> { return this.querySelectorAll(element, "." + name); } getElementsByTagName(element: any, name: string): List<HTMLElement> { throw _notImplemented('getElementsByTagName'); } classList(element): List<string> { var classAttrValue = null; var attributes = element.attribs; if (attributes && attributes.hasOwnProperty("class")) { classAttrValue = attributes["class"]; } return classAttrValue ? classAttrValue.trim().split(/\s+/g) : []; } addClass(element, classname: string) { var classList = this.classList(element); var index = classList.indexOf(classname); if (index == -1) { classList.push(classname); element.attribs["class"] = element.className = ListWrapper.join(classList, " "); } } removeClass(element, classname: string) { var classList = this.classList(element); var index = classList.indexOf(classname); if (index > -1) { classList.splice(index, 1); element.attribs["class"] = element.className = ListWrapper.join(classList, " "); } } hasClass(element, classname: string): boolean { return ListWrapper.contains(this.classList(element), classname); } _readStyleAttribute(element) { var styleMap = {}; var attributes = element.attribs; if (attributes && attributes.hasOwnProperty("style")) { var styleAttrValue = attributes["style"]; var styleList = styleAttrValue.split(/;+/g); for (var i = 0; i < styleList.length; i++) { if (styleList[i].length > 0) { var elems = styleList[i].split(/:+/g); styleMap[elems[0].trim()] = elems[1].trim(); } } } return styleMap; } _writeStyleAttribute(element, styleMap) { var styleAttrValue = ""; for (var key in styleMap) { var newValue = styleMap[key]; if (newValue && newValue.length > 0) { styleAttrValue += key + ":" + styleMap[key] + ";"; } } element.attribs["style"] = styleAttrValue; } setStyle(element, stylename: string, stylevalue: string) { var styleMap = this._readStyleAttribute(element); styleMap[stylename] = stylevalue; this._writeStyleAttribute(element, styleMap); } removeStyle(element, stylename: string) { this.setStyle(element, stylename, null); } getStyle(element, stylename: string): string { var styleMap = this._readStyleAttribute(element); return styleMap.hasOwnProperty(stylename) ? styleMap[stylename] : ""; } tagName(element): string { return element.tagName == "style" ? "STYLE" : element.tagName; } attributeMap(element): Map<string, string> { var res = new Map(); var elAttrs = treeAdapter.getAttrList(element); for (var i = 0; i < elAttrs.length; i++) { var attrib = elAttrs[i]; res.set(attrib.name, attrib.value); } return res; } hasAttribute(element, attribute: string): boolean { return element.attribs && element.attribs.hasOwnProperty(attribute); } getAttribute(element, attribute: string): string { return element.attribs && element.attribs.hasOwnProperty(attribute) ? element.attribs[attribute] : null; } setAttribute(element, attribute: string, value: string) { if (attribute) { element.attribs[attribute] = value; } } removeAttribute(element, attribute: string) { if (attribute) { StringMapWrapper.delete(element.attribs, attribute); } } templateAwareRoot(el): any { return this.isTemplateElement(el) ? this.content(el) : el; } createHtmlDocument(): Document { var newDoc = treeAdapter.createDocument(); newDoc.title = "fake title"; var head = treeAdapter.createElement("head", null, []); var body = treeAdapter.createElement("body", 'http://www.w3.org/1999/xhtml', []); this.appendChild(newDoc, head); this.appendChild(newDoc, body); StringMapWrapper.set(newDoc, "head", head); StringMapWrapper.set(newDoc, "body", body); StringMapWrapper.set(newDoc, "_window", StringMapWrapper.create()); return newDoc; } defaultDoc(): Document { if (defDoc === null) { defDoc = this.createHtmlDocument(); } return defDoc; } getBoundingClientRect(el): any { return {left: 0, top: 0, width: 0, height: 0}; } getTitle(): string { return this.defaultDoc().title || ""; } setTitle(newTitle: string) { this.defaultDoc().title = newTitle; } isTemplateElement(el: any): boolean { return this.isElementNode(el) && this.tagName(el) === "template"; } isTextNode(node): boolean { return treeAdapter.isTextNode(node); } isCommentNode(node): boolean { return treeAdapter.isCommentNode(node); } isElementNode(node): boolean { return node ? treeAdapter.isElementNode(node) : false; } hasShadowRoot(node): boolean { return isPresent(node.shadowRoot); } isShadowRoot(node): boolean { return this.getShadowRoot(node) == node; } importIntoDoc(node): any { return this.clone(node); } isPageRule(rule): boolean { return rule.type === 6; // CSSRule.PAGE_RULE } isStyleRule(rule): boolean { return rule.type === 1; // CSSRule.MEDIA_RULE } isMediaRule(rule): boolean { return rule.type === 4; // CSSRule.MEDIA_RULE } isKeyframesRule(rule): boolean { return rule.type === 7; // CSSRule.KEYFRAMES_RULE } getHref(el): string { return el.href; } resolveAndSetHref(el, baseUrl: string, href: string) { if (href == null) { el.href = baseUrl; } else { el.href = url.resolve(baseUrl, href); } } _buildRules(parsedRules, css?) { var rules = []; for (var i = 0; i < parsedRules.length; i++) { var parsedRule = parsedRules[i]; var rule: StringMap<string, any> = StringMapWrapper.create(); StringMapWrapper.set(rule, "cssText", css); StringMapWrapper.set(rule, "style", {content: "", cssText: ""}); if (parsedRule.type == "rule") { StringMapWrapper.set(rule, "type", 1); StringMapWrapper.set(rule, "selectorText", parsedRule.selectors.join(", ") .replace(/\s{2,}/g, " ") .replace(/\s*~\s*/g, " ~ ") .replace(/\s*\+\s*/g, " + ") .replace(/\s*>\s*/g, " > ") .replace(/\[(\w+)=(\w+)\]/g, '[$1="$2"]')); if (isBlank(parsedRule.declarations)) { continue; } for (var j = 0; j < parsedRule.declarations.length; j++) { var declaration = parsedRule.declarations[j]; StringMapWrapper.set(StringMapWrapper.get(rule, "style"), declaration.property, declaration.value); StringMapWrapper.get(rule, "style").cssText += declaration.property + ": " + declaration.value + ";"; } } else if (parsedRule.type == "media") { StringMapWrapper.set(rule, "type", 4); StringMapWrapper.set(rule, "media", {mediaText: parsedRule.media}); if (parsedRule.rules) { StringMapWrapper.set(rule, "cssRules", this._buildRules(parsedRule.rules)); } } rules.push(rule); } return rules; } cssToRules(css: string): List<any> { css = css.replace(/url\(\'(.+)\'\)/g, 'url($1)'); var rules = []; var parsedCSS = cssParse(css, {silent: true}); if (parsedCSS.stylesheet && parsedCSS.stylesheet.rules) { rules = this._buildRules(parsedCSS.stylesheet.rules, css); } return rules; } supportsDOMEvents(): boolean { return false; } supportsNativeShadowDOM(): boolean { return false; } getGlobalEventTarget(target: string): any { if (target == "window") { return (<any>this.defaultDoc())._window; } else if (target == "document") { return this.defaultDoc(); } else if (target == "body") { return this.defaultDoc().body; } } getHistory(): History { throw 'not implemented'; } getLocation(): Location { throw 'not implemented'; } getUserAgent(): string { return "Fake user agent"; } getData(el, name: string): string { return this.getAttribute(el, 'data-' + name); } setData(el, name: string, value: string) { this.setAttribute(el, 'data-' + name, value); } // TODO(tbosch): move this into a separate environment class once we have it setGlobalVar(name: string, value: any) { global[name] = value; } } // TODO: build a proper list, this one is all the keys of a HTMLInputElement var _HTMLElementPropertyList = [ "webkitEntries", "incremental", "webkitdirectory", "selectionDirection", "selectionEnd", "selectionStart", "labels", "validationMessage", "validity", "willValidate", "width", "valueAsNumber", "valueAsDate", "value", "useMap", "defaultValue", "type", "step", "src", "size", "required", "readOnly", "placeholder", "pattern", "name", "multiple", "min", "minLength", "maxLength", "max", "list", "indeterminate", "height", "formTarget", "formNoValidate", "formMethod", "formEnctype", "formAction", "files", "form", "disabled", "dirName", "checked", "defaultChecked", "autofocus", "autocomplete", "alt", "align", "accept", "onautocompleteerror", "onautocomplete", "onwaiting", "onvolumechange", "ontoggle", "ontimeupdate", "onsuspend", "onsubmit", "onstalled", "onshow", "onselect", "onseeking", "onseeked", "onscroll", "onresize", "onreset", "onratechange", "onprogress", "onplaying", "onplay", "onpause", "onmousewheel", "onmouseup", "onmouseover", "onmouseout", "onmousemove", "onmouseleave", "onmouseenter", "onmousedown", "onloadstart", "onloadedmetadata", "onloadeddata", "onload", "onkeyup", "onkeypress", "onkeydown", "oninvalid", "oninput", "onfocus", "onerror", "onended", "onemptied", "ondurationchange", "ondrop", "ondragstart", "ondragover", "ondragleave", "ondragenter", "ondragend", "ondrag", "ondblclick", "oncuechange", "oncontextmenu", "onclose", "onclick", "onchange", "oncanplaythrough", "oncanplay", "oncancel", "onblur", "onabort", "spellcheck", "isContentEditable", "contentEditable", "outerText", "innerText", "accessKey", "hidden", "webkitdropzone", "draggable", "tabIndex", "dir", "translate", "lang", "title", "childElementCount", "lastElementChild", "firstElementChild", "children", "onwebkitfullscreenerror", "onwebkitfullscreenchange", "nextElementSibling", "previousElementSibling", "onwheel", "onselectstart", "onsearch", "onpaste", "oncut", "oncopy", "onbeforepaste", "onbeforecut", "onbeforecopy", "shadowRoot", "dataset", "classList", "className", "outerHTML", "innerHTML", "scrollHeight", "scrollWidth", "scrollTop", "scrollLeft", "clientHeight", "clientWidth", "clientTop", "clientLeft", "offsetParent", "offsetHeight", "offsetWidth", "offsetTop", "offsetLeft", "localName", "prefix", "namespaceURI", "id", "style", "attributes", "tagName", "parentElement", "textContent", "baseURI", "ownerDocument", "nextSibling", "previousSibling", "lastChild", "firstChild", "childNodes", "parentNode", "nodeType", "nodeValue", "nodeName", "closure_lm_714617", "__jsaction" ];
modules/angular2/src/dom/parse5_adapter.ts
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0004420821205712855, 0.00017384730745106936, 0.0001619446265976876, 0.00016878990572877228, 0.00003257092976127751 ]
{ "id": 3, "code_window": [ " expect(rootTC.nativeElement).toHaveText('Hello World!');\n", " async.done();\n", " });\n", " }));\n", "\n", " it('should consume element binding changes',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div [id]=\"ctxProp\"></div>'}))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should update text node with a blank string when interpolation evaluates to null',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div>{{null}}{{ctxProp}}</div>'}))\n", " .createAsync(MyComp)\n", " .then((rootTC) => {\n", " rootTC.componentInstance.ctxProp = null;\n", "\n", " rootTC.detectChanges();\n", " expect(rootTC.nativeElement).toHaveText('');\n", " async.done();\n", " });\n", " }));\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/integration_spec.ts", "type": "add", "edit_start_line_idx": 96 }
/// This file contains tests that make sense only in Dart library angular2.test.di.injector_dart_spec; import 'package:angular2/test_lib.dart'; import 'package:angular2/di.dart'; main() { describe('Injector', () { it('should support TypeLiteral', () { var i = Injector.resolveAndCreate( [bind(new TypeLiteral<List<int>>()).toValue([1, 2, 3]), Foo,]); expect(i.get(Foo).value).toEqual([1, 2, 3]); }); }); } class Foo { final List<int> value; Foo(this.value); }
modules/angular2/test/di/injector_dart_spec.dart
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0001710083888610825, 0.00016877746384125203, 0.0001668138284003362, 0.0001685101742623374, 0.000001722820684335602 ]
{ "id": 3, "code_window": [ " expect(rootTC.nativeElement).toHaveText('Hello World!');\n", " async.done();\n", " });\n", " }));\n", "\n", " it('should consume element binding changes',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div [id]=\"ctxProp\"></div>'}))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should update text node with a blank string when interpolation evaluates to null',\n", " inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n", " tcb.overrideView(MyComp, new viewAnn.View({template: '<div>{{null}}{{ctxProp}}</div>'}))\n", " .createAsync(MyComp)\n", " .then((rootTC) => {\n", " rootTC.componentInstance.ctxProp = null;\n", "\n", " rootTC.detectChanges();\n", " expect(rootTC.nativeElement).toHaveText('');\n", " async.done();\n", " });\n", " }));\n", "\n" ], "file_path": "modules/angular2/test/core/compiler/integration_spec.ts", "type": "add", "edit_start_line_idx": 96 }
library angular2.transform.common.class_matcher_base; import 'package:analyzer/src/generated/ast.dart'; import 'package:barback/barback.dart' show AssetId; import 'package:code_transformers/assets.dart'; import 'package:path/path.dart' as path; import 'logging.dart' show logger; /// Checks if a given [Identifier] matches any of the given [ClassDescriptor]s. abstract class ClassMatcherBase { /// Always start out with the default angular [ClassDescriptor]s. final List<ClassDescriptor> _classDescriptors; ClassMatcherBase(this._classDescriptors); /// Adds a new [ClassDescriptor]. void add(ClassDescriptor classDescriptor) => _classDescriptors.add(classDescriptor); /// Adds a number of [ClassDescriptor]s. void addAll(Iterable<ClassDescriptor> classDescriptors) => _classDescriptors.addAll(classDescriptors); /// Returns the first [ClassDescriptor] that matches the given /// [Identifier] node which appears in `assetId`. ClassDescriptor firstMatch(Identifier className, AssetId assetId) => _classDescriptors.firstWhere((a) => isMatch(className, a, assetId), orElse: () => null); /// Checks whether an [Identifier] matches any [ClassDescriptor]. bool hasMatch(Identifier className, AssetId assetId) => _classDescriptors.any((a) => isMatch(className, a, assetId)); /// Checks whether an [Identifier] matches any [ClassDescriptor]. ImportDirective getMatchingImport(Identifier className, AssetId assetId) { for (var d in _classDescriptors) { var matchingImport = _getMatchingImport(className, d, assetId); if (matchingImport != null) { return matchingImport; } } return null; } /// Checks if `descriptor` extends or is any of the supplied `interfaces`. bool implements(ClassDescriptor descriptor, List<ClassDescriptor> interfaces, {String missingSuperClassWarning}) { if (descriptor == null) return false; if (interfaces.contains(descriptor)) return true; if (descriptor.superClass == null) return false; var superClass = _classDescriptors.firstWhere( (a) => a.name == descriptor.superClass, orElse: () => null); if (superClass == null) { if (missingSuperClassWarning != null && missingSuperClassWarning.isNotEmpty) { logger.warning(missingSuperClassWarning); } return false; } return implements(superClass, interfaces); } } // Returns an [ImportDirective] matching `descriptor` for `className` which appears in `assetId`, or `null` if none exists. ImportDirective _getMatchingImport( Identifier className, ClassDescriptor descriptor, AssetId assetId) { if (className == null) return null; String name; Identifier prefix; if (className is PrefixedIdentifier) { name = className.identifier.name; prefix = className.prefix; } else { name = className.name; } if (name != descriptor.name) return null; return (className.root as CompilationUnit).directives .where((d) => d is ImportDirective) .firstWhere((ImportDirective i) { var importMatch = false; var uriString = i.uri.stringValue; if (uriString == descriptor.import) { importMatch = true; } else if (uriString.startsWith('package:') || uriString.startsWith('dart:')) { return false; } else { importMatch = descriptor.assetId == uriToAssetId(assetId, uriString, logger, null); } if (!importMatch) return false; if (prefix == null) return i.prefix == null; if (i.prefix == null) return false; return prefix.name == i.prefix.name; }, orElse: () => null); } // Checks if `className` which appears in `assetId` matches a [ClassDescriptor]. bool isMatch( Identifier className, ClassDescriptor descriptor, AssetId assetId) { return _getMatchingImport(className, descriptor, assetId) != null; } /// String based description of a class and its location. class ClassDescriptor { /// The name of the class. final String name; /// A `package:` style import path to the file where the class is defined. final String import; /// The class that this class extends or implements. This is the only optional /// field. final String superClass; AssetId get assetId => new AssetId(package, packagePath); String get package => path.split(import.replaceFirst('package:', '')).first; String get packagePath => path.joinAll(['lib'] ..addAll(path.split(import.replaceFirst('package:', ''))..removeAt(0))); const ClassDescriptor(this.name, this.import, {this.superClass}); }
modules/angular2/src/transform/common/class_matcher_base.dart
0
https://github.com/angular/angular/commit/345fa521dd65b97ee1ca06329acde7d4f869e75a
[ 0.0001736561971483752, 0.00016877023153938353, 0.00016294431407004595, 0.0001682102883933112, 0.000003666764314402826 ]
{ "id": 0, "code_window": [ " children: void 0,\n", " };\n", " }\n", " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n", " if (childrenLength === 1) {\n", " props.children = children;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 49 }
// @flow import template from "@babel/template"; const helpers = Object.create(null); export default helpers; const helper = (minVersion: string) => tpl => ({ minVersion, ast: () => template.program.ast(tpl), }); helpers.typeof = helper("7.0.0-beta.0")` export default function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } `; // "for" is a reserved keyword in ES3 so escaping it here for backward compatibility helpers.jsx = helper("7.0.0-beta.0")` var REACT_ELEMENT_TYPE; export default function _createRawReactElement(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = ( typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") ) || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { // If we're going to assign props.children, we create a new object now // to avoid mutating defaultProps. props = { children: void 0, }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null, }; } `; helpers.asyncIterator = helper("7.0.0-beta.0")` export default function _asyncIterator(iterable) { var method if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator] if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator] if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } `; helpers.AwaitValue = helper("7.0.0-beta.0")` export default function _AwaitValue(value) { this.wrapped = value; } `; helpers.AsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null, }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg) var value = result.value; var wrappedAwait = value instanceof AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then( function (arg) { if (wrappedAwait) { resume("next", arg); return } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; // Hide "return" method if generator return is not supported if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; `; helpers.wrapAsyncGenerator = helper("7.0.0-beta.0")` import AsyncGenerator from "AsyncGenerator"; export default function _wrapAsyncGenerator(fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; } `; helpers.awaitAsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function _awaitAsyncGenerator(value) { return new AwaitValue(value); } `; helpers.asyncGeneratorDelegate = helper("7.0.0-beta.0")` export default function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function (resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; }; if (typeof Symbol === "function" && Symbol.iterator) { iter[Symbol.iterator] = function () { return this; }; } iter.next = function (value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function (value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function (value) { return pump("return", value); }; } return iter; } `; helpers.asyncToGenerator = helper("7.0.0-beta.0")` function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } export default function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } `; helpers.classCallCheck = helper("7.0.0-beta.0")` export default function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } `; helpers.createClass = helper("7.0.0-beta.0")` function _defineProperties(target, props) { for (var i = 0; i < props.length; i ++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } export default function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } `; helpers.defineEnumerableProperties = helper("7.0.0-beta.0")` export default function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, key, desc); } // Symbols are not enumerated over by for-in loops. If native // Symbols are available, fetch all of the descs object's own // symbol properties and define them on our target object too. if (Object.getOwnPropertySymbols) { var objectSymbols = Object.getOwnPropertySymbols(descs); for (var i = 0; i < objectSymbols.length; i++) { var sym = objectSymbols[i]; var desc = descs[sym]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, sym, desc); } } return obj; } `; helpers.defaults = helper("7.0.0-beta.0")` export default function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } `; helpers.defineProperty = helper("7.0.0-beta.0")` export default function _defineProperty(obj, key, value) { // Shortcircuit the slow defineProperty path when possible. // We are trying to avoid issues where setters defined on the // prototype cause side effects under the fast path of simple // assignment. By checking for existence of the property with // the in operator, we can optimize most of this overhead away. if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } `; helpers.extends = helper("7.0.0-beta.0")` export default function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } `; // This old helper can be removed in babel v8 helpers.objectSpread = helper("7.0.0-beta.0")` import defineProperty from "defineProperty"; export default function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { defineProperty(target, key, source[key]); }); } return target; } `; helpers.objectSpread2 = helper("7.5.0")` import defineProperty from "defineProperty"; // This function is different to "Reflect.ownKeys". The enumerableOnly // filters on symbol properties only. Returned string properties are always // enumerable. It is good to use in objectSpread. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } export default function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key) ); }); } } return target; } `; helpers.inherits = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; export default function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } `; helpers.inheritsLoose = helper("7.0.0-beta.0")` export default function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } `; helpers.getPrototypeOf = helper("7.0.0-beta.0")` export default function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } `; helpers.setPrototypeOf = helper("7.0.0-beta.0")` export default function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } `; helpers.construct = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; // core-js@3 if (Reflect.construct.sham) return false; // Proxy can't be polyfilled. Every browser implemented // proxies before or at the same time as Reflect.construct, // so if they support Proxy they also support Reflect.construct. if (typeof Proxy === "function") return true; // Since Reflect.construct can't be properly polyfilled, some // implementations (e.g. core-js@2) don't set the correct internal slots. // Those polyfills don't allow us to subclass built-ins, so we need to // use our fallback implementation. try { // If the internal slots aren't set, this throws an error similar to // TypeError: this is not a Date object. Date.prototype.toString.call(Reflect.construct(Date, [], function() {})); return true; } catch (e) { return false; } } export default function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { // NOTE: If Parent !== Class, the correct __proto__ is set *after* // calling the constructor. _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }; } // Avoid issues with Class being present but undefined when it wasn't // present in the original call. return _construct.apply(null, arguments); } `; helpers.isNativeFunction = helper("7.0.0-beta.0")` export default function _isNativeFunction(fn) { // Note: This function returns "true" for core-js functions. return Function.toString.call(fn).indexOf("[native code]") !== -1; } `; // Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes helpers.wrapNativeSuper = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; import setPrototypeOf from "setPrototypeOf"; import isNativeFunction from "isNativeFunction"; import construct from "construct"; export default function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct(Class, arguments, getPrototypeOf(this).constructor) } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true, } }); return setPrototypeOf(Wrapper, Class); } return _wrapNativeSuper(Class) } `; helpers.instanceof = helper("7.0.0-beta.0")` export default function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } `; helpers.interopRequireDefault = helper("7.0.0-beta.0")` export default function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } `; helpers.interopRequireWildcard = helper("7.0.0-beta.0")` function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } export default function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } `; helpers.newArrowCheck = helper("7.0.0-beta.0")` export default function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } `; helpers.objectDestructuringEmpty = helper("7.0.0-beta.0")` export default function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); } `; helpers.objectWithoutPropertiesLoose = helper("7.0.0-beta.0")` export default function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } `; helpers.objectWithoutProperties = helper("7.0.0-beta.0")` import objectWithoutPropertiesLoose from "objectWithoutPropertiesLoose"; export default function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } `; helpers.assertThisInitialized = helper("7.0.0-beta.0")` export default function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } `; helpers.possibleConstructorReturn = helper("7.0.0-beta.0")` import assertThisInitialized from "assertThisInitialized"; export default function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } `; helpers.superPropBase = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; export default function _superPropBase(object, property) { // Yes, this throws if object is null to being with, that's on purpose. while (!Object.prototype.hasOwnProperty.call(object, property)) { object = getPrototypeOf(object); if (object === null) break; } return object; } `; helpers.get = helper("7.0.0-beta.0")` import superPropBase from "superPropBase"; export default function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } `; helpers.set = helper("7.0.0-beta.0")` import superPropBase from "superPropBase"; import defineProperty from "defineProperty"; function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { // Both getter and non-writable fall into this. return false; } } // Without a super that defines the property, spec boils down to // "define on receiver" for some reason. desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { // Setter, getter, and non-writable fall into this. return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { // Avoid setters that may be defined on Sub's prototype, but not on // the instance. defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } export default function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } `; helpers.taggedTemplateLiteral = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } `; helpers.taggedTemplateLiteralLoose = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; } `; helpers.readOnlyError = helper("7.0.0-beta.0")` export default function _readOnlyError(name) { throw new Error("\\"" + name + "\\" is read-only"); } `; helpers.classNameTDZError = helper("7.0.0-beta.0")` export default function _classNameTDZError(name) { throw new Error("Class \\"" + name + "\\" cannot be referenced in computed property keys."); } `; helpers.temporalUndefined = helper("7.0.0-beta.0")` // This function isn't mean to be called, but to be used as a reference. // We can't use a normal object because it isn't hoisted. export default function _temporalUndefined() {} `; helpers.tdz = helper("7.5.5")` export default function _tdzError(name) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } `; helpers.temporalRef = helper("7.0.0-beta.0")` import undef from "temporalUndefined"; import err from "tdz"; export default function _temporalRef(val, name) { return val === undef ? err(name) : val; } `; helpers.slicedToArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimit from "iterableToArrayLimit"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); } `; helpers.slicedToArrayLoose = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimitLoose from "iterableToArrayLimitLoose"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArrayLoose(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || nonIterableRest(); } `; helpers.toArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArray from "iterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _toArray(arr) { return arrayWithHoles(arr) || iterableToArray(arr) || nonIterableRest(); } `; helpers.toConsumableArray = helper("7.0.0-beta.0")` import arrayWithoutHoles from "arrayWithoutHoles"; import iterableToArray from "iterableToArray"; import nonIterableSpread from "nonIterableSpread"; export default function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } `; helpers.arrayWithoutHoles = helper("7.0.0-beta.0")` export default function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } `; helpers.arrayWithHoles = helper("7.0.0-beta.0")` export default function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } `; helpers.iterableToArray = helper("7.0.0-beta.0")` export default function _iterableToArray(iter) { if ( Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]" ) return Array.from(iter); } `; helpers.iterableToArrayLimit = helper("7.0.0-beta.0")` export default function _iterableToArrayLimit(arr, i) { // this is an expanded form of \`for...of\` that properly supports abrupt completions of // iterators etc. variable names have been minimised to reduce the size of this massive // helper. sometimes spec compliancy is annoying :( // // _n = _iteratorNormalCompletion // _d = _didIteratorError // _e = _iteratorError // _i = _iterator // _s = _step var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } `; helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")` export default function _iterableToArrayLimitLoose(arr, i) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } `; helpers.nonIterableSpread = helper("7.0.0-beta.0")` export default function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } `; helpers.nonIterableRest = helper("7.0.0-beta.0")` export default function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } `; helpers.skipFirstGeneratorNext = helper("7.0.0-beta.0")` export default function _skipFirstGeneratorNext(fn) { return function () { var it = fn.apply(this, arguments); it.next(); return it; } } `; helpers.toPrimitive = helper("7.1.5")` export default function _toPrimitive( input, hint /*: "default" | "string" | "number" | void */ ) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } `; helpers.toPropertyKey = helper("7.1.5")` import toPrimitive from "toPrimitive"; export default function _toPropertyKey(arg) { var key = toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } `; /** * Add a helper that will throw a useful error if the transform fails to detect the class * property assignment, so users know something failed. */ helpers.initializerWarningHelper = helper("7.0.0-beta.0")` export default function _initializerWarningHelper(descriptor, context){ throw new Error( 'Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and set to use loose mode. ' + 'To use proposal-class-properties in spec mode with decorators, wait for ' + 'the next major version of decorators in stage 2.' ); } `; /** * Add a helper to call as a replacement for class property definition. */ helpers.initializerDefineProperty = helper("7.0.0-beta.0")` export default function _initializerDefineProperty(target, property, descriptor, context){ if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0, }); } `; /** * Add a helper to take an initial descriptor, apply some decorators to it, and optionally * define the property. */ helpers.applyDecoratedDescriptor = helper("7.0.0-beta.0")` export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context){ var desc = {}; Object.keys(descriptor).forEach(function(key){ desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer){ desc.writable = true; } desc = decorators.slice().reverse().reduce(function(desc, decorator){ return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0){ desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0){ // This is a hack to avoid this being processed by 'transform-runtime'. // See issue #9. Object.defineProperty(target, property, desc); desc = null; } return desc; } `; helpers.classPrivateFieldLooseKey = helper("7.0.0-beta.0")` var id = 0; export default function _classPrivateFieldKey(name) { return "__private_" + (id++) + "_" + name; } `; helpers.classPrivateFieldLooseBase = helper("7.0.0-beta.0")` export default function _classPrivateFieldBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } `; helpers.classPrivateFieldGet = helper("7.0.0-beta.0")` export default function _classPrivateFieldGet(receiver, privateMap) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError("attempted to get private field on non-instance"); } if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; } `; helpers.classPrivateFieldSet = helper("7.0.0-beta.0")` export default function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError("attempted to set private field on non-instance"); } if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } return value; } `; helpers.classPrivateFieldDestructureSet = helper("7.4.4")` export default function _classPrivateFieldDestructureSet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } var descriptor = privateMap.get(receiver); if (descriptor.set) { if (!("__destrObj" in descriptor)) { descriptor.__destrObj = { set value(v) { descriptor.set.call(receiver, v) }, }; } return descriptor.__destrObj; } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } return descriptor; } } `; helpers.classStaticPrivateFieldSpecGet = helper("7.0.2")` export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } return descriptor.value; } `; helpers.classStaticPrivateFieldSpecSet = helper("7.0.2")` export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; return value; } `; helpers.classStaticPrivateMethodGet = helper("7.3.2")` export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } return method; } `; helpers.classStaticPrivateMethodSet = helper("7.3.2")` export default function _classStaticPrivateMethodSet() { throw new TypeError("attempted to set read only static private field"); } `; helpers.decorate = helper("7.1.5")` import toArray from "toArray"; import toPropertyKey from "toPropertyKey"; // These comments are stripped by @babel/template /*:: type PropertyDescriptor = | { value: any, writable: boolean, configurable: boolean, enumerable: boolean, } | { get?: () => any, set?: (v: any) => void, configurable: boolean, enumerable: boolean, }; type FieldDescriptor ={ writable: boolean, configurable: boolean, enumerable: boolean, }; type Placement = "static" | "prototype" | "own"; type Key = string | symbol; // PrivateName is not supported yet. type ElementDescriptor = | { kind: "method", key: Key, placement: Placement, descriptor: PropertyDescriptor } | { kind: "field", key: Key, placement: Placement, descriptor: FieldDescriptor, initializer?: () => any, }; // This is exposed to the user code type ElementObjectInput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" }; // This is exposed to the user code type ElementObjectOutput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" extras?: ElementDescriptor[], finisher?: ClassFinisher, }; // This is exposed to the user code type ClassObject = { [@@toStringTag]?: "Descriptor", kind: "class", elements: ElementDescriptor[], }; type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput; type ClassDecorator = (descriptor: ClassObject) => ?ClassObject; type ClassFinisher = <A, B>(cl: Class<A>) => Class<B>; // Only used by Babel in the transform output, not part of the spec. type ElementDefinition = | { kind: "method", value: any, key: Key, static?: boolean, decorators?: ElementDecorator[], } | { kind: "field", value: () => any, key: Key, static?: boolean, decorators?: ElementDecorator[], }; declare function ClassFactory<C>(initialize: (instance: C) => void): { F: Class<C>, d: ElementDefinition[] } */ /*:: // Various combinations with/without extras and with one or many finishers type ElementFinisherExtras = { element: ElementDescriptor, finisher?: ClassFinisher, extras?: ElementDescriptor[], }; type ElementFinishersExtras = { element: ElementDescriptor, finishers: ClassFinisher[], extras: ElementDescriptor[], }; type ElementsFinisher = { elements: ElementDescriptor[], finisher?: ClassFinisher, }; type ElementsFinishers = { elements: ElementDescriptor[], finishers: ClassFinisher[], }; */ /*:: type Placements = { static: Key[], prototype: Key[], own: Key[], }; */ // ClassDefinitionEvaluation (Steps 26-*) export default function _decorate( decorators /*: ClassDecorator[] */, factory /*: ClassFactory */, superClass /*: ?Class<*> */, mixins /*: ?Array<Function> */, ) /*: Class<*> */ { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass( _coalesceClassElements(r.d.map(_createElementDescriptor)), decorators, ); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } function _getDecoratorsApi() { _getDecoratorsApi = function() { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], // InitializeInstanceElements initializeInstanceElements: function( /*::<C>*/ O /*: C */, elements /*: ElementDescriptor[] */, ) { ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, // InitializeClassElements initializeClassElements: function( /*::<C>*/ F /*: Class<C> */, elements /*: ElementDescriptor[] */, ) { var proto = F.prototype; ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { var placement = element.placement; if ( element.kind === kind && (placement === "static" || placement === "prototype") ) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, // DefineClassElement defineClassElement: function( /*::<C>*/ receiver /*: C | Class<C> */, element /*: ElementDescriptor */, ) { var descriptor /*: PropertyDescriptor */ = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver), }; } Object.defineProperty(receiver, element.key, descriptor); }, // DecorateClass decorateClass: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var newElements /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; var placements /*: Placements */ = { static: [], prototype: [], own: [], }; elements.forEach(function(element /*: ElementDescriptor */) { this.addElementPlacement(element, placements); }, this); elements.forEach(function(element /*: ElementDescriptor */) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement( element, placements, ); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result /*: ElementsFinishers */ = this.decorateConstructor( newElements, decorators, ); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, // AddElementPlacement addElementPlacement: function( element /*: ElementDescriptor */, placements /*: Placements */, silent /*: boolean */, ) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, // DecorateElement decorateElement: function( element /*: ElementDescriptor */, placements /*: Placements */, ) /*: ElementFinishersExtras */ { var extras /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; for ( var decorators = element.decorators, i = decorators.length - 1; i >= 0; i-- ) { // (inlined) RemoveElementPlacement var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor( element, ); var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras( (0, decorators[i])(elementObject) /*: ElementObjectOutput */ || elementObject, ); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras /*: ElementDescriptor[] | void */ = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, // DecorateConstructor decorateConstructor: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var finishers /*: ClassFinisher[] */ = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj /*: ClassObject */ = this.fromClassDescriptor(elements); var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor( (0, decorators[i])(obj) /*: ClassObject */ || obj, ); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if ( elements[j].key === elements[k].key && elements[j].placement === elements[k].placement ) { throw new TypeError( "Duplicated element (" + elements[j].key + ")", ); } } } } } return { elements: elements, finishers: finishers }; }, // FromElementDescriptor fromElementDescriptor: function( element /*: ElementDescriptor */, ) /*: ElementObject */ { var obj /*: ElementObject */ = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor, }; var desc = { value: "Descriptor", configurable: true, }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, // ToElementDescriptors toElementDescriptors: function( elementObjects /*: ElementObject[] */, ) /*: ElementDescriptor[] */ { if (elementObjects === undefined) return; return toArray(elementObjects).map(function(elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, // ToElementDescriptor toElementDescriptor: function( elementObject /*: ElementObject */, ) /*: ElementDescriptor */ { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError( 'An element descriptor\\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"', ); } var key = toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if ( placement !== "static" && placement !== "prototype" && placement !== "own" ) { throw new TypeError( 'An element descriptor\\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"', ); } var descriptor /*: PropertyDescriptor */ = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element /*: ElementDescriptor */ = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor), }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty( descriptor, "get", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "set", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "value", "The property descriptor of a field descriptor", ); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function( elementObject /*: ElementObject */, ) /*: ElementFinisherExtras */ { var element /*: ElementDescriptor */ = this.toElementDescriptor( elementObject, ); var finisher /*: ClassFinisher */ = _optionalCallableProperty( elementObject, "finisher", ); var extras /*: ElementDescriptors[] */ = this.toElementDescriptors( elementObject.extras, ); return { element: element, finisher: finisher, extras: extras }; }, // FromClassDescriptor fromClassDescriptor: function( elements /*: ElementDescriptor[] */, ) /*: ClassObject */ { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this), }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, // ToClassDescriptor toClassDescriptor: function( obj /*: ClassObject */, ) /*: ElementsFinisher */ { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError( 'A class descriptor\\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"', ); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, // RunClassFinishers runClassFinishers: function( constructor /*: Class<*> */, finishers /*: ClassFinisher[] */, ) /*: Class<*> */ { for (var i = 0; i < finishers.length; i++) { var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor); if (newConstructor !== undefined) { // NOTE: This should check if IsConstructor(newConstructor) is false. if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function(obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } // ClassElementEvaluation function _createElementDescriptor( def /*: ElementDefinition */, ) /*: ElementDescriptor */ { var key = toPropertyKey(def.key); var descriptor /*: PropertyDescriptor */; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false, }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element /*: ElementDescriptor */ = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor, }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } // CoalesceGetterSetter function _coalesceGetterSetter( element /*: ElementDescriptor */, other /*: ElementDescriptor */, ) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } // CoalesceClassElements function _coalesceClassElements( elements /*: ElementDescriptor[] */, ) /*: ElementDescriptor[] */ { var newElements /*: ElementDescriptor[] */ = []; var isSameElement = function( other /*: ElementDescriptor */, ) /*: boolean */ { return ( other.kind === "method" && other.key === element.key && other.placement === element.placement ); }; for (var i = 0; i < elements.length; i++) { var element /*: ElementDescriptor */ = elements[i]; var other /*: ElementDescriptor */; if ( element.kind === "method" && (other = newElements.find(isSameElement)) ) { if ( _isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor) ) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError( "Duplicated methods (" + element.key + ") can't be decorated.", ); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError( "Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").", ); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ { return element.decorators && element.decorators.length; } function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ { return ( desc !== undefined && !(desc.value === undefined && desc.writable === undefined) ); } function _optionalCallableProperty /*::<T>*/( obj /*: T */, name /*: $Keys<T> */, ) /*: ?Function */ { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } `; helpers.classPrivateMethodGet = helper("7.1.6")` export default function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; } `; helpers.classPrivateMethodSet = helper("7.1.6")` export default function _classPrivateMethodSet() { throw new TypeError("attempted to reassign private method"); } `; helpers.wrapRegExp = helper("7.2.6")` import wrapNativeSuper from "wrapNativeSuper"; import getPrototypeOf from "getPrototypeOf"; import possibleConstructorReturn from "possibleConstructorReturn"; import inherits from "inherits"; export default function _wrapRegExp(re, groups) { _wrapRegExp = function(re, groups) { return new BabelRegExp(re, undefined, groups); }; var _RegExp = wrapNativeSuper(RegExp); var _super = RegExp.prototype; var _groups = new WeakMap(); function BabelRegExp(re, flags, groups) { var _this = _RegExp.call(this, re, flags); // if the regex is recreated with 'g' flag _groups.set(_this, groups || _groups.get(re)); return _this; } inherits(BabelRegExp, _RegExp); BabelRegExp.prototype.exec = function(str) { var result = _super.exec.call(this, str); if (result) result.groups = buildGroups(result, this); return result; }; BabelRegExp.prototype[Symbol.replace] = function(str, substitution) { if (typeof substitution === "string") { var groups = _groups.get(this); return _super[Symbol.replace].call( this, str, substitution.replace(/\\$<([^>]+)>/g, function(_, name) { return "$" + groups[name]; }) ); } else if (typeof substitution === "function") { var _this = this; return _super[Symbol.replace].call( this, str, function() { var args = []; args.push.apply(args, arguments); if (typeof args[args.length - 1] !== "object") { // Modern engines already pass result.groups as the last arg. args.push(buildGroups(args, _this)); } return substitution.apply(this, args); } ); } else { return _super[Symbol.replace].call(this, str, substitution); } } function buildGroups(result, re) { // NOTE: This function should return undefined if there are no groups, // but in that case Babel doesn't add the wrapper anyway. var g = _groups.get(re); return Object.keys(g).reduce(function(groups, name) { groups[name] = result[g[name]]; return groups; }, Object.create(null)); } return _wrapRegExp.apply(this, arguments); } `;
packages/babel-helpers/src/helpers.js
1
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.9977375268936157, 0.0058984351344406605, 0.00016128936840686947, 0.00017275282880291343, 0.07102397084236145 ]
{ "id": 0, "code_window": [ " children: void 0,\n", " };\n", " }\n", " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n", " if (childrenLength === 1) {\n", " props.children = children;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 49 }
try { doThat(); } catch (e) { say(e) }
packages/babel-parser/test/fixtures/esprima/statement-try/migrated_0005/input.js
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00017091157496906817, 0.00017091157496906817, 0.00017091157496906817, 0.00017091157496906817, 0 ]
{ "id": 0, "code_window": [ " children: void 0,\n", " };\n", " }\n", " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n", " if (childrenLength === 1) {\n", " props.children = children;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 49 }
{ "type": "File", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "program": { "type": "Program", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "sourceType": "script", "interpreter": null, "body": [], "directives": [ { "type": "Directive", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "value": { "type": "DirectiveLiteral", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "value": "Hello\\0122World", "extra": { "raw": "\"Hello\\0122World\"", "rawValue": "Hello\\0122World" } } } ] } }
packages/babel-parser/test/fixtures/esprima/expression-primary-literal-string/migrated_0011/output.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00017529221076983958, 0.00017341623606625944, 0.0001688525953795761, 0.00017405845574103296, 0.0000019374701878405176 ]
{ "id": 0, "code_window": [ " children: void 0,\n", " };\n", " }\n", " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n", " if (childrenLength === 1) {\n", " props.children = children;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 49 }
arguments++
packages/babel-parser/test/fixtures/esprima/expression-postfix/migrated_0004/input.js
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00016817949654068798, 0.00016817949654068798, 0.00016817949654068798, 0.00016817949654068798, 0 ]
{ "id": 1, "code_window": [ " childArray[i] = arguments[i + 3];\n", " }\n", " props.children = childArray;\n", " }\n", "\n", " return {\n", " $$typeof: REACT_ELEMENT_TYPE,\n", " type: type,\n", " key: key === undefined ? null : '' + key,\n", " ref: null,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "add", "edit_start_line_idx": 69 }
var REACT_ELEMENT_TYPE; function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; } var _ref = /*#__PURE__*/ _jsx("foo", {}); function render() { return _ref; } function render() { var text = getText(); var _ref2 = /*#__PURE__*/ _jsx("foo", {}, void 0, text); return function () { return _ref2; }; }
packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/inline-elements/output.js
1
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.9484801888465881, 0.3162720501422882, 0.00016790773952379823, 0.00016807738575153053, 0.4470386207103729 ]
{ "id": 1, "code_window": [ " childArray[i] = arguments[i + 3];\n", " }\n", " props.children = childArray;\n", " }\n", "\n", " return {\n", " $$typeof: REACT_ELEMENT_TYPE,\n", " type: type,\n", " key: key === undefined ? null : '' + key,\n", " ref: null,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "add", "edit_start_line_idx": 69 }
{ "throws": "Only expressions, functions or classes are allowed as the `default` export. (1:15)" }
packages/babel-parser/test/fixtures/es2015/modules/export-default-variable-declaration3/options.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.0001645438896957785, 0.0001645438896957785, 0.0001645438896957785, 0.0001645438896957785, 0 ]
{ "id": 1, "code_window": [ " childArray[i] = arguments[i + 3];\n", " }\n", " props.children = childArray;\n", " }\n", "\n", " return {\n", " $$typeof: REACT_ELEMENT_TYPE,\n", " type: type,\n", " key: key === undefined ? null : '' + key,\n", " ref: null,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "add", "edit_start_line_idx": 69 }
{ "plugins": ["transform-regenerator"], "retainLines": true }
packages/babel-plugin-transform-regenerator/test/fixtures/variable-renaming/retain-lines/options.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00017173537344206125, 0.00017173537344206125, 0.00017173537344206125, 0.00017173537344206125, 0 ]
{ "id": 1, "code_window": [ " childArray[i] = arguments[i + 3];\n", " }\n", " props.children = childArray;\n", " }\n", "\n", " return {\n", " $$typeof: REACT_ELEMENT_TYPE,\n", " type: type,\n", " key: key === undefined ? null : '' + key,\n", " ref: null,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (props && defaultProps) {\n", " for (var propName in defaultProps) {\n", " if (props[propName] === void 0) {\n", " props[propName] = defaultProps[propName];\n", " }\n", " }\n", " } else if (!props) {\n", " props = defaultProps || {};\n", " }\n", "\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "add", "edit_start_line_idx": 69 }
(function() { "use strict"; f(yield v) })
packages/babel-parser/test/fixtures/es2015/uncategorised/.260/input.js
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00016518479969818145, 0.00016518479969818145, 0.00016518479969818145, 0.00016518479969818145, 0 ]
{ "id": 2, "code_window": [ "\n", "helpers.objectSpread2 = helper(\"7.5.0\")`\n", " import defineProperty from \"defineProperty\";\n", "\n", " // This function is different to \"Reflect.ownKeys\". The enumerableOnly\n", " // filters on symbol properties only. Returned string properties are always \n", " // enumerable. It is good to use in objectSpread.\n", "\n", " function ownKeys(object, enumerableOnly) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // filters on symbol properties only. Returned string properties are always\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 412 }
// @flow import template from "@babel/template"; const helpers = Object.create(null); export default helpers; const helper = (minVersion: string) => tpl => ({ minVersion, ast: () => template.program.ast(tpl), }); helpers.typeof = helper("7.0.0-beta.0")` export default function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } `; // "for" is a reserved keyword in ES3 so escaping it here for backward compatibility helpers.jsx = helper("7.0.0-beta.0")` var REACT_ELEMENT_TYPE; export default function _createRawReactElement(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = ( typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") ) || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { // If we're going to assign props.children, we create a new object now // to avoid mutating defaultProps. props = { children: void 0, }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null, }; } `; helpers.asyncIterator = helper("7.0.0-beta.0")` export default function _asyncIterator(iterable) { var method if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator] if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator] if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } `; helpers.AwaitValue = helper("7.0.0-beta.0")` export default function _AwaitValue(value) { this.wrapped = value; } `; helpers.AsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null, }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg) var value = result.value; var wrappedAwait = value instanceof AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then( function (arg) { if (wrappedAwait) { resume("next", arg); return } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; // Hide "return" method if generator return is not supported if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; `; helpers.wrapAsyncGenerator = helper("7.0.0-beta.0")` import AsyncGenerator from "AsyncGenerator"; export default function _wrapAsyncGenerator(fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; } `; helpers.awaitAsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function _awaitAsyncGenerator(value) { return new AwaitValue(value); } `; helpers.asyncGeneratorDelegate = helper("7.0.0-beta.0")` export default function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function (resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; }; if (typeof Symbol === "function" && Symbol.iterator) { iter[Symbol.iterator] = function () { return this; }; } iter.next = function (value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function (value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function (value) { return pump("return", value); }; } return iter; } `; helpers.asyncToGenerator = helper("7.0.0-beta.0")` function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } export default function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } `; helpers.classCallCheck = helper("7.0.0-beta.0")` export default function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } `; helpers.createClass = helper("7.0.0-beta.0")` function _defineProperties(target, props) { for (var i = 0; i < props.length; i ++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } export default function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } `; helpers.defineEnumerableProperties = helper("7.0.0-beta.0")` export default function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, key, desc); } // Symbols are not enumerated over by for-in loops. If native // Symbols are available, fetch all of the descs object's own // symbol properties and define them on our target object too. if (Object.getOwnPropertySymbols) { var objectSymbols = Object.getOwnPropertySymbols(descs); for (var i = 0; i < objectSymbols.length; i++) { var sym = objectSymbols[i]; var desc = descs[sym]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, sym, desc); } } return obj; } `; helpers.defaults = helper("7.0.0-beta.0")` export default function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } `; helpers.defineProperty = helper("7.0.0-beta.0")` export default function _defineProperty(obj, key, value) { // Shortcircuit the slow defineProperty path when possible. // We are trying to avoid issues where setters defined on the // prototype cause side effects under the fast path of simple // assignment. By checking for existence of the property with // the in operator, we can optimize most of this overhead away. if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } `; helpers.extends = helper("7.0.0-beta.0")` export default function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } `; // This old helper can be removed in babel v8 helpers.objectSpread = helper("7.0.0-beta.0")` import defineProperty from "defineProperty"; export default function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { defineProperty(target, key, source[key]); }); } return target; } `; helpers.objectSpread2 = helper("7.5.0")` import defineProperty from "defineProperty"; // This function is different to "Reflect.ownKeys". The enumerableOnly // filters on symbol properties only. Returned string properties are always // enumerable. It is good to use in objectSpread. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } export default function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key) ); }); } } return target; } `; helpers.inherits = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; export default function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } `; helpers.inheritsLoose = helper("7.0.0-beta.0")` export default function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } `; helpers.getPrototypeOf = helper("7.0.0-beta.0")` export default function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } `; helpers.setPrototypeOf = helper("7.0.0-beta.0")` export default function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } `; helpers.construct = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; // core-js@3 if (Reflect.construct.sham) return false; // Proxy can't be polyfilled. Every browser implemented // proxies before or at the same time as Reflect.construct, // so if they support Proxy they also support Reflect.construct. if (typeof Proxy === "function") return true; // Since Reflect.construct can't be properly polyfilled, some // implementations (e.g. core-js@2) don't set the correct internal slots. // Those polyfills don't allow us to subclass built-ins, so we need to // use our fallback implementation. try { // If the internal slots aren't set, this throws an error similar to // TypeError: this is not a Date object. Date.prototype.toString.call(Reflect.construct(Date, [], function() {})); return true; } catch (e) { return false; } } export default function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { // NOTE: If Parent !== Class, the correct __proto__ is set *after* // calling the constructor. _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }; } // Avoid issues with Class being present but undefined when it wasn't // present in the original call. return _construct.apply(null, arguments); } `; helpers.isNativeFunction = helper("7.0.0-beta.0")` export default function _isNativeFunction(fn) { // Note: This function returns "true" for core-js functions. return Function.toString.call(fn).indexOf("[native code]") !== -1; } `; // Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes helpers.wrapNativeSuper = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; import setPrototypeOf from "setPrototypeOf"; import isNativeFunction from "isNativeFunction"; import construct from "construct"; export default function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct(Class, arguments, getPrototypeOf(this).constructor) } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true, } }); return setPrototypeOf(Wrapper, Class); } return _wrapNativeSuper(Class) } `; helpers.instanceof = helper("7.0.0-beta.0")` export default function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } `; helpers.interopRequireDefault = helper("7.0.0-beta.0")` export default function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } `; helpers.interopRequireWildcard = helper("7.0.0-beta.0")` function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } export default function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } `; helpers.newArrowCheck = helper("7.0.0-beta.0")` export default function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } `; helpers.objectDestructuringEmpty = helper("7.0.0-beta.0")` export default function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); } `; helpers.objectWithoutPropertiesLoose = helper("7.0.0-beta.0")` export default function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } `; helpers.objectWithoutProperties = helper("7.0.0-beta.0")` import objectWithoutPropertiesLoose from "objectWithoutPropertiesLoose"; export default function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } `; helpers.assertThisInitialized = helper("7.0.0-beta.0")` export default function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } `; helpers.possibleConstructorReturn = helper("7.0.0-beta.0")` import assertThisInitialized from "assertThisInitialized"; export default function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } `; helpers.superPropBase = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; export default function _superPropBase(object, property) { // Yes, this throws if object is null to being with, that's on purpose. while (!Object.prototype.hasOwnProperty.call(object, property)) { object = getPrototypeOf(object); if (object === null) break; } return object; } `; helpers.get = helper("7.0.0-beta.0")` import superPropBase from "superPropBase"; export default function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } `; helpers.set = helper("7.0.0-beta.0")` import superPropBase from "superPropBase"; import defineProperty from "defineProperty"; function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { // Both getter and non-writable fall into this. return false; } } // Without a super that defines the property, spec boils down to // "define on receiver" for some reason. desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { // Setter, getter, and non-writable fall into this. return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { // Avoid setters that may be defined on Sub's prototype, but not on // the instance. defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } export default function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } `; helpers.taggedTemplateLiteral = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } `; helpers.taggedTemplateLiteralLoose = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; } `; helpers.readOnlyError = helper("7.0.0-beta.0")` export default function _readOnlyError(name) { throw new Error("\\"" + name + "\\" is read-only"); } `; helpers.classNameTDZError = helper("7.0.0-beta.0")` export default function _classNameTDZError(name) { throw new Error("Class \\"" + name + "\\" cannot be referenced in computed property keys."); } `; helpers.temporalUndefined = helper("7.0.0-beta.0")` // This function isn't mean to be called, but to be used as a reference. // We can't use a normal object because it isn't hoisted. export default function _temporalUndefined() {} `; helpers.tdz = helper("7.5.5")` export default function _tdzError(name) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } `; helpers.temporalRef = helper("7.0.0-beta.0")` import undef from "temporalUndefined"; import err from "tdz"; export default function _temporalRef(val, name) { return val === undef ? err(name) : val; } `; helpers.slicedToArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimit from "iterableToArrayLimit"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); } `; helpers.slicedToArrayLoose = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimitLoose from "iterableToArrayLimitLoose"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArrayLoose(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || nonIterableRest(); } `; helpers.toArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArray from "iterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _toArray(arr) { return arrayWithHoles(arr) || iterableToArray(arr) || nonIterableRest(); } `; helpers.toConsumableArray = helper("7.0.0-beta.0")` import arrayWithoutHoles from "arrayWithoutHoles"; import iterableToArray from "iterableToArray"; import nonIterableSpread from "nonIterableSpread"; export default function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } `; helpers.arrayWithoutHoles = helper("7.0.0-beta.0")` export default function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } `; helpers.arrayWithHoles = helper("7.0.0-beta.0")` export default function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } `; helpers.iterableToArray = helper("7.0.0-beta.0")` export default function _iterableToArray(iter) { if ( Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]" ) return Array.from(iter); } `; helpers.iterableToArrayLimit = helper("7.0.0-beta.0")` export default function _iterableToArrayLimit(arr, i) { // this is an expanded form of \`for...of\` that properly supports abrupt completions of // iterators etc. variable names have been minimised to reduce the size of this massive // helper. sometimes spec compliancy is annoying :( // // _n = _iteratorNormalCompletion // _d = _didIteratorError // _e = _iteratorError // _i = _iterator // _s = _step var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } `; helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")` export default function _iterableToArrayLimitLoose(arr, i) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } `; helpers.nonIterableSpread = helper("7.0.0-beta.0")` export default function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } `; helpers.nonIterableRest = helper("7.0.0-beta.0")` export default function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } `; helpers.skipFirstGeneratorNext = helper("7.0.0-beta.0")` export default function _skipFirstGeneratorNext(fn) { return function () { var it = fn.apply(this, arguments); it.next(); return it; } } `; helpers.toPrimitive = helper("7.1.5")` export default function _toPrimitive( input, hint /*: "default" | "string" | "number" | void */ ) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } `; helpers.toPropertyKey = helper("7.1.5")` import toPrimitive from "toPrimitive"; export default function _toPropertyKey(arg) { var key = toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } `; /** * Add a helper that will throw a useful error if the transform fails to detect the class * property assignment, so users know something failed. */ helpers.initializerWarningHelper = helper("7.0.0-beta.0")` export default function _initializerWarningHelper(descriptor, context){ throw new Error( 'Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and set to use loose mode. ' + 'To use proposal-class-properties in spec mode with decorators, wait for ' + 'the next major version of decorators in stage 2.' ); } `; /** * Add a helper to call as a replacement for class property definition. */ helpers.initializerDefineProperty = helper("7.0.0-beta.0")` export default function _initializerDefineProperty(target, property, descriptor, context){ if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0, }); } `; /** * Add a helper to take an initial descriptor, apply some decorators to it, and optionally * define the property. */ helpers.applyDecoratedDescriptor = helper("7.0.0-beta.0")` export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context){ var desc = {}; Object.keys(descriptor).forEach(function(key){ desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer){ desc.writable = true; } desc = decorators.slice().reverse().reduce(function(desc, decorator){ return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0){ desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0){ // This is a hack to avoid this being processed by 'transform-runtime'. // See issue #9. Object.defineProperty(target, property, desc); desc = null; } return desc; } `; helpers.classPrivateFieldLooseKey = helper("7.0.0-beta.0")` var id = 0; export default function _classPrivateFieldKey(name) { return "__private_" + (id++) + "_" + name; } `; helpers.classPrivateFieldLooseBase = helper("7.0.0-beta.0")` export default function _classPrivateFieldBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } `; helpers.classPrivateFieldGet = helper("7.0.0-beta.0")` export default function _classPrivateFieldGet(receiver, privateMap) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError("attempted to get private field on non-instance"); } if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; } `; helpers.classPrivateFieldSet = helper("7.0.0-beta.0")` export default function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError("attempted to set private field on non-instance"); } if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } return value; } `; helpers.classPrivateFieldDestructureSet = helper("7.4.4")` export default function _classPrivateFieldDestructureSet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } var descriptor = privateMap.get(receiver); if (descriptor.set) { if (!("__destrObj" in descriptor)) { descriptor.__destrObj = { set value(v) { descriptor.set.call(receiver, v) }, }; } return descriptor.__destrObj; } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } return descriptor; } } `; helpers.classStaticPrivateFieldSpecGet = helper("7.0.2")` export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } return descriptor.value; } `; helpers.classStaticPrivateFieldSpecSet = helper("7.0.2")` export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; return value; } `; helpers.classStaticPrivateMethodGet = helper("7.3.2")` export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } return method; } `; helpers.classStaticPrivateMethodSet = helper("7.3.2")` export default function _classStaticPrivateMethodSet() { throw new TypeError("attempted to set read only static private field"); } `; helpers.decorate = helper("7.1.5")` import toArray from "toArray"; import toPropertyKey from "toPropertyKey"; // These comments are stripped by @babel/template /*:: type PropertyDescriptor = | { value: any, writable: boolean, configurable: boolean, enumerable: boolean, } | { get?: () => any, set?: (v: any) => void, configurable: boolean, enumerable: boolean, }; type FieldDescriptor ={ writable: boolean, configurable: boolean, enumerable: boolean, }; type Placement = "static" | "prototype" | "own"; type Key = string | symbol; // PrivateName is not supported yet. type ElementDescriptor = | { kind: "method", key: Key, placement: Placement, descriptor: PropertyDescriptor } | { kind: "field", key: Key, placement: Placement, descriptor: FieldDescriptor, initializer?: () => any, }; // This is exposed to the user code type ElementObjectInput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" }; // This is exposed to the user code type ElementObjectOutput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" extras?: ElementDescriptor[], finisher?: ClassFinisher, }; // This is exposed to the user code type ClassObject = { [@@toStringTag]?: "Descriptor", kind: "class", elements: ElementDescriptor[], }; type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput; type ClassDecorator = (descriptor: ClassObject) => ?ClassObject; type ClassFinisher = <A, B>(cl: Class<A>) => Class<B>; // Only used by Babel in the transform output, not part of the spec. type ElementDefinition = | { kind: "method", value: any, key: Key, static?: boolean, decorators?: ElementDecorator[], } | { kind: "field", value: () => any, key: Key, static?: boolean, decorators?: ElementDecorator[], }; declare function ClassFactory<C>(initialize: (instance: C) => void): { F: Class<C>, d: ElementDefinition[] } */ /*:: // Various combinations with/without extras and with one or many finishers type ElementFinisherExtras = { element: ElementDescriptor, finisher?: ClassFinisher, extras?: ElementDescriptor[], }; type ElementFinishersExtras = { element: ElementDescriptor, finishers: ClassFinisher[], extras: ElementDescriptor[], }; type ElementsFinisher = { elements: ElementDescriptor[], finisher?: ClassFinisher, }; type ElementsFinishers = { elements: ElementDescriptor[], finishers: ClassFinisher[], }; */ /*:: type Placements = { static: Key[], prototype: Key[], own: Key[], }; */ // ClassDefinitionEvaluation (Steps 26-*) export default function _decorate( decorators /*: ClassDecorator[] */, factory /*: ClassFactory */, superClass /*: ?Class<*> */, mixins /*: ?Array<Function> */, ) /*: Class<*> */ { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass( _coalesceClassElements(r.d.map(_createElementDescriptor)), decorators, ); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } function _getDecoratorsApi() { _getDecoratorsApi = function() { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], // InitializeInstanceElements initializeInstanceElements: function( /*::<C>*/ O /*: C */, elements /*: ElementDescriptor[] */, ) { ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, // InitializeClassElements initializeClassElements: function( /*::<C>*/ F /*: Class<C> */, elements /*: ElementDescriptor[] */, ) { var proto = F.prototype; ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { var placement = element.placement; if ( element.kind === kind && (placement === "static" || placement === "prototype") ) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, // DefineClassElement defineClassElement: function( /*::<C>*/ receiver /*: C | Class<C> */, element /*: ElementDescriptor */, ) { var descriptor /*: PropertyDescriptor */ = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver), }; } Object.defineProperty(receiver, element.key, descriptor); }, // DecorateClass decorateClass: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var newElements /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; var placements /*: Placements */ = { static: [], prototype: [], own: [], }; elements.forEach(function(element /*: ElementDescriptor */) { this.addElementPlacement(element, placements); }, this); elements.forEach(function(element /*: ElementDescriptor */) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement( element, placements, ); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result /*: ElementsFinishers */ = this.decorateConstructor( newElements, decorators, ); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, // AddElementPlacement addElementPlacement: function( element /*: ElementDescriptor */, placements /*: Placements */, silent /*: boolean */, ) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, // DecorateElement decorateElement: function( element /*: ElementDescriptor */, placements /*: Placements */, ) /*: ElementFinishersExtras */ { var extras /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; for ( var decorators = element.decorators, i = decorators.length - 1; i >= 0; i-- ) { // (inlined) RemoveElementPlacement var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor( element, ); var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras( (0, decorators[i])(elementObject) /*: ElementObjectOutput */ || elementObject, ); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras /*: ElementDescriptor[] | void */ = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, // DecorateConstructor decorateConstructor: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var finishers /*: ClassFinisher[] */ = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj /*: ClassObject */ = this.fromClassDescriptor(elements); var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor( (0, decorators[i])(obj) /*: ClassObject */ || obj, ); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if ( elements[j].key === elements[k].key && elements[j].placement === elements[k].placement ) { throw new TypeError( "Duplicated element (" + elements[j].key + ")", ); } } } } } return { elements: elements, finishers: finishers }; }, // FromElementDescriptor fromElementDescriptor: function( element /*: ElementDescriptor */, ) /*: ElementObject */ { var obj /*: ElementObject */ = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor, }; var desc = { value: "Descriptor", configurable: true, }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, // ToElementDescriptors toElementDescriptors: function( elementObjects /*: ElementObject[] */, ) /*: ElementDescriptor[] */ { if (elementObjects === undefined) return; return toArray(elementObjects).map(function(elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, // ToElementDescriptor toElementDescriptor: function( elementObject /*: ElementObject */, ) /*: ElementDescriptor */ { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError( 'An element descriptor\\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"', ); } var key = toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if ( placement !== "static" && placement !== "prototype" && placement !== "own" ) { throw new TypeError( 'An element descriptor\\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"', ); } var descriptor /*: PropertyDescriptor */ = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element /*: ElementDescriptor */ = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor), }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty( descriptor, "get", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "set", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "value", "The property descriptor of a field descriptor", ); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function( elementObject /*: ElementObject */, ) /*: ElementFinisherExtras */ { var element /*: ElementDescriptor */ = this.toElementDescriptor( elementObject, ); var finisher /*: ClassFinisher */ = _optionalCallableProperty( elementObject, "finisher", ); var extras /*: ElementDescriptors[] */ = this.toElementDescriptors( elementObject.extras, ); return { element: element, finisher: finisher, extras: extras }; }, // FromClassDescriptor fromClassDescriptor: function( elements /*: ElementDescriptor[] */, ) /*: ClassObject */ { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this), }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, // ToClassDescriptor toClassDescriptor: function( obj /*: ClassObject */, ) /*: ElementsFinisher */ { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError( 'A class descriptor\\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"', ); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, // RunClassFinishers runClassFinishers: function( constructor /*: Class<*> */, finishers /*: ClassFinisher[] */, ) /*: Class<*> */ { for (var i = 0; i < finishers.length; i++) { var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor); if (newConstructor !== undefined) { // NOTE: This should check if IsConstructor(newConstructor) is false. if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function(obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } // ClassElementEvaluation function _createElementDescriptor( def /*: ElementDefinition */, ) /*: ElementDescriptor */ { var key = toPropertyKey(def.key); var descriptor /*: PropertyDescriptor */; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false, }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element /*: ElementDescriptor */ = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor, }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } // CoalesceGetterSetter function _coalesceGetterSetter( element /*: ElementDescriptor */, other /*: ElementDescriptor */, ) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } // CoalesceClassElements function _coalesceClassElements( elements /*: ElementDescriptor[] */, ) /*: ElementDescriptor[] */ { var newElements /*: ElementDescriptor[] */ = []; var isSameElement = function( other /*: ElementDescriptor */, ) /*: boolean */ { return ( other.kind === "method" && other.key === element.key && other.placement === element.placement ); }; for (var i = 0; i < elements.length; i++) { var element /*: ElementDescriptor */ = elements[i]; var other /*: ElementDescriptor */; if ( element.kind === "method" && (other = newElements.find(isSameElement)) ) { if ( _isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor) ) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError( "Duplicated methods (" + element.key + ") can't be decorated.", ); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError( "Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").", ); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ { return element.decorators && element.decorators.length; } function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ { return ( desc !== undefined && !(desc.value === undefined && desc.writable === undefined) ); } function _optionalCallableProperty /*::<T>*/( obj /*: T */, name /*: $Keys<T> */, ) /*: ?Function */ { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } `; helpers.classPrivateMethodGet = helper("7.1.6")` export default function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; } `; helpers.classPrivateMethodSet = helper("7.1.6")` export default function _classPrivateMethodSet() { throw new TypeError("attempted to reassign private method"); } `; helpers.wrapRegExp = helper("7.2.6")` import wrapNativeSuper from "wrapNativeSuper"; import getPrototypeOf from "getPrototypeOf"; import possibleConstructorReturn from "possibleConstructorReturn"; import inherits from "inherits"; export default function _wrapRegExp(re, groups) { _wrapRegExp = function(re, groups) { return new BabelRegExp(re, undefined, groups); }; var _RegExp = wrapNativeSuper(RegExp); var _super = RegExp.prototype; var _groups = new WeakMap(); function BabelRegExp(re, flags, groups) { var _this = _RegExp.call(this, re, flags); // if the regex is recreated with 'g' flag _groups.set(_this, groups || _groups.get(re)); return _this; } inherits(BabelRegExp, _RegExp); BabelRegExp.prototype.exec = function(str) { var result = _super.exec.call(this, str); if (result) result.groups = buildGroups(result, this); return result; }; BabelRegExp.prototype[Symbol.replace] = function(str, substitution) { if (typeof substitution === "string") { var groups = _groups.get(this); return _super[Symbol.replace].call( this, str, substitution.replace(/\\$<([^>]+)>/g, function(_, name) { return "$" + groups[name]; }) ); } else if (typeof substitution === "function") { var _this = this; return _super[Symbol.replace].call( this, str, function() { var args = []; args.push.apply(args, arguments); if (typeof args[args.length - 1] !== "object") { // Modern engines already pass result.groups as the last arg. args.push(buildGroups(args, _this)); } return substitution.apply(this, args); } ); } else { return _super[Symbol.replace].call(this, str, substitution); } } function buildGroups(result, re) { // NOTE: This function should return undefined if there are no groups, // but in that case Babel doesn't add the wrapper anyway. var g = _groups.get(re); return Object.keys(g).reduce(function(groups, name) { groups[name] = result[g[name]]; return groups; }, Object.create(null)); } return _wrapRegExp.apply(this, arguments); } `;
packages/babel-helpers/src/helpers.js
1
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.9991717338562012, 0.02136734500527382, 0.00016292365035042167, 0.00017525326984468848, 0.14029653370380402 ]
{ "id": 2, "code_window": [ "\n", "helpers.objectSpread2 = helper(\"7.5.0\")`\n", " import defineProperty from \"defineProperty\";\n", "\n", " // This function is different to \"Reflect.ownKeys\". The enumerableOnly\n", " // filters on symbol properties only. Returned string properties are always \n", " // enumerable. It is good to use in objectSpread.\n", "\n", " function ownKeys(object, enumerableOnly) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // filters on symbol properties only. Returned string properties are always\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 412 }
{ "type": "File", "start": 0, "end": 9, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 9 } }, "program": { "type": "Program", "start": 0, "end": 9, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 9 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 9, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 9 } }, "expression": { "type": "BinaryExpression", "start": 0, "end": 9, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 9 } }, "left": { "type": "Identifier", "start": 0, "end": 5, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 5 }, "identifierName": "yield" }, "name": "yield" }, "operator": "*", "right": { "type": "NumericLiteral", "start": 7, "end": 9, "loc": { "start": { "line": 1, "column": 7 }, "end": { "line": 1, "column": 9 } }, "extra": { "rawValue": 10, "raw": "10" }, "value": 10 } } } ], "directives": [] } }
packages/babel-parser/test/fixtures/es2015/yield/yield-star-in-global-scope-is-multiplication/output.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.0001749023504089564, 0.00017277407459914684, 0.00017024518456310034, 0.0001731391967041418, 0.0000016692356439307332 ]
{ "id": 2, "code_window": [ "\n", "helpers.objectSpread2 = helper(\"7.5.0\")`\n", " import defineProperty from \"defineProperty\";\n", "\n", " // This function is different to \"Reflect.ownKeys\". The enumerableOnly\n", " // filters on symbol properties only. Returned string properties are always \n", " // enumerable. It is good to use in objectSpread.\n", "\n", " function ownKeys(object, enumerableOnly) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // filters on symbol properties only. Returned string properties are always\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 412 }
{ "type": "File", "start": 0, "end": 54, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 4, "column": 10 } }, "program": { "type": "Program", "start": 0, "end": 54, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 4, "column": 10 } }, "sourceType": "module", "interpreter": null, "body": [ { "type": "ExpressionStatement", "start": 44, "end": 54, "loc": { "start": { "line": 4, "column": 0 }, "end": { "line": 4, "column": 10 } }, "expression": { "type": "CallExpression", "start": 44, "end": 53, "loc": { "start": { "line": 4, "column": 0 }, "end": { "line": 4, "column": 9 } }, "callee": { "type": "Identifier", "start": 44, "end": 47, "loc": { "start": { "line": 4, "column": 0 }, "end": { "line": 4, "column": 3 }, "identifierName": "foo" }, "name": "foo" }, "typeArguments": { "type": "TypeParameterInstantiation", "start": 47, "end": 50, "loc": { "start": { "line": 4, "column": 3 }, "end": { "line": 4, "column": 6 } }, "params": [ { "type": "GenericTypeAnnotation", "start": 48, "end": 49, "loc": { "start": { "line": 4, "column": 4 }, "end": { "line": 4, "column": 5 } }, "typeParameters": null, "id": { "type": "Identifier", "start": 48, "end": 49, "loc": { "start": { "line": 4, "column": 4 }, "end": { "line": 4, "column": 5 }, "identifierName": "x" }, "name": "x" } } ] }, "arguments": [ { "type": "Identifier", "start": 51, "end": 52, "loc": { "start": { "line": 4, "column": 7 }, "end": { "line": 4, "column": 8 }, "identifierName": "y" }, "name": "y" } ] }, "leadingComments": [ { "type": "CommentLine", "value": " arbitrary comment", "start": 14, "end": 34, "loc": { "start": { "line": 2, "column": 0 }, "end": { "line": 2, "column": 20 } } }, { "type": "CommentLine", "value": " @flow", "start": 35, "end": 43, "loc": { "start": { "line": 3, "column": 0 }, "end": { "line": 3, "column": 8 } } } ] } ], "directives": [ { "type": "Directive", "start": 0, "end": 13, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 13 } }, "value": { "type": "DirectiveLiteral", "start": 0, "end": 12, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 12 } }, "value": "use strict", "extra": { "raw": "'use strict'", "rawValue": "use strict" } }, "trailingComments": [ { "type": "CommentLine", "value": " arbitrary comment", "start": 14, "end": 34, "loc": { "start": { "line": 2, "column": 0 }, "end": { "line": 2, "column": 20 } } }, { "type": "CommentLine", "value": " @flow", "start": 35, "end": 43, "loc": { "start": { "line": 3, "column": 0 }, "end": { "line": 3, "column": 8 } } } ] } ] }, "comments": [ { "type": "CommentLine", "value": " arbitrary comment", "start": 14, "end": 34, "loc": { "start": { "line": 2, "column": 0 }, "end": { "line": 2, "column": 20 } } }, { "type": "CommentLine", "value": " @flow", "start": 35, "end": 43, "loc": { "start": { "line": 3, "column": 0 }, "end": { "line": 3, "column": 8 } } } ] }
packages/babel-parser/test/fixtures/flow/pragma/4/output.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00017555832164362073, 0.000172992076841183, 0.00017075063078664243, 0.00017305172514170408, 0.0000013703803460884956 ]
{ "id": 2, "code_window": [ "\n", "helpers.objectSpread2 = helper(\"7.5.0\")`\n", " import defineProperty from \"defineProperty\";\n", "\n", " // This function is different to \"Reflect.ownKeys\". The enumerableOnly\n", " // filters on symbol properties only. Returned string properties are always \n", " // enumerable. It is good to use in objectSpread.\n", "\n", " function ownKeys(object, enumerableOnly) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // filters on symbol properties only. Returned string properties are always\n" ], "file_path": "packages/babel-helpers/src/helpers.js", "type": "replace", "edit_start_line_idx": 412 }
var Test = function Test() { "use strict"; babelHelpers.classCallCheck(this, Test); };
packages/babel-plugin-transform-classes/test/fixtures/spec/plain-class/output.js
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00016926138778217137, 0.00016926138778217137, 0.00016926138778217137, 0.00016926138778217137, 0 ]
{ "id": 3, "code_window": [ "var REACT_ELEMENT_TYPE;\n", "\n", "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n", "\n", "var _ref =\n", "/*#__PURE__*/\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n" ], "file_path": "packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/inline-elements/output.js", "type": "replace", "edit_start_line_idx": 2 }
var REACT_ELEMENT_TYPE; function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; } var _ref = /*#__PURE__*/ _jsx("foo", {}); function render() { return _ref; } function render() { var text = getText(); var _ref2 = /*#__PURE__*/ _jsx("foo", {}, void 0, text); return function () { return _ref2; }; }
packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/inline-elements/output.js
1
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.9983252882957458, 0.6592696905136108, 0.0001750234659994021, 0.9793087840080261, 0.46611496806144714 ]
{ "id": 3, "code_window": [ "var REACT_ELEMENT_TYPE;\n", "\n", "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n", "\n", "var _ref =\n", "/*#__PURE__*/\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n" ], "file_path": "packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/inline-elements/output.js", "type": "replace", "edit_start_line_idx": 2 }
{ "type": "File", "start": 0, "end": 26, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 4, "column": 1 } }, "program": { "type": "Program", "start": 0, "end": 26, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 4, "column": 1 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "BlockStatement", "start": 0, "end": 26, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 4, "column": 1 } }, "body": [ { "type": "ExpressionStatement", "start": 6, "end": 10, "loc": { "start": { "line": 2, "column": 4 }, "end": { "line": 2, "column": 8 } }, "expression": { "type": "CallExpression", "start": 6, "end": 9, "loc": { "start": { "line": 2, "column": 4 }, "end": { "line": 2, "column": 7 } }, "callee": { "type": "Identifier", "start": 6, "end": 7, "loc": { "start": { "line": 2, "column": 4 }, "end": { "line": 2, "column": 5 }, "identifierName": "a" }, "name": "a" }, "arguments": [] }, "trailingComments": [ { "type": "CommentLine", "value": "comment", "start": 15, "end": 24, "loc": { "start": { "line": 3, "column": 4 }, "end": { "line": 3, "column": 13 } } } ] } ], "directives": [] } ], "directives": [] }, "comments": [ { "type": "CommentLine", "value": "comment", "start": 15, "end": 24, "loc": { "start": { "line": 3, "column": 4 }, "end": { "line": 3, "column": 13 } } } ] }
packages/babel-parser/test/fixtures/comments/basic/block-trailing-comment/output.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.00145349174272269, 0.0005474803620018065, 0.00023415166651830077, 0.0005068971076980233, 0.0002983609738294035 ]
{ "id": 3, "code_window": [ "var REACT_ELEMENT_TYPE;\n", "\n", "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n", "\n", "var _ref =\n", "/*#__PURE__*/\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n" ], "file_path": "packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/inline-elements/output.js", "type": "replace", "edit_start_line_idx": 2 }
{ "type": "File", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "program": { "type": "Program", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "sourceType": "module", "interpreter": null, "body": [ { "type": "VariableDeclaration", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "declarations": [ { "type": "VariableDeclarator", "start": 4, "end": 17, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 17 } }, "id": { "type": "Identifier", "start": 4, "end": 17, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 17 }, "identifierName": "a" }, "name": "a", "typeAnnotation": { "type": "TypeAnnotation", "start": 5, "end": 17, "loc": { "start": { "line": 1, "column": 5 }, "end": { "line": 1, "column": 17 } }, "typeAnnotation": { "type": "TypeofTypeAnnotation", "start": 8, "end": 16, "loc": { "start": { "line": 1, "column": 8 }, "end": { "line": 1, "column": 16 } }, "argument": { "type": "GenericTypeAnnotation", "start": 15, "end": 16, "loc": { "start": { "line": 1, "column": 15 }, "end": { "line": 1, "column": 16 } }, "typeParameters": null, "id": { "type": "Identifier", "start": 15, "end": 16, "loc": { "start": { "line": 1, "column": 15 }, "end": { "line": 1, "column": 16 }, "identifierName": "A" }, "name": "A" } } } } }, "init": null } ], "kind": "var" } ], "directives": [] } }
packages/babel-parser/test/fixtures/flow/type-grouping/4/output.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.0013341042213141918, 0.000570218893699348, 0.00035586091689765453, 0.0004987134016118944, 0.000266741233645007 ]
{ "id": 3, "code_window": [ "var REACT_ELEMENT_TYPE;\n", "\n", "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n", "\n", "var _ref =\n", "/*#__PURE__*/\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\") || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0 }; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null }; }\n" ], "file_path": "packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/inline-elements/output.js", "type": "replace", "edit_start_line_idx": 2 }
{ "type": "File", "start": 0, "end": 38, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 38 } }, "program": { "type": "Program", "start": 0, "end": 38, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 38 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "VariableDeclaration", "start": 0, "end": 38, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 38 } }, "declarations": [ { "type": "VariableDeclarator", "start": 4, "end": 37, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 37 } }, "id": { "type": "Identifier", "start": 4, "end": 9, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 9 }, "identifierName": "hello" }, "name": "hello" }, "init": { "type": "FunctionExpression", "start": 12, "end": 37, "loc": { "start": { "line": 1, "column": 12 }, "end": { "line": 1, "column": 37 } }, "id": { "type": "Identifier", "start": 21, "end": 23, "loc": { "start": { "line": 1, "column": 21 }, "end": { "line": 1, "column": 23 }, "identifierName": "hi" }, "name": "hi" }, "generator": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 26, "end": 37, "loc": { "start": { "line": 1, "column": 26 }, "end": { "line": 1, "column": 37 } }, "body": [ { "type": "ExpressionStatement", "start": 28, "end": 35, "loc": { "start": { "line": 1, "column": 28 }, "end": { "line": 1, "column": 35 } }, "expression": { "type": "CallExpression", "start": 28, "end": 35, "loc": { "start": { "line": 1, "column": 28 }, "end": { "line": 1, "column": 35 } }, "callee": { "type": "Identifier", "start": 28, "end": 33, "loc": { "start": { "line": 1, "column": 28 }, "end": { "line": 1, "column": 33 }, "identifierName": "sayHi" }, "name": "sayHi" }, "arguments": [] } } ], "directives": [] } } } ], "kind": "var" } ], "directives": [] } }
packages/babel-parser/test/fixtures/esprima/declaration-function/migrated_0011/output.json
0
https://github.com/babel/babel/commit/a112be2fa0b2abab7fd9a845b3a76b273c506449
[ 0.0013012753333896399, 0.0006134072318673134, 0.0002163028111681342, 0.000540889916010201, 0.0003153794095851481 ]
{ "id": 0, "code_window": [ "#!/usr/bin/env node\n", "\n", "var commander = require(\"commander\");\n", "var Module = require(\"module\");\n", "var path = require(\"path\");\n", "var util = require(\"../lib/6to5/util\");\n", "var path = require(\"path\");\n", "var repl = require(\"repl\");\n", "var to5 = require(\"../lib/6to5\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 4 }
var traverse = require("./traverse"); var astTypes = require("recast").types; var recast = require("recast"); var path = require("path"); var fs = require("fs"); var _ = require("lodash"); var n = astTypes.namedTypes; var b = astTypes.builders; exports.ensureBlock = function (node) { var block = node.body; if (block.type === "BlockStatement") return; if (!_.isArray(block)) { if (!n.Statement.check(block)) block = b.returnStatement(block); block = [block]; } node.body = b.blockStatement(block); }; exports.getUid = function (parent, file) { var node; if (parent.type === "AssignmentExpression") { node = parent.left; } else if (parent.type === "VariableDeclarator") { node = parent.id; } var id = "ref"; if (node && node.type === "Identifier") { id = node.name; } return b.identifier(file.generateUid(id)); }; exports.isAbsolute = function (loc) { if (!loc) return false; if (loc[0] === "/") return true; // unix if (loc[1] === ":" && loc[2] === "\\") return true; // windows return false; }; exports.removeProperties = function (tree) { var clear = function (node) { delete node.tokens; delete node.range; delete node.loc; }; clear(tree); traverse(tree, clear); return tree; }; exports.getIds = function (node) { var search = [node]; var ids = []; while (search.length) { var id = search.shift(); if (id.type === "Identifier") { ids.push(id.name); } else if (id.type === "ArrayPattern") { _.each(id.elements, function (elem) { search.push(elem); }); } else if (id.type === "ObjectPattern") { _.each(id.properties, function (prop) { search.push(prop.value); }); } else { throw new Error("unknown node " + id.type); } } return ids; }; exports.errorWithNode = function (node, msg) { var line = node.loc.start.line; var col = node.loc.start.column; var err = new SyntaxError("Line " + line + ": " + msg); err.lineNumber = line; err.column = col; return err; }; exports.canCompile = function (filename) { var ext = path.extname(filename); return _.contains([".js", ".es6", ".jsx"], ext); }; exports.sourceMapToComment = function (map) { var json = JSON.stringify(map); var base64 = new Buffer(json).toString("base64"); return "//# sourceMappingURL=data:application/json;base64," + base64; }; exports.pushMutatorMap = function (mutatorMap, key, kind, method) { var map; if (_.has(mutatorMap, key)) { map = mutatorMap[key]; } else { map = {}; } mutatorMap[key] = map; if (map[kind]) { throw new Error("a " + kind + " already exists for this property"); } else { map[kind] = method; } }; exports.buildDefineProperties = function (mutatorMap, keyNode) { var objExpr = b.objectExpression([]); _.each(mutatorMap, function (map, key) { var mapNode = b.objectExpression([]); var propNode = b.property("init", b.identifier(key), mapNode); _.each(map, function (node, key) { node = _.clone(node); if (node.type === "MethodDefinition") node = node.value; mapNode.properties.push(b.property("init", b.identifier(key), node)); }); objExpr.properties.push(propNode); }); return exports.template("object-define-properties", { OBJECT: keyNode, PROPS: objExpr }, true); }; exports.template = function (name, nodes, keepExpression) { var template = exports.templates[name]; if (!template) throw new ReferenceError("unknown template " + name); template = _.cloneDeep(template); if (!_.isEmpty(nodes)) { traverse(template, function (node) { if (node.type === "Identifier" && _.has(nodes, node.name)) { var newNode = nodes[node.name]; if (_.isString(newNode)) { node.name = newNode; } else { return newNode; } } }); } var node = template.body[0]; if (!keepExpression && node.type === "ExpressionStatement") { return node.expression; } else { return node; } }; exports.isReferenced = function (node, parent) { // we're a property key if (parent.type === "Property" && parent.key === node) return false; var isMemberExpression = parent.type === "MemberExpression"; // we're in a member expression and we're the computed property so we're referenced var isComputedProperty = isMemberExpression && parent.property === node && parent.computed; // we're in a member expression and we're the object so we're referenced var isObject = isMemberExpression && parent.object === node; // we are referenced if (!isMemberExpression || isComputedProperty || isObject) return true; return false; }; exports.codeFrame = function (lines, lineNumber, colNumber) { colNumber = Math.max(colNumber, 0); lines = lines.split("\n"); var start = Math.max(lineNumber - 3, 0); var end = Math.min(lines.length, lineNumber + 3); var width = (end + "").length; return "\n" + lines.slice(start, end).map(function (line, i) { var curr = i + start + 1; var gutter = curr === lineNumber ? "> " : " "; var sep = curr + exports.repeat(width + 1); gutter += sep + "| "; var str = gutter + line; if (colNumber && curr === lineNumber) { str += "\n"; str += exports.repeat(gutter.length - 2); str += "|" + exports.repeat(colNumber) + "^"; } return str; }).join("\n"); }; exports.repeat = function (width, cha) { cha = cha || " "; return new Array(width + 1).join(cha); }; exports.parse = function (opts, code, callback) { try { var recastOpts = {}; if (opts.sourceMap) { recastOpts.sourceFileName = opts.sourceFileName; recastOpts.sourceRoot = opts.sourceRoot; } var ast = recast.parse(code, recastOpts); if (callback) { return callback(ast); } else { return ast; } } catch (err) { if (!err._6to5) { err._6to5 = true; err.message = opts.filename + ": " + err.message; if (err.lineNumber) { var frame = exports.codeFrame(code, err.lineNumber, err.column); var err2 = new SyntaxError(err.message + frame); err2._6to5 = true; throw err2; } } throw err; } }; exports.parseNoProperties = function (loc, code) { var ast = exports.parse({ filename: loc }, code).program; return exports.removeProperties(ast); }; try { exports.templates = require("../../templates.json"); } catch (err) { if (err.code !== "MODULE_NOT_FOUND") throw err; exports.templates = {}; var templatesLoc = __dirname + "/templates"; if (!fs.existsSync(templatesLoc)) { throw new Error("no templates directory - this is most likely the result" + " of a broken `npm publish`. Please report to " + "https://github.com/sebmck/6to5/issues"); } _.each(fs.readdirSync(templatesLoc), function (name) { if (name[0] === ".") return; var key = path.basename(name, path.extname(name)); var loc = templatesLoc + "/" + name; var code = fs.readFileSync(loc, "utf8"); exports.templates[key] = exports.parseNoProperties(loc, code); }); }
lib/6to5/util.js
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.980517566204071, 0.07197496294975281, 0.00016678297834005207, 0.00017480066162534058, 0.24823586642742157 ]
{ "id": 0, "code_window": [ "#!/usr/bin/env node\n", "\n", "var commander = require(\"commander\");\n", "var Module = require(\"module\");\n", "var path = require(\"path\");\n", "var util = require(\"../lib/6to5/util\");\n", "var path = require(\"path\");\n", "var repl = require(\"repl\");\n", "var to5 = require(\"../lib/6to5\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 4 }
var rewritePattern = require("regexpu/rewrite-pattern"); var b = require("recast").types.builders; var _ = require("lodash"); exports.Literal = function (node) { var regex = node.regex; if (!regex) return; var flags = regex.flags.split(""); if (!_.contains(regex.flags, "u")) return; _.pull(flags, "u"); var pattern = rewritePattern(regex.pattern, regex.flags); return b.literal(new RegExp(pattern, flags.join(""))); };
lib/6to5/transformers/unicode-regex.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017598687554709613, 0.00017203341121785343, 0.00016807994688861072, 0.00017203341121785343, 0.000003953464329242706 ]
{ "id": 0, "code_window": [ "#!/usr/bin/env node\n", "\n", "var commander = require(\"commander\");\n", "var Module = require(\"module\");\n", "var path = require(\"path\");\n", "var util = require(\"../lib/6to5/util\");\n", "var path = require(\"path\");\n", "var repl = require(\"repl\");\n", "var to5 = require(\"../lib/6to5\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 4 }
{ "throws": "Line 2: Unexpected token ILLEGAL" }
test/fixtures/syntax/errors/syntax/options.json
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00016994448378682137, 0.00016994448378682137, 0.00016994448378682137, 0.00016994448378682137, 0 ]
{ "id": 0, "code_window": [ "#!/usr/bin/env node\n", "\n", "var commander = require(\"commander\");\n", "var Module = require(\"module\");\n", "var path = require(\"path\");\n", "var util = require(\"../lib/6to5/util\");\n", "var path = require(\"path\");\n", "var repl = require(\"repl\");\n", "var to5 = require(\"../lib/6to5\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 4 }
{ "args": ["src", "--source-maps", "--out-dir", "lib"] }
test/fixtures/bin/6to5/dir --out-dir --source-maps/options.json
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017496707732789218, 0.00017496707732789218, 0.00017496707732789218, 0.00017496707732789218, 0 ]
{ "id": 1, "code_window": [ "\n", "commander.option(\"-e, --eval [script]\", \"evaluate script\");\n", "commander.option(\"-p, --print\", \"evaluate script and print result\");\n", "\n", "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-i, --ignore [regex]\", \"ignore all files that match this regex when using the require hook\");\n", "commander.option(\"-x, --extensions [extensions]\", \"list of extensions to hook into [.es6,.js]\", util.list);\n" ], "file_path": "bin/6to5-node", "type": "add", "edit_start_line_idx": 14 }
#!/usr/bin/env node var commander = require("commander"); var Module = require("module"); var path = require("path"); var util = require("../lib/6to5/util"); var path = require("path"); var repl = require("repl"); var to5 = require("../lib/6to5"); var vm = require("vm"); var _ = require("lodash"); commander.option("-e, --eval [script]", "evaluate script"); commander.option("-p, --print", "evaluate script and print result"); var pkg = require("../package.json"); commander.version(pkg.version); commander.usage("[options] [ -e script | script.js ] [arguments]"); commander.parse(process.argv); to5.register(); var _eval = function (code, filename) { code = to5.transform(code, { filename: filename }).code; return vm.runInThisContext(code, filename); }; if (commander.eval) { var code = to5.transform(commander.eval, { filename: "eval" }).code; var result = _eval(code, "eval"); if (commander.print) console.log(result); } else { var filenames = commander.args; if (filenames.length) { _.each(filenames, function (filename) { if (!util.isAbsolute(filename)) { filename = path.join(process.cwd(), filename); } require(require.resolve(filename)); }); } else { replStart(); } } function replStart() { repl.start({ prompt: "> ", input: process.stdin, output: process.stdout, eval: replEval, useGlobal: true }); } function replEval(code, context, filename, callback) { var err; var result; try { code = code.slice(1, -2); // remove "(" and "\n)" result = _eval(code, filename); } catch (e) { err = e; } callback(err, result); }
bin/6to5-node
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.9981127977371216, 0.12514176964759827, 0.00016680666885804385, 0.000201813702005893, 0.32995250821113586 ]
{ "id": 1, "code_window": [ "\n", "commander.option(\"-e, --eval [script]\", \"evaluate script\");\n", "commander.option(\"-p, --print\", \"evaluate script and print result\");\n", "\n", "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-i, --ignore [regex]\", \"ignore all files that match this regex when using the require hook\");\n", "commander.option(\"-x, --extensions [extensions]\", \"list of extensions to hook into [.es6,.js]\", util.list);\n" ], "file_path": "bin/6to5-node", "type": "add", "edit_start_line_idx": 14 }
(function (obj) { for (var i in obj) { exports[i] = obj[i]; } }(require(MODULE_NAME)));
lib/6to5/templates/exports-wildcard.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00016977427003439516, 0.00016977427003439516, 0.00016977427003439516, 0.00016977427003439516, 0 ]
{ "id": 1, "code_window": [ "\n", "commander.option(\"-e, --eval [script]\", \"evaluate script\");\n", "commander.option(\"-p, --print\", \"evaluate script and print result\");\n", "\n", "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-i, --ignore [regex]\", \"ignore all files that match this regex when using the require hook\");\n", "commander.option(\"-x, --extensions [extensions]\", \"list of extensions to hook into [.es6,.js]\", util.list);\n" ], "file_path": "bin/6to5-node", "type": "add", "edit_start_line_idx": 14 }
var {topLeft: [x1, y1], bottomRight: [x2, y2] } = rect;
test/fixtures/syntax/destructuring/mixed/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00016479368787258863, 0.00016479368787258863, 0.00016479368787258863, 0.00016479368787258863, 0 ]
{ "id": 1, "code_window": [ "\n", "commander.option(\"-e, --eval [script]\", \"evaluate script\");\n", "commander.option(\"-p, --print\", \"evaluate script and print result\");\n", "\n", "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-i, --ignore [regex]\", \"ignore all files that match this regex when using the require hook\");\n", "commander.option(\"-x, --extensions [extensions]\", \"list of extensions to hook into [.es6,.js]\", util.list);\n" ], "file_path": "bin/6to5-node", "type": "add", "edit_start_line_idx": 14 }
var arr = [for (x of "abcdefgh".split("")) for (y of "12345678".split("")) (x + y)];
test/fixtures/syntax/array-comprehension/multiple/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017142306023743004, 0.00017142306023743004, 0.00017142306023743004, 0.00017142306023743004, 0 ]
{ "id": 2, "code_window": [ "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n", "commander.parse(process.argv);\n", "\n", "to5.register();\n", "\n", "var _eval = function (code, filename) {\n", " code = to5.transform(code, { filename: filename }).code;\n", " return vm.runInThisContext(code, filename);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "//\n", "\n", "var registerOpts = {};\n", "\n", "if (commander.ignore) {\n", " registerOpts.ignoreRegex = new RegExp(commander.ignore);\n", "}\n", "\n", "if (commander.extensions && commander.extensions.length) {\n", " registerOpts.extensions = commander.extensions\n", "}\n", "\n", "to5.register(registerOpts);\n", "\n", "//\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 20 }
var transform = require("./transform"); var fs = require("fs"); var _ = require("lodash"); exports.util = require("./util"); exports.register = function () { return require("./register"); }; exports.polyfill = function () { require("./polyfill"); }; exports.transform = transform; exports.transformFile = function (filename, opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts.filename = filename; fs.readFile(filename, function (err, code) { if (err) return callback(err); var result; try { result = transform(code, opts); } catch (err) { return callback(err); } callback(null, result); }); }; exports.transformFileSync = function (filename, opts) { opts = opts || {}; opts.filename = filename; return transform(fs.readFileSync(filename), opts); };
lib/6to5/index.js
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.9430854916572571, 0.19154156744480133, 0.00016873575805220753, 0.000781373935751617, 0.3758062422275543 ]
{ "id": 2, "code_window": [ "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n", "commander.parse(process.argv);\n", "\n", "to5.register();\n", "\n", "var _eval = function (code, filename) {\n", " code = to5.transform(code, { filename: filename }).code;\n", " return vm.runInThisContext(code, filename);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "//\n", "\n", "var registerOpts = {};\n", "\n", "if (commander.ignore) {\n", " registerOpts.ignoreRegex = new RegExp(commander.ignore);\n", "}\n", "\n", "if (commander.extensions && commander.extensions.length) {\n", " registerOpts.extensions = commander.extensions\n", "}\n", "\n", "to5.register(registerOpts);\n", "\n", "//\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 20 }
var obj = function (_obj) { Object.defineProperties(_obj, { foo: { get: function () { return 5 + 5; } } }); return _obj; }({});
test/fixtures/syntax/property-methods-assignment/getter/expected.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017133905203081667, 0.000170791958225891, 0.00017024486442096531, 0.000170791958225891, 5.470938049256802e-7 ]
{ "id": 2, "code_window": [ "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n", "commander.parse(process.argv);\n", "\n", "to5.register();\n", "\n", "var _eval = function (code, filename) {\n", " code = to5.transform(code, { filename: filename }).code;\n", " return vm.runInThisContext(code, filename);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "//\n", "\n", "var registerOpts = {};\n", "\n", "if (commander.ignore) {\n", " registerOpts.ignoreRegex = new RegExp(commander.ignore);\n", "}\n", "\n", "if (commander.extensions && commander.extensions.length) {\n", " registerOpts.extensions = commander.extensions\n", "}\n", "\n", "to5.register(registerOpts);\n", "\n", "//\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 20 }
var {topLeft: {x: x1, y: y1}, bottomRight: {x: x2, y: y2}} = rect;
test/fixtures/syntax/destructuring/object-advanced/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00016853892884682864, 0.00016853892884682864, 0.00016853892884682864, 0.00016853892884682864, 0 ]
{ "id": 2, "code_window": [ "var pkg = require(\"../package.json\");\n", "commander.version(pkg.version);\n", "commander.usage(\"[options] [ -e script | script.js ] [arguments]\");\n", "commander.parse(process.argv);\n", "\n", "to5.register();\n", "\n", "var _eval = function (code, filename) {\n", " code = to5.transform(code, { filename: filename }).code;\n", " return vm.runInThisContext(code, filename);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "//\n", "\n", "var registerOpts = {};\n", "\n", "if (commander.ignore) {\n", " registerOpts.ignoreRegex = new RegExp(commander.ignore);\n", "}\n", "\n", "if (commander.extensions && commander.extensions.length) {\n", " registerOpts.extensions = commander.extensions\n", "}\n", "\n", "to5.register(registerOpts);\n", "\n", "//\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 20 }
var BaseView = class BaseView { constructor() { this.autoRender = true; } } var BaseView = class { constructor() { this.autoRender = true; } }
test/fixtures/syntax/classes/statement/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017379286873620003, 0.00017299203318543732, 0.0001721911976346746, 0.00017299203318543732, 8.00835550762713e-7 ]
{ "id": 3, "code_window": [ "var sourceMap = require(\"source-map\");\n", "var transform = require(\"../../lib/6to5/transform\");\n", "var chokidar = require(\"chokidar\");\n", "var mkdirp = require(\"mkdirp\");\n", "var path = require(\"path\");\n", "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "commander.option(\"-t, --source-maps-inline\", \"Append sourceMappingURL comment to bottom of code\");\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var util2 = require(\"../../lib/6to5/util\");\n", "var util = require(\"./util\");\n" ], "file_path": "bin/6to5/index.js", "type": "add", "edit_start_line_idx": 7 }
#!/usr/bin/env node var commander = require("commander"); var Module = require("module"); var path = require("path"); var util = require("../lib/6to5/util"); var path = require("path"); var repl = require("repl"); var to5 = require("../lib/6to5"); var vm = require("vm"); var _ = require("lodash"); commander.option("-e, --eval [script]", "evaluate script"); commander.option("-p, --print", "evaluate script and print result"); var pkg = require("../package.json"); commander.version(pkg.version); commander.usage("[options] [ -e script | script.js ] [arguments]"); commander.parse(process.argv); to5.register(); var _eval = function (code, filename) { code = to5.transform(code, { filename: filename }).code; return vm.runInThisContext(code, filename); }; if (commander.eval) { var code = to5.transform(commander.eval, { filename: "eval" }).code; var result = _eval(code, "eval"); if (commander.print) console.log(result); } else { var filenames = commander.args; if (filenames.length) { _.each(filenames, function (filename) { if (!util.isAbsolute(filename)) { filename = path.join(process.cwd(), filename); } require(require.resolve(filename)); }); } else { replStart(); } } function replStart() { repl.start({ prompt: "> ", input: process.stdin, output: process.stdout, eval: replEval, useGlobal: true }); } function replEval(code, context, filename, callback) { var err; var result; try { code = code.slice(1, -2); // remove "(" and "\n)" result = _eval(code, filename); } catch (e) { err = e; } callback(err, result); }
bin/6to5-node
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.9979647397994995, 0.22418734431266785, 0.00016992163727991283, 0.005983369424939156, 0.3796544373035431 ]
{ "id": 3, "code_window": [ "var sourceMap = require(\"source-map\");\n", "var transform = require(\"../../lib/6to5/transform\");\n", "var chokidar = require(\"chokidar\");\n", "var mkdirp = require(\"mkdirp\");\n", "var path = require(\"path\");\n", "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "commander.option(\"-t, --source-maps-inline\", \"Append sourceMappingURL comment to bottom of code\");\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var util2 = require(\"../../lib/6to5/util\");\n", "var util = require(\"./util\");\n" ], "file_path": "bin/6to5/index.js", "type": "add", "edit_start_line_idx": 7 }
var t = function (i, x) { return i * x; };
test/fixtures/syntax/arrow-functions/multiple-arguments/expected.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.0031787205953150988, 0.0031787205953150988, 0.0031787205953150988, 0.0031787205953150988, 0 ]
{ "id": 3, "code_window": [ "var sourceMap = require(\"source-map\");\n", "var transform = require(\"../../lib/6to5/transform\");\n", "var chokidar = require(\"chokidar\");\n", "var mkdirp = require(\"mkdirp\");\n", "var path = require(\"path\");\n", "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "commander.option(\"-t, --source-maps-inline\", \"Append sourceMappingURL comment to bottom of code\");\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var util2 = require(\"../../lib/6to5/util\");\n", "var util = require(\"./util\");\n" ], "file_path": "bin/6to5/index.js", "type": "add", "edit_start_line_idx": 7 }
{ "whitelist": ["arrowFunctions"] }
test/fixtures/syntax/api/whitelist/options.json
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.0001725559268379584, 0.0001725559268379584, 0.0001725559268379584, 0.0001725559268379584, 0 ]
{ "id": 3, "code_window": [ "var sourceMap = require(\"source-map\");\n", "var transform = require(\"../../lib/6to5/transform\");\n", "var chokidar = require(\"chokidar\");\n", "var mkdirp = require(\"mkdirp\");\n", "var path = require(\"path\");\n", "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "commander.option(\"-t, --source-maps-inline\", \"Append sourceMappingURL comment to bottom of code\");\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var util2 = require(\"../../lib/6to5/util\");\n", "var util = require(\"./util\");\n" ], "file_path": "bin/6to5/index.js", "type": "add", "edit_start_line_idx": 7 }
ARRAY.map(function (KEY) { return STATEMENT; });
lib/6to5/templates/array-comprehension-map.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017006281996145844, 0.00017006281996145844, 0.00017006281996145844, 0.00017006281996145844, 0 ]
{ "id": 4, "code_window": [ "commander.option(\"-f, --filename [filename]\", \"Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]\", \"stdin\");\n", "commander.option(\"-w, --watch\", \"Recompile files on changes\");\n", "\n", "var list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n", "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", list);\n", "commander.option(\"-o, --out-file [out]\", \"Compile all input files into a single file\");\n", "commander.option(\"-d, --out-dir [out]\", \"Compile an input directory of modules into an output directory\");\n", "\n", "commander.on(\"--help\", function(){\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", util2.list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", util2.list);\n" ], "file_path": "bin/6to5/index.js", "type": "replace", "edit_start_line_idx": 16 }
#!/usr/bin/env node var commander = require("commander"); var sourceMap = require("source-map"); var transform = require("../../lib/6to5/transform"); var chokidar = require("chokidar"); var mkdirp = require("mkdirp"); var path = require("path"); var fs = require("fs"); var _ = require("lodash"); commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to bottom of code"); commander.option("-s, --source-maps", "Save source map alongside the compiled code"); commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin"); commander.option("-w, --watch", "Recompile files on changes"); var list = function (val) { return val ? val.split(",") : []; }; commander.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", list); commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", list); commander.option("-o, --out-file [out]", "Compile all input files into a single file"); commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory"); commander.on("--help", function(){ console.log(" Transformers:"); console.log(); _.each(_.keys(transform.transformers).sort(), function (key) { if (key[0] === "_") return; console.log(" - " + key); }); console.log(); }); var pkg = require("../../package.json"); commander.version(pkg.version); commander.usage("[options] <files ...>"); commander.parse(process.argv); // var errors = []; var filenames = commander.args; _.each(filenames, function (filename) { if (!fs.existsSync(filename)) { errors.push(filename + " doesn't exist"); } }); if (commander.outDir && !filenames.length) { errors.push("filenames required for --out-dir"); } if (commander.outFile && commander.outDir) { errors.push("cannot have --out-file and --out-dir"); } if (commander.watch) { if (!commander.outFile && !commander.outDir) { errors.push("--watch requires --out-file or --out-dir"); } if (!filenames.length) { errors.push("--watch requires filenames"); } } if (commander.sourceMaps) { if (!commander.outFile && !commander.outDir) { errors.push("--source-maps requires --out-file or --out-dir"); } } if (errors.length) { console.error(errors.join(". ")); process.exit(2); } // exports.opts = { sourceMapName: commander.outFile, blacklist: commander.blacklist, whitelist: commander.whitelist, sourceMap: commander.sourceMaps || commander.sourceMapsInline }; var fn; if (commander.outDir) { fn = require("./dir"); } else { fn = require("./file"); } fn(commander, filenames, exports.opts);
bin/6to5/index.js
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.9986100196838379, 0.2015341967344284, 0.0001650885824346915, 0.0004176228540018201, 0.3984067738056183 ]
{ "id": 4, "code_window": [ "commander.option(\"-f, --filename [filename]\", \"Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]\", \"stdin\");\n", "commander.option(\"-w, --watch\", \"Recompile files on changes\");\n", "\n", "var list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n", "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", list);\n", "commander.option(\"-o, --out-file [out]\", \"Compile all input files into a single file\");\n", "commander.option(\"-d, --out-dir [out]\", \"Compile an input directory of modules into an output directory\");\n", "\n", "commander.on(\"--help\", function(){\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", util2.list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", util2.list);\n" ], "file_path": "bin/6to5/index.js", "type": "replace", "edit_start_line_idx": 16 }
var foo = `test ${foo + bar}`;
test/fixtures/syntax/template-literals/statement/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00021434176596812904, 0.00021434176596812904, 0.00021434176596812904, 0.00021434176596812904, 0 ]
{ "id": 4, "code_window": [ "commander.option(\"-f, --filename [filename]\", \"Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]\", \"stdin\");\n", "commander.option(\"-w, --watch\", \"Recompile files on changes\");\n", "\n", "var list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n", "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", list);\n", "commander.option(\"-o, --out-file [out]\", \"Compile all input files into a single file\");\n", "commander.option(\"-d, --out-dir [out]\", \"Compile an input directory of modules into an output directory\");\n", "\n", "commander.on(\"--help\", function(){\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", util2.list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", util2.list);\n" ], "file_path": "bin/6to5/index.js", "type": "replace", "edit_start_line_idx": 16 }
[a, b] = f();
test/fixtures/syntax/destructuring/assignment/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.0025755895767360926, 0.0025755895767360926, 0.0025755895767360926, 0.0025755895767360926, 0 ]
{ "id": 4, "code_window": [ "commander.option(\"-f, --filename [filename]\", \"Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]\", \"stdin\");\n", "commander.option(\"-w, --watch\", \"Recompile files on changes\");\n", "\n", "var list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n", "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", list);\n", "commander.option(\"-o, --out-file [out]\", \"Compile all input files into a single file\");\n", "commander.option(\"-d, --out-dir [out]\", \"Compile an input directory of modules into an output directory\");\n", "\n", "commander.on(\"--help\", function(){\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "commander.option(\"-w, --whitelist [whitelist]\", \"Whitelist of transformers to ONLY use\", util2.list);\n", "commander.option(\"-b, --blacklist [blacklist]\", \"Blacklist of transformers to NOT use\", util2.list);\n" ], "file_path": "bin/6to5/index.js", "type": "replace", "edit_start_line_idx": 16 }
import { isEven } from "./evens"; export function nextOdd(n) { return isEven(n) ? n + 1 : n + 2; } export var isOdd = (function(isEven) { return function(n) { return !isEven(n); }; })(isEven);
test/fixtures/syntax/modules/hoist-function-exports/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017270488024223596, 0.0001724565081531182, 0.00017220813606400043, 0.0001724565081531182, 2.4837208911776543e-7 ]
{ "id": 5, "code_window": [ "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "exports.util = require(\"./util\");\n", "\n", "exports.register = function () {\n", " return require(\"./register\");\n", "};\n", "\n", "exports.polyfill = function () {\n", " require(\"./polyfill\");\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "exports.register = function (opts) {\n", " var register = require(\"./register\");\n", " if (opts != null) register(opts);\n", " return register;\n" ], "file_path": "lib/6to5/index.js", "type": "replace", "edit_start_line_idx": 6 }
#!/usr/bin/env node var commander = require("commander"); var Module = require("module"); var path = require("path"); var util = require("../lib/6to5/util"); var path = require("path"); var repl = require("repl"); var to5 = require("../lib/6to5"); var vm = require("vm"); var _ = require("lodash"); commander.option("-e, --eval [script]", "evaluate script"); commander.option("-p, --print", "evaluate script and print result"); var pkg = require("../package.json"); commander.version(pkg.version); commander.usage("[options] [ -e script | script.js ] [arguments]"); commander.parse(process.argv); to5.register(); var _eval = function (code, filename) { code = to5.transform(code, { filename: filename }).code; return vm.runInThisContext(code, filename); }; if (commander.eval) { var code = to5.transform(commander.eval, { filename: "eval" }).code; var result = _eval(code, "eval"); if (commander.print) console.log(result); } else { var filenames = commander.args; if (filenames.length) { _.each(filenames, function (filename) { if (!util.isAbsolute(filename)) { filename = path.join(process.cwd(), filename); } require(require.resolve(filename)); }); } else { replStart(); } } function replStart() { repl.start({ prompt: "> ", input: process.stdin, output: process.stdout, eval: replEval, useGlobal: true }); } function replEval(code, context, filename, callback) { var err; var result; try { code = code.slice(1, -2); // remove "(" and "\n)" result = _eval(code, filename); } catch (e) { err = e; } callback(err, result); }
bin/6to5-node
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.002565458184108138, 0.0005105967866256833, 0.0001693965314188972, 0.00017665643827058375, 0.0007794939447194338 ]
{ "id": 5, "code_window": [ "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "exports.util = require(\"./util\");\n", "\n", "exports.register = function () {\n", " return require(\"./register\");\n", "};\n", "\n", "exports.polyfill = function () {\n", " require(\"./polyfill\");\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "exports.register = function (opts) {\n", " var register = require(\"./register\");\n", " if (opts != null) register(opts);\n", " return register;\n" ], "file_path": "lib/6to5/index.js", "type": "replace", "edit_start_line_idx": 6 }
(function() { var x = 1; function f() { assert.equal(x, 1); { let x = 2; assert.equal(x, 2); } assert.equal(x, 1); } f(); })();
test/fixtures/syntax/let-scoping/nested-conflict/exec.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00023614955716766417, 0.00020511093316599727, 0.00017407230916433036, 0.00020511093316599727, 0.000031038624001666903 ]