How to use extension method in storybook-root

Best JavaScript code snippet using storybook-root

extensionManagementService.ts

Source:extensionManagementService.ts Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import { Event, EventMultiplexer } from 'vs/base/common/event';6import {7 ILocalExtension, IGalleryExtension, InstallExtensionEvent, DidInstallExtensionEvent, IExtensionIdentifier, DidUninstallExtensionEvent, IReportedExtension, IGalleryMetadata, IExtensionGalleryService, InstallOptions, UninstallOptions, INSTALL_ERROR_NOT_SUPPORTED, InstallVSIXOptions8} from 'vs/platform/extensionManagement/common/extensionManagement';9import { IExtensionManagementServer, IExtensionManagementServerService, IWorkbenchExtensionManagementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement';10import { ExtensionType, isLanguagePackExtension, IExtensionManifest } from 'vs/platform/extensions/common/extensions';11import { URI } from 'vs/base/common/uri';12import { Disposable } from 'vs/base/common/lifecycle';13import { IConfigurationService } from 'vs/platform/configuration/common/configuration';14import { CancellationToken } from 'vs/base/common/cancellation';15import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';16import { localize } from 'vs/nls';17import { IProductService } from 'vs/platform/product/common/productService';18import { Schemas } from 'vs/base/common/network';19import { IDownloadService } from 'vs/platform/download/common/download';20import { flatten } from 'vs/base/common/arrays';21import { IDialogService } from 'vs/platform/dialogs/common/dialogs';22import Severity from 'vs/base/common/severity';23import { canceled } from 'vs/base/common/errors';24import { IUserDataAutoSyncEnablementService, IUserDataSyncResourceEnablementService, SyncResource } from 'vs/platform/userDataSync/common/userDataSync';25import { Promises } from 'vs/base/common/async';26import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';27import { IExtensionManifestPropertiesService } from 'vs/workbench/services/extensions/common/extensionManifestPropertiesService';28import { isWeb } from 'vs/base/common/platform';29export class ExtensionManagementService extends Disposable implements IWorkbenchExtensionManagementService {30 declare readonly _serviceBrand: undefined;31 readonly onInstallExtension: Event<InstallExtensionEvent>;32 readonly onDidInstallExtension: Event<DidInstallExtensionEvent>;33 readonly onUninstallExtension: Event<IExtensionIdentifier>;34 readonly onDidUninstallExtension: Event<DidUninstallExtensionEvent>;35 protected readonly servers: IExtensionManagementServer[] = [];36 constructor(37 @IExtensionManagementServerService protected readonly extensionManagementServerService: IExtensionManagementServerService,38 @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService,39 @IConfigurationService protected readonly configurationService: IConfigurationService,40 @IProductService protected readonly productService: IProductService,41 @IDownloadService protected readonly downloadService: IDownloadService,42 @IUserDataAutoSyncEnablementService private readonly userDataAutoSyncEnablementService: IUserDataAutoSyncEnablementService,43 @IUserDataSyncResourceEnablementService private readonly userDataSyncResourceEnablementService: IUserDataSyncResourceEnablementService,44 @IDialogService private readonly dialogService: IDialogService,45 @IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService,46 @IExtensionManifestPropertiesService private readonly extensionManifestPropertiesService: IExtensionManifestPropertiesService,47 ) {48 super();49 if (this.extensionManagementServerService.localExtensionManagementServer) {50 this.servers.push(this.extensionManagementServerService.localExtensionManagementServer);51 }52 if (this.extensionManagementServerService.remoteExtensionManagementServer) {53 this.servers.push(this.extensionManagementServerService.remoteExtensionManagementServer);54 }55 if (this.extensionManagementServerService.webExtensionManagementServer) {56 this.servers.push(this.extensionManagementServerService.webExtensionManagementServer);57 }58 this.onInstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<InstallExtensionEvent>, server) => { emitter.add(server.extensionManagementService.onInstallExtension); return emitter; }, new EventMultiplexer<InstallExtensionEvent>())).event;59 this.onDidInstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<DidInstallExtensionEvent>, server) => { emitter.add(server.extensionManagementService.onDidInstallExtension); return emitter; }, new EventMultiplexer<DidInstallExtensionEvent>())).event;60 this.onUninstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<IExtensionIdentifier>, server) => { emitter.add(server.extensionManagementService.onUninstallExtension); return emitter; }, new EventMultiplexer<IExtensionIdentifier>())).event;61 this.onDidUninstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<DidUninstallExtensionEvent>, server) => { emitter.add(server.extensionManagementService.onDidUninstallExtension); return emitter; }, new EventMultiplexer<DidUninstallExtensionEvent>())).event;62 }63 async getInstalled(type?: ExtensionType): Promise<ILocalExtension[]> {64 const result = await Promise.all(this.servers.map(({ extensionManagementService }) => extensionManagementService.getInstalled(type)));65 return flatten(result);66 }67 async uninstall(extension: ILocalExtension, options?: UninstallOptions): Promise<void> {68 const server = this.getServer(extension);69 if (!server) {70 return Promise.reject(`Invalid location ${extension.location.toString()}`);71 }72 if (this.servers.length > 1) {73 if (isLanguagePackExtension(extension.manifest)) {74 return this.uninstallEverywhere(extension);75 }76 return this.uninstallInServer(extension, server, options);77 }78 return server.extensionManagementService.uninstall(extension);79 }80 private async uninstallEverywhere(extension: ILocalExtension): Promise<void> {81 const server = this.getServer(extension);82 if (!server) {83 return Promise.reject(`Invalid location ${extension.location.toString()}`);84 }85 const promise = server.extensionManagementService.uninstall(extension);86 const otherServers: IExtensionManagementServer[] = this.servers.filter(s => s !== server);87 if (otherServers.length) {88 for (const otherServer of otherServers) {89 const installed = await otherServer.extensionManagementService.getInstalled();90 extension = installed.filter(i => !i.isBuiltin && areSameExtensions(i.identifier, extension.identifier))[0];91 if (extension) {92 await otherServer.extensionManagementService.uninstall(extension);93 }94 }95 }96 return promise;97 }98 private async uninstallInServer(extension: ILocalExtension, server: IExtensionManagementServer, options?: UninstallOptions): Promise<void> {99 if (server === this.extensionManagementServerService.localExtensionManagementServer) {100 const installedExtensions = await this.extensionManagementServerService.remoteExtensionManagementServer!.extensionManagementService.getInstalled(ExtensionType.User);101 const dependentNonUIExtensions = installedExtensions.filter(i => !this.extensionManifestPropertiesService.prefersExecuteOnUI(i.manifest)102 && i.manifest.extensionDependencies && i.manifest.extensionDependencies.some(id => areSameExtensions({ id }, extension.identifier)));103 if (dependentNonUIExtensions.length) {104 return Promise.reject(new Error(this.getDependentsErrorMessage(extension, dependentNonUIExtensions)));105 }106 }107 return server.extensionManagementService.uninstall(extension, options);108 }109 private getDependentsErrorMessage(extension: ILocalExtension, dependents: ILocalExtension[]): string {110 if (dependents.length === 1) {111 return localize('singleDependentError', "Cannot uninstall extension '{0}'. Extension '{1}' depends on this.",112 extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);113 }114 if (dependents.length === 2) {115 return localize('twoDependentsError', "Cannot uninstall extension '{0}'. Extensions '{1}' and '{2}' depend on this.",116 extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);117 }118 return localize('multipleDependentsError', "Cannot uninstall extension '{0}'. Extensions '{1}', '{2}' and others depend on this.",119 extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);120 }121 async reinstallFromGallery(extension: ILocalExtension): Promise<void> {122 const server = this.getServer(extension);123 if (server) {124 await this.checkForWorkspaceTrust(extension.manifest);125 return server.extensionManagementService.reinstallFromGallery(extension);126 }127 return Promise.reject(`Invalid location ${extension.location.toString()}`);128 }129 updateMetadata(extension: ILocalExtension, metadata: IGalleryMetadata): Promise<ILocalExtension> {130 const server = this.getServer(extension);131 if (server) {132 return server.extensionManagementService.updateMetadata(extension, metadata);133 }134 return Promise.reject(`Invalid location ${extension.location.toString()}`);135 }136 updateExtensionScope(extension: ILocalExtension, isMachineScoped: boolean): Promise<ILocalExtension> {137 const server = this.getServer(extension);138 if (server) {139 return server.extensionManagementService.updateExtensionScope(extension, isMachineScoped);140 }141 return Promise.reject(`Invalid location ${extension.location.toString()}`);142 }143 zip(extension: ILocalExtension): Promise<URI> {144 const server = this.getServer(extension);145 if (server) {146 return server.extensionManagementService.zip(extension);147 }148 return Promise.reject(`Invalid location ${extension.location.toString()}`);149 }150 unzip(zipLocation: URI): Promise<IExtensionIdentifier> {151 return Promises.settled(this.servers152 // Filter out web server153 .filter(server => server !== this.extensionManagementServerService.webExtensionManagementServer)154 .map(({ extensionManagementService }) => extensionManagementService.unzip(zipLocation))).then(([extensionIdentifier]) => extensionIdentifier);155 }156 async install(vsix: URI, options?: InstallVSIXOptions): Promise<ILocalExtension> {157 if (this.extensionManagementServerService.localExtensionManagementServer && this.extensionManagementServerService.remoteExtensionManagementServer) {158 const manifest = await this.getManifest(vsix);159 if (isLanguagePackExtension(manifest)) {160 // Install on both servers161 const [local] = await Promises.settled([this.extensionManagementServerService.localExtensionManagementServer, this.extensionManagementServerService.remoteExtensionManagementServer].map(server => this.installVSIX(vsix, server, options)));162 return local;163 }164 if (this.extensionManifestPropertiesService.prefersExecuteOnUI(manifest)) {165 // Install only on local server166 return this.installVSIX(vsix, this.extensionManagementServerService.localExtensionManagementServer, options);167 }168 // Install only on remote server169 return this.installVSIX(vsix, this.extensionManagementServerService.remoteExtensionManagementServer, options);170 }171 if (this.extensionManagementServerService.localExtensionManagementServer) {172 return this.installVSIX(vsix, this.extensionManagementServerService.localExtensionManagementServer, options);173 }174 if (this.extensionManagementServerService.remoteExtensionManagementServer) {175 return this.installVSIX(vsix, this.extensionManagementServerService.remoteExtensionManagementServer, options);176 }177 return Promise.reject('No Servers to Install');178 }179 protected async installVSIX(vsix: URI, server: IExtensionManagementServer, options: InstallVSIXOptions | undefined): Promise<ILocalExtension> {180 const manifest = await this.getManifest(vsix);181 if (manifest) {182 await this.checkForWorkspaceTrust(manifest);183 return server.extensionManagementService.install(vsix, options);184 }185 return Promise.reject('Unable to get the extension manifest.');186 }187 getManifest(vsix: URI): Promise<IExtensionManifest> {188 if (vsix.scheme === Schemas.file && this.extensionManagementServerService.localExtensionManagementServer) {189 return this.extensionManagementServerService.localExtensionManagementServer.extensionManagementService.getManifest(vsix);190 }191 if (vsix.scheme === Schemas.vscodeRemote && this.extensionManagementServerService.remoteExtensionManagementServer) {192 return this.extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService.getManifest(vsix);193 }194 return Promise.reject('No Servers');195 }196 async canInstall(gallery: IGalleryExtension): Promise<boolean> {197 for (const server of this.servers) {198 if (await server.extensionManagementService.canInstall(gallery)) {199 return true;200 }201 }202 return false;203 }204 async updateFromGallery(gallery: IGalleryExtension, extension: ILocalExtension): Promise<ILocalExtension> {205 const server = this.getServer(extension);206 if (!server) {207 return Promise.reject(`Invalid location ${extension.location.toString()}`);208 }209 const servers: IExtensionManagementServer[] = [];210 // Update Language pack on local and remote servers211 if (isLanguagePackExtension(extension.manifest)) {212 servers.push(...this.servers.filter(server => server !== this.extensionManagementServerService.webExtensionManagementServer));213 } else {214 servers.push(server);215 }216 return Promises.settled(servers.map(server => server.extensionManagementService.installFromGallery(gallery))).then(([local]) => local);217 }218 async installExtensions(extensions: IGalleryExtension[], installOptions?: InstallOptions): Promise<ILocalExtension[]> {219 if (!installOptions) {220 const isMachineScoped = await this.hasToFlagExtensionsMachineScoped(extensions);221 installOptions = { isMachineScoped, isBuiltin: false };222 }223 return Promises.settled(extensions.map(extension => this.installFromGallery(extension, installOptions)));224 }225 async installFromGallery(gallery: IGalleryExtension, installOptions?: InstallOptions): Promise<ILocalExtension> {226 const manifest = await this.extensionGalleryService.getManifest(gallery, CancellationToken.None);227 if (!manifest) {228 return Promise.reject(localize('Manifest is not found', "Installing Extension {0} failed: Manifest is not found.", gallery.displayName || gallery.name));229 }230 const servers: IExtensionManagementServer[] = [];231 // Install Language pack on local and remote servers232 if (isLanguagePackExtension(manifest)) {233 servers.push(...this.servers.filter(server => server !== this.extensionManagementServerService.webExtensionManagementServer));234 } else {235 const server = this.getExtensionManagementServerToInstall(manifest);236 if (server) {237 servers.push(server);238 }239 }240 if (servers.length) {241 if (!installOptions) {242 const isMachineScoped = await this.hasToFlagExtensionsMachineScoped([gallery]);243 installOptions = { isMachineScoped, isBuiltin: false };244 }245 if (!installOptions.isMachineScoped && this.isExtensionsSyncEnabled()) {246 if (this.extensionManagementServerService.localExtensionManagementServer && !servers.includes(this.extensionManagementServerService.localExtensionManagementServer)) {247 servers.push(this.extensionManagementServerService.localExtensionManagementServer);248 }249 }250 await this.checkForWorkspaceTrust(manifest);251 return Promises.settled(servers.map(server => server.extensionManagementService.installFromGallery(gallery, installOptions))).then(([local]) => local);252 }253 const error = new Error(localize('cannot be installed', "Cannot install the '{0}' extension because it is not available in this setup.", gallery.displayName || gallery.name));254 error.name = INSTALL_ERROR_NOT_SUPPORTED;255 return Promise.reject(error);256 }257 getExtensionManagementServerToInstall(manifest: IExtensionManifest): IExtensionManagementServer | null {258 // Only local server259 if (this.servers.length === 1 && this.extensionManagementServerService.localExtensionManagementServer) {260 return this.extensionManagementServerService.localExtensionManagementServer;261 }262 const extensionKind = this.extensionManifestPropertiesService.getExtensionKind(manifest);263 for (const kind of extensionKind) {264 if (kind === 'ui' && this.extensionManagementServerService.localExtensionManagementServer) {265 return this.extensionManagementServerService.localExtensionManagementServer;266 }267 if (kind === 'workspace' && this.extensionManagementServerService.remoteExtensionManagementServer) {268 return this.extensionManagementServerService.remoteExtensionManagementServer;269 }270 if (kind === 'web' && this.extensionManagementServerService.webExtensionManagementServer) {271 return this.extensionManagementServerService.webExtensionManagementServer;272 }273 }274 // NOTE@coder: Fall back to installing on the remote server on web.275 if (isWeb && this.extensionManagementServerService.remoteExtensionManagementServer) {276 return this.extensionManagementServerService.remoteExtensionManagementServer;277 }278 279 // Local server can accept any extension. So return local server if not compatible server found.280 return this.extensionManagementServerService.localExtensionManagementServer;281 }282 private isExtensionsSyncEnabled(): boolean {283 return this.userDataAutoSyncEnablementService.isEnabled() && this.userDataSyncResourceEnablementService.isResourceEnabled(SyncResource.Extensions);284 }285 private async hasToFlagExtensionsMachineScoped(extensions: IGalleryExtension[]): Promise<boolean> {286 if (this.isExtensionsSyncEnabled()) {287 const result = await this.dialogService.show(288 Severity.Info,289 extensions.length === 1 ? localize('install extension', "Install Extension") : localize('install extensions', "Install Extensions"),290 [291 localize('install', "Install"),292 localize('install and do no sync', "Install (Do not sync)"),293 localize('cancel', "Cancel"),294 ],295 {296 cancelId: 2,297 detail: extensions.length === 1298 ? localize('install single extension', "Would you like to install and synchronize '{0}' extension across your devices?", extensions[0].displayName)299 : localize('install multiple extensions', "Would you like to install and synchronize extensions across your devices?")300 }301 );302 switch (result.choice) {303 case 0:304 return false;305 case 1:306 return true;307 }308 throw canceled();309 }310 return false;311 }312 getExtensionsReport(): Promise<IReportedExtension[]> {313 if (this.extensionManagementServerService.localExtensionManagementServer) {314 return this.extensionManagementServerService.localExtensionManagementServer.extensionManagementService.getExtensionsReport();315 }316 if (this.extensionManagementServerService.remoteExtensionManagementServer) {317 return this.extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService.getExtensionsReport();318 }319 return Promise.resolve([]);320 }321 private getServer(extension: ILocalExtension): IExtensionManagementServer | null {322 return this.extensionManagementServerService.getExtensionManagementServer(extension);323 }324 protected async checkForWorkspaceTrust(manifest: IExtensionManifest): Promise<void> {325 if (this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(manifest) === false) {326 const trustState = await this.workspaceTrustRequestService.requestWorkspaceTrust({327 message: localize('extensionInstallWorkspaceTrustMessage', "Enabling this extension requires a trusted workspace."),328 buttons: [329 { label: localize('extensionInstallWorkspaceTrustButton', "Trust Workspace & Install"), type: 'ContinueWithTrust' },330 { label: localize('extensionInstallWorkspaceTrustContinueButton', "Install"), type: 'ContinueWithoutTrust' },331 { label: localize('extensionInstallWorkspaceTrustManageButton', "Learn More"), type: 'Manage' }332 ]333 });334 if (trustState === undefined) {335 return Promise.reject(canceled());336 }337 }338 return Promise.resolve();339 }...

Full Screen

Full Screen

extensionService.test.ts

Source:extensionService.test.ts Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import * as assert from 'assert';6import { ExtensionService as BrowserExtensionService } from 'vs/workbench/services/extensions/browser/extensionService';7import { ExtensionRunningLocation, ExtensionRunningPreference } from 'vs/workbench/services/extensions/common/abstractExtensionService';8suite('BrowserExtensionService', () => {9 test('pickRunningLocation', () => {10 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation([], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);11 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation([], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.None);12 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation([], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);13 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation([], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.None);14 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);15 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);16 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);17 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);18 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);19 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);20 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);21 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);22 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);23 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.None);24 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);25 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);26 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);27 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);28 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);29 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);30 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);31 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);32 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);33 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);34 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);35 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);36 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);37 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);38 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);39 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);40 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);41 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);42 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);43 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);44 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);45 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);46 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);47 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);48 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);49 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);50 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web', 'workspace'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);51 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web', 'workspace'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);52 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web', 'workspace'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);53 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'web', 'workspace'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);54 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace', 'web'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);55 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace', 'web'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);56 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace', 'web'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);57 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['ui', 'workspace', 'web'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);58 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui', 'workspace'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);59 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui', 'workspace'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);60 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui', 'workspace'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);61 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'ui', 'workspace'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);62 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace', 'ui'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);63 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace', 'ui'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);64 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace', 'ui'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);65 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['web', 'workspace', 'ui'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);66 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui', 'web'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);67 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui', 'web'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);68 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui', 'web'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);69 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'ui', 'web'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);70 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web', 'ui'], false, false, ExtensionRunningPreference.None), ExtensionRunningLocation.None);71 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web', 'ui'], false, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);72 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web', 'ui'], true, false, ExtensionRunningPreference.None), ExtensionRunningLocation.LocalWebWorker);73 assert.deepStrictEqual(BrowserExtensionService.pickRunningLocation(['workspace', 'web', 'ui'], true, true, ExtensionRunningPreference.None), ExtensionRunningLocation.Remote);74 });...

Full Screen

Full Screen

extension_dict.py

Source:extension_dict.py Github

copy

Full Screen

1# Protocol Buffers - Google's data interchange format2# Copyright 2008 Google Inc. All rights reserved.3# https://developers.google.com/protocol-buffers/4#5# Redistribution and use in source and binary forms, with or without6# modification, are permitted provided that the following conditions are7# met:8#9# * Redistributions of source code must retain the above copyright10# notice, this list of conditions and the following disclaimer.11# * Redistributions in binary form must reproduce the above12# copyright notice, this list of conditions and the following disclaimer13# in the documentation and/or other materials provided with the14# distribution.15# * Neither the name of Google Inc. nor the names of its16# contributors may be used to endorse or promote products derived from17# this software without specific prior written permission.18#19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.30"""Contains _ExtensionDict class to represent extensions.31"""32from google.protobuf.internal import type_checkers33from google.protobuf.descriptor import FieldDescriptor34def _VerifyExtensionHandle(message, extension_handle):35 """Verify that the given extension handle is valid."""36 if not isinstance(extension_handle, FieldDescriptor):37 raise KeyError('HasExtension() expects an extension handle, got: %s' %38 extension_handle)39 if not extension_handle.is_extension:40 raise KeyError('"%s" is not an extension.' % extension_handle.full_name)41 if not extension_handle.containing_type:42 raise KeyError('"%s" is missing a containing_type.'43 % extension_handle.full_name)44 if extension_handle.containing_type is not message.DESCRIPTOR:45 raise KeyError('Extension "%s" extends message type "%s", but this '46 'message is of type "%s".' %47 (extension_handle.full_name,48 extension_handle.containing_type.full_name,49 message.DESCRIPTOR.full_name))50# TODO(robinson): Unify error handling of "unknown extension" crap.51# TODO(robinson): Support iteritems()-style iteration over all52# extensions with the "has" bits turned on?53class _ExtensionDict(object):54 """Dict-like container for Extension fields on proto instances.55 Note that in all cases we expect extension handles to be56 FieldDescriptors.57 """58 def __init__(self, extended_message):59 """60 Args:61 extended_message: Message instance for which we are the Extensions dict.62 """63 self._extended_message = extended_message64 def __getitem__(self, extension_handle):65 """Returns the current value of the given extension handle."""66 _VerifyExtensionHandle(self._extended_message, extension_handle)67 result = self._extended_message._fields.get(extension_handle)68 if result is not None:69 return result70 if extension_handle.label == FieldDescriptor.LABEL_REPEATED:71 result = extension_handle._default_constructor(self._extended_message)72 elif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:73 message_type = extension_handle.message_type74 if not hasattr(message_type, '_concrete_class'):75 # pylint: disable=protected-access76 self._extended_message._FACTORY.GetPrototype(message_type)77 assert getattr(extension_handle.message_type, '_concrete_class', None), (78 'Uninitialized concrete class found for field %r (message type %r)'79 % (extension_handle.full_name,80 extension_handle.message_type.full_name))81 result = extension_handle.message_type._concrete_class()82 try:83 result._SetListener(self._extended_message._listener_for_children)84 except ReferenceError:85 pass86 else:87 # Singular scalar -- just return the default without inserting into the88 # dict.89 return extension_handle.default_value90 # Atomically check if another thread has preempted us and, if not, swap91 # in the new object we just created. If someone has preempted us, we92 # take that object and discard ours.93 # WARNING: We are relying on setdefault() being atomic. This is true94 # in CPython but we haven't investigated others. This warning appears95 # in several other locations in this file.96 result = self._extended_message._fields.setdefault(97 extension_handle, result)98 return result99 def __eq__(self, other):100 if not isinstance(other, self.__class__):101 return False102 my_fields = self._extended_message.ListFields()103 other_fields = other._extended_message.ListFields()104 # Get rid of non-extension fields.105 my_fields = [field for field in my_fields if field.is_extension]106 other_fields = [field for field in other_fields if field.is_extension]107 return my_fields == other_fields108 def __ne__(self, other):109 return not self == other110 def __len__(self):111 fields = self._extended_message.ListFields()112 # Get rid of non-extension fields.113 extension_fields = [field for field in fields if field[0].is_extension]114 return len(extension_fields)115 def __hash__(self):116 raise TypeError('unhashable object')117 # Note that this is only meaningful for non-repeated, scalar extension118 # fields. Note also that we may have to call _Modified() when we do119 # successfully set a field this way, to set any necessary "has" bits in the120 # ancestors of the extended message.121 def __setitem__(self, extension_handle, value):122 """If extension_handle specifies a non-repeated, scalar extension123 field, sets the value of that field.124 """125 _VerifyExtensionHandle(self._extended_message, extension_handle)126 if (extension_handle.label == FieldDescriptor.LABEL_REPEATED or127 extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE):128 raise TypeError(129 'Cannot assign to extension "%s" because it is a repeated or '130 'composite type.' % extension_handle.full_name)131 # It's slightly wasteful to lookup the type checker each time,132 # but we expect this to be a vanishingly uncommon case anyway.133 type_checker = type_checkers.GetTypeChecker(extension_handle)134 # pylint: disable=protected-access135 self._extended_message._fields[extension_handle] = (136 type_checker.CheckValue(value))137 self._extended_message._Modified()138 def __delitem__(self, extension_handle):139 self._extended_message.ClearExtension(extension_handle)140 def _FindExtensionByName(self, name):141 """Tries to find a known extension with the specified name.142 Args:143 name: Extension full name.144 Returns:145 Extension field descriptor.146 """147 return self._extended_message._extensions_by_name.get(name, None)148 def _FindExtensionByNumber(self, number):149 """Tries to find a known extension with the field number.150 Args:151 number: Extension field number.152 Returns:153 Extension field descriptor.154 """155 return self._extended_message._extensions_by_number.get(number, None)156 def __iter__(self):157 # Return a generator over the populated extension fields158 return (f[0] for f in self._extended_message.ListFields()159 if f[0].is_extension)160 def __contains__(self, extension_handle):161 _VerifyExtensionHandle(self._extended_message, extension_handle)162 if extension_handle not in self._extended_message._fields:163 return False164 if extension_handle.label == FieldDescriptor.LABEL_REPEATED:165 return bool(self._extended_message._fields.get(extension_handle))166 if extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:167 value = self._extended_message._fields.get(extension_handle)168 # pylint: disable=protected-access169 return value is not None and value._is_present_in_parent...

Full Screen

Full Screen

ExtensionManager.test.js

Source:ExtensionManager.test.js Github

copy

Full Screen

1import { Exception } from 'handlebars';2import ExtensionManager from './ExtensionManager.js';3import MODULE_TYPES from './MODULE_TYPES.js';4import log from './../log.js';5jest.mock('./../log.js');6describe('ExtensionManager.js', () => {7 let extensionManager, commandsManager, servicesManager, appConfig;8 beforeEach(() => {9 commandsManager = {10 createContext: jest.fn(),11 getContext: jest.fn(),12 registerCommand: jest.fn(),13 };14 servicesManager = {15 registerService: jest.fn(),16 };17 appConfig = {18 testing: true,19 };20 extensionManager = new ExtensionManager({21 servicesManager,22 commandsManager,23 appConfig,24 });25 log.warn.mockClear();26 jest.clearAllMocks();27 });28 it('creates a module namespace for each module type', () => {29 const moduleKeys = Object.keys(extensionManager.modules);30 const moduleTypeValues = Object.values(MODULE_TYPES);31 expect(moduleKeys.sort()).toEqual(moduleTypeValues.sort());32 });33 describe('registerExtensions()', () => {34 it('calls registerExtension() for each extension', () => {35 extensionManager.registerExtension = jest.fn();36 // SUT37 const fakeExtensions = [{ one: '1' }, { two: '2' }, { three: '3 ' }];38 extensionManager.registerExtensions(fakeExtensions);39 // Assert40 expect(extensionManager.registerExtension.mock.calls.length).toBe(3);41 });42 it('calls registerExtension() for each extension passing its configuration if tuple', () => {43 const fakeConfiguration = { testing: true };44 extensionManager.registerExtension = jest.fn();45 // SUT46 const fakeExtensions = [47 { one: '1' },48 [{ two: '2' }, fakeConfiguration],49 { three: '3 ' },50 ];51 extensionManager.registerExtensions(fakeExtensions);52 // Assert53 expect(extensionManager.registerExtension.mock.calls[1][1]).toEqual(54 fakeConfiguration55 );56 });57 });58 describe('registerExtension()', () => {59 it('calls preRegistration() for extension', () => {60 // SUT61 const fakeExtension = { one: '1', preRegistration: jest.fn() };62 extensionManager.registerExtension(fakeExtension);63 // Assert64 expect(fakeExtension.preRegistration.mock.calls.length).toBe(1);65 });66 it('calls preRegistration() passing dependencies and extension configuration to extension', () => {67 const extensionConfiguration = { config: 'Some configuration' };68 // SUT69 const extension = { one: '1', preRegistration: jest.fn() };70 extensionManager.registerExtension(extension, extensionConfiguration);71 // Assert72 expect(extension.preRegistration.mock.calls[0][0]).toEqual({73 servicesManager,74 commandsManager,75 appConfig,76 configuration: extensionConfiguration,77 });78 });79 it('logs a warning if the extension is null or undefined', () => {80 const undefinedExtension = undefined;81 const nullExtension = null;82 extensionManager.registerExtension(undefinedExtension);83 extensionManager.registerExtension(nullExtension);84 expect(log.warn.mock.calls.length).toBe(2);85 });86 it('logs a warning if the extension does not have an id', () => {87 const extensionWithoutId = {};88 extensionManager.registerExtension(extensionWithoutId);89 expect(log.warn.mock.calls.length).toBe(1);90 });91 it('tracks which extensions have been registered', () => {92 const extension = {93 id: 'hello-world',94 };95 extensionManager.registerExtension(extension);96 expect(extensionManager.registeredExtensionIds).toContain(extension.id);97 });98 it('logs a warning if the extension has an id that has already been registered', () => {99 const extension = { id: 'hello-world' };100 extensionManager.registerExtension(extension);101 // SUT102 extensionManager.registerExtension(extension);103 expect(log.warn.mock.calls.length).toBe(1);104 });105 it('logs a warning if a defined module returns null or undefined', () => {106 const extensionWithBadModule = {107 id: 'hello-world',108 getViewportModule: () => {109 return null;110 },111 };112 extensionManager.registerExtension(extensionWithBadModule);113 expect(log.warn.mock.calls.length).toBe(1);114 expect(log.warn.mock.calls[0][0]).toContain(115 'Null or undefined returned when registering'116 );117 });118 it('logs an error if an exception is thrown while retrieving a module', () => {119 const extensionWithBadModule = {120 id: 'hello-world',121 getViewportModule: () => {122 throw new Exception('Hello World');123 },124 };125 extensionManager.registerExtension(extensionWithBadModule);126 expect(log.error.mock.calls.length).toBe(1);127 expect(log.error.mock.calls[0][0]).toContain(128 'Exception thrown while trying to call'129 );130 });131 it('successfully passes dependencies to each module along with extension configuration', () => {132 const extensionConfiguration = { testing: true };133 const extension = {134 id: 'hello-world',135 getViewportModule: jest.fn(),136 getSopClassHandlerModule: jest.fn(),137 getPanelModule: jest.fn(),138 getToolbarModule: jest.fn(),139 getCommandsModule: jest.fn(),140 };141 extensionManager.registerExtension(extension, extensionConfiguration);142 Object.keys(extension).forEach(module => {143 if (typeof extension[module] === 'function') {144 expect(extension[module].mock.calls[0][0]).toEqual({145 servicesManager,146 commandsManager,147 appConfig,148 configuration: extensionConfiguration,149 api: undefined,150 extensionManager,151 });152 }153 });154 });155 it('successfully registers a module for each module type', () => {156 const extension = {157 id: 'hello-world',158 getViewportModule: () => {159 return {};160 },161 getSopClassHandlerModule: () => {162 return {};163 },164 getPanelModule: () => {165 return {};166 },167 getToolbarModule: () => {168 return {};169 },170 getCommandsModule: () => {171 return {};172 },173 };174 extensionManager.registerExtension(extension);175 // Registers 1 module per module type176 Object.keys(extensionManager.modules).forEach(moduleType => {177 const modulesForType = extensionManager.modules[moduleType];178 expect(modulesForType.length).toBe(1);179 });180 });181 it('calls commandsManager.registerCommand for each commandsModule command definition', () => {182 const extension = {183 id: 'hello-world',184 getCommandsModule: () => {185 return {186 definitions: {187 exampleDefinition: {188 commandFn: () => {},189 storeContexts: [],190 options: {},191 },192 },193 };194 },195 };196 // SUT197 extensionManager.registerExtension(extension);198 expect(commandsManager.registerCommand.mock.calls.length).toBe(1);199 });200 it('logs a warning if the commandsModule contains no command definitions', () => {201 const extension = {202 id: 'hello-world',203 getCommandsModule: () => {204 return {};205 },206 };207 // SUT208 extensionManager.registerExtension(extension);209 expect(log.warn.mock.calls.length).toBe(1);210 expect(log.warn.mock.calls[0][0]).toContain(211 'Commands Module contains no command definitions'212 );213 });214 });...

Full Screen

Full Screen

extensionsUtil.ts

Source:extensionsUtil.ts Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import { IConfigurationService } from 'vs/platform/configuration/common/configuration';6import { IExtensionManifest, ExtensionKind, ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';7import { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry';8import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';9import { isNonEmptyArray } from 'vs/base/common/arrays';10import { IProductService } from 'vs/platform/product/common/productService';11export class ExtensionKindController2 {12 constructor(13 @IProductService private readonly productService: IProductService,14 @IConfigurationService private readonly configurationService: IConfigurationService,15 ) {16 }17 prefersExecuteOnUI(manifest: IExtensionManifest): boolean {18 const extensionKind = this.getExtensionKind(manifest);19 return (extensionKind.length > 0 && extensionKind[0] === 'ui');20 }21 prefersExecuteOnWorkspace(manifest: IExtensionManifest): boolean {22 const extensionKind = this.getExtensionKind(manifest);23 return (extensionKind.length > 0 && extensionKind[0] === 'workspace');24 }25 prefersExecuteOnWeb(manifest: IExtensionManifest): boolean {26 const extensionKind = this.getExtensionKind(manifest);27 return (extensionKind.length > 0 && extensionKind[0] === 'web');28 }29 canExecuteOnUI(manifest: IExtensionManifest): boolean {30 const extensionKind = this.getExtensionKind(manifest);31 return extensionKind.some(kind => kind === 'ui');32 }33 canExecuteOnWorkspace(manifest: IExtensionManifest): boolean {34 const extensionKind = this.getExtensionKind(manifest);35 return extensionKind.some(kind => kind === 'workspace');36 }37 canExecuteOnWeb(manifest: IExtensionManifest): boolean {38 const extensionKind = this.getExtensionKind(manifest);39 return extensionKind.some(kind => kind === 'web');40 }41 getExtensionKind(manifest: IExtensionManifest): ExtensionKind[] {42 // check in config43 let result = getConfiguredExtensionKind(manifest, this.configurationService);44 if (typeof result !== 'undefined') {45 return toArray(result);46 }47 // check product.json48 result = getProductExtensionKind(manifest, this.productService);49 if (typeof result !== 'undefined') {50 return result;51 }52 // check the manifest itself53 result = manifest.extensionKind;54 if (typeof result !== 'undefined') {55 return toArray(result);56 }57 return deduceExtensionKind(manifest);58 }59}60export function deduceExtensionKind(manifest: IExtensionManifest): ExtensionKind[] {61 // Not an UI extension if it has main62 if (manifest.main) {63 if (manifest.browser) {64 return ['workspace', 'web'];65 }66 return ['workspace'];67 }68 if (manifest.browser) {69 return ['web'];70 }71 // Not an UI nor web extension if it has dependencies or an extension pack72 if (isNonEmptyArray(manifest.extensionDependencies) || isNonEmptyArray(manifest.extensionPack)) {73 return ['workspace'];74 }75 if (manifest.contributes) {76 // Not an UI nor web extension if it has no ui contributions77 for (const contribution of Object.keys(manifest.contributes)) {78 if (!isUIExtensionPoint(contribution)) {79 return ['workspace'];80 }81 }82 }83 return ['ui', 'workspace', 'web'];84}85let _uiExtensionPoints: Set<string> | null = null;86function isUIExtensionPoint(extensionPoint: string): boolean {87 if (_uiExtensionPoints === null) {88 const uiExtensionPoints = new Set<string>();89 ExtensionsRegistry.getExtensionPoints().filter(e => e.defaultExtensionKind !== 'workspace').forEach(e => {90 uiExtensionPoints.add(e.name);91 });92 _uiExtensionPoints = uiExtensionPoints;93 }94 return _uiExtensionPoints.has(extensionPoint);95}96let _productExtensionKindsMap: Map<string, ExtensionKind[]> | null = null;97function getProductExtensionKind(manifest: IExtensionManifest, productService: IProductService): ExtensionKind[] | undefined {98 if (_productExtensionKindsMap === null) {99 const productExtensionKindsMap = new Map<string, ExtensionKind[]>();100 if (productService.extensionKind) {101 for (const id of Object.keys(productService.extensionKind)) {102 productExtensionKindsMap.set(ExtensionIdentifier.toKey(id), productService.extensionKind[id]);103 }104 }105 _productExtensionKindsMap = productExtensionKindsMap;106 }107 const extensionId = getGalleryExtensionId(manifest.publisher, manifest.name);108 return _productExtensionKindsMap.get(ExtensionIdentifier.toKey(extensionId));109}110let _configuredExtensionKindsMap: Map<string, ExtensionKind | ExtensionKind[]> | null = null;111function getConfiguredExtensionKind(manifest: IExtensionManifest, configurationService: IConfigurationService): ExtensionKind | ExtensionKind[] | undefined {112 if (_configuredExtensionKindsMap === null) {113 const configuredExtensionKindsMap = new Map<string, ExtensionKind | ExtensionKind[]>();114 const configuredExtensionKinds = configurationService.getValue<{ [key: string]: ExtensionKind | ExtensionKind[] }>('remote.extensionKind') || {};115 for (const id of Object.keys(configuredExtensionKinds)) {116 configuredExtensionKindsMap.set(ExtensionIdentifier.toKey(id), configuredExtensionKinds[id]);117 }118 _configuredExtensionKindsMap = configuredExtensionKindsMap;119 }120 const extensionId = getGalleryExtensionId(manifest.publisher, manifest.name);121 return _configuredExtensionKindsMap.get(ExtensionIdentifier.toKey(extensionId));122}123function toArray(extensionKind: ExtensionKind | ExtensionKind[]): ExtensionKind[] {124 if (Array.isArray(extensionKind)) {125 return extensionKind;126 }127 return extensionKind === 'ui' ? ['ui', 'workspace'] : [extensionKind];...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/**2 * 2007-2019 PrestaShop and Contributors3 *4 * NOTICE OF LICENSE5 *6 * This source file is subject to the Open Software License (OSL 3.0)7 * that is bundled with this package in the file LICENSE.txt.8 * It is also available through the world-wide-web at this URL:9 * https://opensource.org/licenses/OSL-3.010 * If you did not receive a copy of the license and are unable to11 * obtain it through the world-wide-web, please send an email12 * to license@prestashop.com so we can send you a copy immediately.13 *14 * DISCLAIMER15 *16 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer17 * versions in the future. If you wish to customize PrestaShop for your18 * needs please refer to https://www.prestashop.com for more information.19 *20 * @author PrestaShop SA <contact@prestashop.com>21 * @copyright 2007-2019 PrestaShop SA and Contributors22 * @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)23 * International Registered Trademark & Property of PrestaShop SA24 */25import Grid from '../../components/grid/grid';26import SortingExtension from '../../components/grid/extension/sorting-extension';27import SubmitRowActionExtension from '../../components/grid/extension/action/row/submit-row-action-extension';28import FiltersResetExtension from '../../components/grid/extension/filters-reset-extension';29import ReloadListActionExtension from '../../components/grid/extension/reload-list-extension';30import ExportToSqlManagerExtension from '../../components/grid/extension/export-to-sql-manager-extension';31import LinkRowActionExtension from '../../components/grid/extension/link-row-action-extension';32import SubmitBulkExtension from '../../components/grid/extension/submit-bulk-action-extension';33import BulkActionCheckboxExtension from '../../components/grid/extension/bulk-action-checkbox-extension';34import ColumnTogglingExtension from '../../components/grid/extension/column-toggling-extension';35import PositionExtension from '../../components/grid/extension/position-extension';36import ChoiceTree from '../../components/form/choice-tree';37import TranslatableInput from '../../components/translatable-input';38import textToLinkRewriteCopier from '../../components/text-to-link-rewrite-copier';39import TaggableField from '../../components/taggable-field';40import ShowcaseCard from '../../components/showcase-card/showcase-card';41import ShowcaseCardCloseExtension from '../../components/showcase-card/extension/showcase-card-close-extension';42const $ = window.$;43$(() => {44 const cmsCategory = new Grid('cms_page_category');45 cmsCategory.addExtension(new ReloadListActionExtension());46 cmsCategory.addExtension(new ExportToSqlManagerExtension());47 cmsCategory.addExtension(new FiltersResetExtension());48 cmsCategory.addExtension(new SortingExtension());49 cmsCategory.addExtension(new LinkRowActionExtension());50 cmsCategory.addExtension(new SubmitBulkExtension());51 cmsCategory.addExtension(new BulkActionCheckboxExtension());52 cmsCategory.addExtension(new SubmitRowActionExtension());53 cmsCategory.addExtension(new ColumnTogglingExtension());54 cmsCategory.addExtension(new PositionExtension());55 const translatorInput = new TranslatableInput();56 textToLinkRewriteCopier({57 sourceElementSelector: 'input[name^="cms_page_category[name]"]',58 destinationElementSelector: `${translatorInput.localeInputSelector}:not(.d-none) input[name^="cms_page_category[friendly_url]"]`,59 });60 new ChoiceTree('#cms_page_category_parent_category');61 const shopChoiceTree = new ChoiceTree('#cms_page_category_shop_association');62 shopChoiceTree.enableAutoCheckChildren();63 new TaggableField({64 tokenFieldSelector: 'input[name^="cms_page_category[meta_keywords]"]',65 options: {66 createTokensOnBlur: true,67 },68 });69 const cmsGrid = new Grid('cms_page');70 cmsGrid.addExtension(new ReloadListActionExtension());71 cmsGrid.addExtension(new ExportToSqlManagerExtension());72 cmsGrid.addExtension(new FiltersResetExtension());73 cmsGrid.addExtension(new SortingExtension());74 cmsGrid.addExtension(new ColumnTogglingExtension());75 cmsGrid.addExtension(new BulkActionCheckboxExtension());76 cmsGrid.addExtension(new SubmitBulkExtension());77 cmsGrid.addExtension(new SubmitRowActionExtension());78 cmsGrid.addExtension(new PositionExtension());79 cmsGrid.addExtension(new LinkRowActionExtension());80 const helperBlock = new ShowcaseCard('cms-pages-showcase-card');81 helperBlock.addExtension(new ShowcaseCardCloseExtension());...

Full Screen

Full Screen

check_url.py

Source:check_url.py Github

copy

Full Screen

1import re2from urllib import robotparser3def check_media(url):4 extension = url[-4:].lower()5 if extension == '.jpg' or extension == '.png' or extension == '.gif' \6 or extension == '.svg' or extension == '.pdf' or extension == '.doc' \7 or extension == '.ppt' or extension == '.mp3' or extension == '.mp4' \8 or extension == '.zip' or extension == '.aac' or extension == '.wav' \9 or extension == '.wma' or extension == '.bmp' or extension == '.avi' \10 or extension == '.mkv' or extension == '.mov' or extension == '.flv' \11 or extension == '.xls' or extension == '.rtf' or extension == '-mp3':12 return True13 extension = url[-5:].lower()14 if extension == '.jpeg' or extension == '.tiff' or extension == '.pptx' \15 or extension == '.docs' or extension == '.xlsx' or extension == '.webm' \16 or extension == '.djvu':17 return True18 return False19def check_response(response):20 flag_type = False21 flag_lang = False22 if 'Content-Type' in response.headers:23 content_type = response.headers['Content-Type']24 else:25 return False26 if content_type is None or re.match('html|text', content_type):27 flag_type = True28 if flag_type:29 return True30 else:31 return False32def check_robot(scheme, domain, url):33 rp = robotparser.RobotFileParser()34 rp.set_url(scheme + "://" + domain + "/robots.txt")35 try:36 rp.read()37 except:38 return False39 return rp.can_fetch('*', url)40def test():41 pass42if __name__ == '__main__':...

Full Screen

Full Screen

0001_setup_extensions.py

Source:0001_setup_extensions.py Github

copy

Full Screen

1from unittest import mock2from django.db import connection, migrations3try:4 from django.contrib.postgres.operations import (5 BloomExtension, BtreeGinExtension, BtreeGistExtension, CITextExtension,6 CreateExtension, CryptoExtension, HStoreExtension, TrigramExtension,7 UnaccentExtension,8 )9except ImportError:10 BloomExtension = mock.Mock()11 BtreeGinExtension = mock.Mock()12 BtreeGistExtension = mock.Mock()13 CITextExtension = mock.Mock()14 CreateExtension = mock.Mock()15 HStoreExtension = mock.Mock()16 TrigramExtension = mock.Mock()17 UnaccentExtension = mock.Mock()18 needs_crypto_extension = False19else:20 needs_crypto_extension = (21 connection.vendor == 'postgresql' and22 not connection.features.is_postgresql_1323 )24class Migration(migrations.Migration):25 operations = [26 BloomExtension(),27 BtreeGinExtension(),28 BtreeGistExtension(),29 CITextExtension(),30 # Ensure CreateExtension quotes extension names by creating one with a31 # dash in its name.32 CreateExtension('uuid-ossp'),33 # CryptoExtension is required for RandomUUID() on PostgreSQL < 13.34 CryptoExtension() if needs_crypto_extension else mock.Mock(),35 HStoreExtension(),36 TrigramExtension(),37 UnaccentExtension(),...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withRootDecorator } from 'storybook-root-decorator';2import { withKnobs } from '@storybook/addon-knobs';3import { withA11y } from '@storybook/addon-a11y';4];5export const parameters = {6 options: {7 storySort: {8 },9 },10};11import { withRootDecorator } from 'storybook-root-decorator';12import { withKnobs } from '@storybook/addon-knobs';13import { withA11y } from '@storybook/addon-a11y';14];15export const parameters = {16 options: {17 storySort: {18 },19 },20};21MIT © [dangvanthanh](

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { withRootDecorator } from 'storybook-root-decorator';3import { storiesOf } from '@storybook/react';4import { action } from '@storybook/addon-actions';5import { Button } from '@storybook/react/demo';6import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';7storiesOf('Button', module)8 .addDecorator(withRootDecorator())9 .add('with text', () => (10 <Button onClick={action('clicked')}>Hello Button</Button>11 .add('with some emoji', () => (12 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>13 ));14MIT © [ashishkumarshrestha](

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from '@storybook/react';2import { withRootDecorator } from 'storybook-root-decorator';3import { withKnobs } from '@storybook/addon-knobs';4import { withA11y } from '@storybook/addon-a11y';5addDecorator(withRootDecorator);6addDecorator(withKnobs);7addDecorator(withA11y);8import { addParameters } from '@storybook/react';9import { muiTheme } from 'storybook-addon-material-ui';10import { createMuiTheme } from '@material-ui/core/styles';11const theme = createMuiTheme({12 palette: {13 primary: {14 },15 secondary: {16 },17 },18});19addParameters({20});21import { withThemesProvider } from 'storybook-addon-styled-component-theme';22import { ThemeProvider } from 'styled-components';23import { theme as defaultTheme } from '../src/theme';24import { theme as darkTheme } from '../src/theme/dark';25const themes = [defaultTheme, darkTheme];26addDecorator(withThemesProvider(themes));27addDecorator((storyFn) => (28 <ThemeProvider theme={defaultTheme}>{storyFn()}</ThemeProvider>29));30import { addParameters } from '@storybook/react';31import { muiTheme } from 'storybook-addon-material-ui';32import { createMuiTheme } from '@material-ui/core/styles';33const theme = createMuiTheme({34 palette: {35 primary: {36 },37 secondary: {38 },39 },40});41addParameters({42});43import { withThemesProvider } from 'storybook-addon-styled-component-theme';44import { ThemeProvider } from 'styled-components';45import { theme as defaultTheme } from '../src/theme';46import { theme as darkTheme } from '../src/theme/dark';47const themes = [defaultTheme, darkTheme];48addDecorator(withThemesProvider(themes));49addDecorator((storyFn) => (50 <ThemeProvider theme={defaultTheme}>{storyFn()}</ThemeProvider>51));

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configure } from '@storybook/react';2import { setOptions } from '@storybook/addon-options';3import { setAddon } from '@storybook/react';4import infoAddon from '@storybook/addon-info';5import { withInfo } from '@storybook/addon-info';6import { addDecorator } from '@storybook/react';7import { withRoot } from './storybook-root';8addDecorator(withRoot);9setAddon(infoAddon);10addDecorator(11 withInfo({12 styles: {13 header: {14 h1: {15 },16 body: {17 },18 h2: {19 },20 },21 infoBody: {22 },23 },24 info: {25 },26 })27);28setOptions({

Full Screen

Using AI Code Generation

copy

Full Screen

1require('storybook-root-require')(__dirname);2module.exports = {3};4import React from 'react';5import { storiesOf } from '@storybook/react';6import { action } from '@storybook/addon-actions';7import Button from 'components/Button';8storiesOf('Button', module)9 .add('with text', () => <Button onClick={action('clicked')}>Hello Button</Button>)10 .add('with some emoji', () => (11 <Button onClick={action('clicked')}>12 ));13| [@storybook/addon-actions](

Full Screen

Using AI Code Generation

copy

Full Screen

1var path = require('path');2var rootPath = path.resolve(__dirname, '../');3require('storybook-root')(rootPath);4const path = require('path');5const rootPath = path.resolve(__dirname, '../');6const storybookRootPath = path.resolve(__dirname, '../node_modules/storybook-root');7module.exports = {8 module: {9 {10 query: {11 }12 }13 }14};15{16}17import { configure } from '@storybook/react';18function loadStories() {19 require('../stories/index.js');20}21configure(loadStories, module);22import { storiesOf } from '@storybook/react';23import React from 'react';24import { Hello } from 'components/hello';25storiesOf('Hello', module)26 .add('with default text', () => (27 .add('with custom text', () => (28 ));29import React from 'react';30export const Hello = (props) => {31 return (32 <h1>Hello {props.text}!</h1>33 );34};35Hello.defaultProps = {36};

Full Screen

Using AI Code Generation

copy

Full Screen

1const rootConfig = require('storybook-root-config');2module.exports = rootConfig({3 {4 options: {5 },6 },7});8module.exports = {9};10import React from 'react';11import { storiesOf } from '@storybook/react';12import { jsxDecorator } from 'storybook-addon-jsx';13storiesOf('Button', module)14 .addDecorator(jsxDecorator)15 .add('with text', () => <Button>Hello Button</Button>);16import React from 'react';17import { storiesOf } from '@storybook/react';18import { jsxDecorator } from 'storybook-addon-jsx';19import { withKnobs, text } from '@storybook/addon-knobs';20storiesOf('Button', module)21 .addDecorator(jsxDecorator)22 .addDecorator(withKnobs)23 .add('with text', () => <Button>{text('Label', 'Hello Button')}</Button>);24| enableBeautify | `true` | Enable [js-beautify](

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful