-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathextension.ts
491 lines (439 loc) · 19.2 KB
/
extension.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import TelemetryReporter from "@vscode/extension-telemetry";
import * as path from "path";
import * as vscode from "vscode";
import { AppTelemetryConfigUtility } from "../common/pp-tooling-telemetry-node";
import { vscodeExtAppInsightsResourceProvider } from "../common/telemetry-generated/telemetryConfiguration";
import { ITelemetryData } from "../common/TelemetryData";
import { CliAcquisition, ICliAcquisitionContext } from "./lib/CliAcquisition";
import { PacTerminal } from "./lib/PacTerminal";
import { PortalWebView } from "./PortalWebView";
import { ITelemetry } from "./telemetry/ITelemetry";
import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
TransportKind,
WorkspaceFolder,
} from "vscode-languageclient/node";
import { getPortalsOrgURLs, workspaceContainsPortalConfigFolder } from "../common/PortalConfigFinder";
import {
activateDebugger,
deactivateDebugger,
shouldEnableDebugger,
} from "../debugger";
import { handleFileSystemCallbacks } from "./power-pages/fileSystemCallbacks";
import { readUserSettings } from "./telemetry/localfileusersettings";
import { initializeGenerator } from "./power-pages/create/CreateCommandWrapper";
import { disposeDiagnostics } from "./power-pages/validationDiagnostics";
import { bootstrapDiff } from "./power-pages/bootstrapdiff/BootstrapDiff";
import { CopilotNotificationShown } from "../common/copilot/telemetry/telemetryConstants";
import { copilotNotificationPanel, disposeNotificationPanel } from "../common/copilot/welcome-notification/CopilotNotificationPanel";
import { COPILOT_NOTIFICATION_DISABLED } from "../common/copilot/constants";
import { oneDSLoggerWrapper } from "../common/OneDSLoggerTelemetry/oneDSLoggerWrapper";
import { OrgChangeNotifier, orgChangeEvent } from "../common/OrgChangeNotifier";
import { ActiveOrgOutput } from "./pac/PacTypes";
import { telemetryEventNames } from "./telemetry/TelemetryEventNames";
import { IArtemisAPIOrgResponse } from "../common/services/Interfaces";
import { ArtemisService } from "../common/services/ArtemisService";
import { treeView } from "../common/TreeStructure/DataMapper";
let client: LanguageClient;
let _context: vscode.ExtensionContext;
let htmlServerRunning = false;
let yamlServerRunning = false;
let _telemetry: TelemetryReporter;
export async function activate(
context: vscode.ExtensionContext
): Promise<void> {
_context = context;
// setup telemetry
const telemetryEnv =
AppTelemetryConfigUtility.createGlobalTelemetryEnvironment();
const appInsightsResource =
vscodeExtAppInsightsResourceProvider.GetAppInsightsResourceForDataBoundary(
telemetryEnv.dataBoundary
);
_telemetry = new TelemetryReporter(
context.extension.id,
context.extension.packageJSON.version,
appInsightsResource.instrumentationKey
);
context.subscriptions.push(_telemetry);
// Logging telemetry in US cluster for unauthenticated scenario
oneDSLoggerWrapper.instantiate("us");
oneDSLoggerWrapper.getLogger().traceInfo("Instantiating tree view", {
"instantiate": performance.now()
});
await treeView();
_telemetry.sendTelemetryEvent("Start", {
"pac.userId": readUserSettings().uniqueId,
});
oneDSLoggerWrapper.getLogger().traceInfo("Start", {
"pac.userId": readUserSettings().uniqueId
});
// Setup context switches
if (
vscode.env.remoteName === undefined ||
vscode.env.remoteName === "wsl"
) {
// PAC Interactive Login works when we are the UI is running on the same machine
// as the extension (i.e. NOT remote), or the remote is WSL
vscode.commands.executeCommand(
"setContext",
"pacCLI.authPanel.interactiveLoginSupported",
true
);
} else {
_context.environmentVariableCollection.replace(
"PAC_CLI_INTERACTIVE_AUTH_NOT_AVAILABLE",
"true"
);
}
// portal web view panel
_context.subscriptions.push(
vscode.commands.registerCommand(
"microsoft-powerapps-portals.preview-show",
() => {
_telemetry.sendTelemetryEvent("StartCommand", {
commandId: "microsoft-powerapps-portals.preview-show",
});
oneDSLoggerWrapper.getLogger().traceInfo("StartCommand", {
commandId: "microsoft-powerapps-portals.preview-show"
});
PortalWebView.createOrShow();
}
)
);
// registering bootstrapdiff command
_context.subscriptions.push(
vscode.commands.registerCommand('microsoft-powerapps-portals.bootstrap-diff', async () => {
_telemetry.sendTelemetryEvent("StartCommand", {
commandId: "microsoft-powerapps-portals.bootstrap-diff",
});
oneDSLoggerWrapper.getLogger().traceInfo("StartCommand", {
commandId: "microsoft-powerapps-portals.bootstrap-diff",
});
bootstrapDiff();
}
)
);
_context.subscriptions.push(
vscode.workspace.onDidOpenTextDocument(() => {
if (vscode.window.activeTextEditor === undefined) {
return;
} else if (
!isCurrentDocumentEdited() &&
PortalWebView.checkDocumentIsHTML()
) {
if (PortalWebView?.currentPanel) {
_telemetry.sendTelemetryEvent("PortalWebPagePreview", {
page: "NewPage",
});
oneDSLoggerWrapper.getLogger().traceInfo("PortalWebPagePreview", {
page: "NewPage",
});
PortalWebView?.currentPanel?._update();
}
}
})
);
_context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument(() => {
if (vscode.window.activeTextEditor === undefined) {
return;
} else if (isCurrentDocumentEdited()) {
if (PortalWebView?.currentPanel) {
_telemetry.sendTelemetryEvent("PortalWebPagePreview", {
page: "ExistingPage",
});
oneDSLoggerWrapper.getLogger().traceInfo("PortalWebPagePreview", {
page: "ExistingPage",
});
PortalWebView?.currentPanel?._update();
}
}
})
);
if (vscode.window.registerWebviewPanelSerializer) {
vscode.window.registerWebviewPanelSerializer(PortalWebView.viewType, {
async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel) {
PortalWebView.revive(webviewPanel);
},
});
}
// Add CRUD related callback subscription here
await handleFileSystemCallbacks(_context, _telemetry);
const cliContext = new CliAcquisitionContext(_context, _telemetry);
const cli = new CliAcquisition(cliContext);
const cliPath = await cli.ensureInstalled();
const pacTerminal = new PacTerminal(_context, _telemetry, cliPath);
_context.subscriptions.push(cli);
_context.subscriptions.push(pacTerminal);
const workspaceFolders =
vscode.workspace.workspaceFolders?.map(
(fl) => ({ ...fl, uri: fl.uri.fsPath } as WorkspaceFolder)
) || [];
_context.subscriptions.push(
orgChangeEvent(async (orgDetails: ActiveOrgOutput) => {
const orgID = orgDetails.OrgId;
const artemisResponse = await ArtemisService.fetchArtemisResponse(orgID, _telemetry);
if (artemisResponse !== null && artemisResponse.length > 0) {
const { geoName, geoLongName } = artemisResponse[0]?.response as unknown as IArtemisAPIOrgResponse;
oneDSLoggerWrapper.instantiate(geoName, geoLongName);
oneDSLoggerWrapper.getLogger().traceInfo(telemetryEventNames.DESKTOP_EXTENSION_INIT_CONTEXT, { ...orgDetails, orgGeo: geoName });
}
})
);
// TODO: Handle for VSCode.dev also
if (workspaceContainsPortalConfigFolder(workspaceFolders)) {
let telemetryData = '';
let listOfActivePortals = [];
try {
listOfActivePortals = getPortalsOrgURLs(workspaceFolders, _telemetry);
telemetryData = JSON.stringify(listOfActivePortals);
_telemetry.sendTelemetryEvent("VscodeDesktopUsage", { listOfActivePortals: telemetryData, countOfActivePortals: listOfActivePortals.length.toString() });
oneDSLoggerWrapper.getLogger().traceInfo("VscodeDesktopUsage", { listOfActivePortals: telemetryData, countOfActivePortals: listOfActivePortals.length.toString() });
} catch (exception) {
const exceptionError = exception as Error;
_telemetry.sendTelemetryException(exceptionError, { eventName: 'VscodeDesktopUsage' });
oneDSLoggerWrapper.getLogger().traceError(exceptionError.name, exceptionError.message, exceptionError, { eventName: 'VscodeDesktopUsage' });
}
// Init OrgChangeNotifier instance
OrgChangeNotifier.createOrgChangeNotifierInstance(pacTerminal.getWrapper());
vscode.workspace.onDidOpenTextDocument(didOpenTextDocument);
vscode.workspace.textDocuments.forEach(didOpenTextDocument);
_telemetry.sendTelemetryEvent("PowerPagesWebsiteYmlExists"); // Capture's PowerPages Users
oneDSLoggerWrapper.getLogger().traceInfo("PowerPagesWebsiteYmlExists");
vscode.commands.executeCommand('setContext', 'powerpages.websiteYmlExists', true);
initializeGenerator(_context, cliContext, _telemetry); // Showing the create command only if website.yml exists
showNotificationForCopilot(_telemetry, telemetryData, listOfActivePortals.length.toString());
}
else {
vscode.commands.executeCommand('setContext', 'powerpages.websiteYmlExists', false);
}
const workspaceFolderWatcher = vscode.workspace.onDidChangeWorkspaceFolders(handleWorkspaceFolderChange);
_context.subscriptions.push(workspaceFolderWatcher);
if (shouldEnableDebugger()) {
activateDebugger(context, _telemetry);
}
_telemetry.sendTelemetryEvent("activated");
oneDSLoggerWrapper.getLogger().traceInfo("activated");
}
export async function deactivate(): Promise<void> {
if (_telemetry) {
_telemetry.sendTelemetryEvent("End");
oneDSLoggerWrapper.getLogger().traceInfo("End");
// dispose() will flush any events not sent
// Note, while dispose() returns a promise, we don't await it so that we can unblock the rest of unloading logic
_telemetry.dispose();
}
if (client) {
await client.stop();
}
disposeDiagnostics();
deactivateDebugger();
disposeNotificationPanel();
}
function didOpenTextDocument(document: vscode.TextDocument): void {
// The debug options for the server
// --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging
const debugOptions = { execArgv: ["--nolazy", "--inspect=6009"] };
if (document.languageId === "yaml" && !yamlServerRunning) {
// The server is implemented in node
const serverModule = _context.asAbsolutePath(
path.join("dist", "yamlServer.js")
);
// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
const serverOptions: ServerOptions = {
run: { module: serverModule, transport: TransportKind.ipc },
debug: {
module: serverModule,
transport: TransportKind.ipc,
options: debugOptions,
},
};
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for yaml documents
documentSelector: [{ scheme: "file", language: "yaml" }],
synchronize: {
// Notify the server about file changes to '.clientrc files contained in the workspace
fileEvents:
vscode.workspace.createFileSystemWatcher("**/.clientrc"),
},
};
// Create the language client and start the client.
client = new LanguageClient(
"PowerappsYamlLanguageServer",
"PowerApps Yaml Language Server",
serverOptions,
clientOptions
);
// Start the client. This will also launch the server
const disposable = client.start();
if (disposable) {
yamlServerRunning = true;
_context.subscriptions.push(disposable);
}
// this is used to send yamlServer telemetry events
registerClientToReceiveNotifications(client);
} else if (document.languageId === "html" && !htmlServerRunning) {
// The server is implemented in node
const serverModule = _context.asAbsolutePath(
path.join("dist", "htmlServer.js")
);
// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
const serverOptions: ServerOptions = {
run: { module: serverModule, transport: TransportKind.ipc },
debug: {
module: serverModule,
transport: TransportKind.ipc,
options: debugOptions,
},
};
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for yaml documents
documentSelector: [{ scheme: "file", language: "html" }],
synchronize: {
// Notify the server about file changes to '.clientrc files contained in the workspace
fileEvents:
vscode.workspace.createFileSystemWatcher("**/.clientrc"),
},
};
// Create the language client and start the client.
client = new LanguageClient(
"PowerappsHtmlLanguageServer",
"PowerApps Html Language Server",
serverOptions,
clientOptions
);
// Start the client. This will also launch the server
const disposable = client.start();
if (disposable) {
htmlServerRunning = true;
_context.subscriptions.push(disposable);
}
// this is used to send HtmlServer telemetry events
registerClientToReceiveNotifications(client);
}
}
function registerClientToReceiveNotifications(client: LanguageClient) {
client.onReady().then(() => {
client.onNotification("telemetry/event", (payload: string) => {
const serverTelemetry = JSON.parse(payload) as ITelemetryData;
if (!!serverTelemetry && !!serverTelemetry.eventName) {
_telemetry.sendTelemetryEvent(
serverTelemetry.eventName,
serverTelemetry.properties,
serverTelemetry.measurements
);
oneDSLoggerWrapper.getLogger().traceInfo(
serverTelemetry.eventName,
serverTelemetry.properties,
serverTelemetry.measurements
);
}
});
});
}
function isCurrentDocumentEdited(): boolean {
const workspaceFolderExists =
vscode.workspace.workspaceFolders !== undefined;
let currentPanelExists = false;
if (PortalWebView?.currentPanel) {
currentPanelExists = true;
}
return (
workspaceFolderExists &&
currentPanelExists &&
PortalWebView.currentDocument ===
vscode?.window?.activeTextEditor?.document?.fileName
);
}
function handleWorkspaceFolderChange() {
const workspaceFolders =
vscode.workspace.workspaceFolders?.map(
(fl) => ({ ...fl, uri: fl.uri.fsPath } as WorkspaceFolder)
) || [];
if (workspaceContainsPortalConfigFolder(workspaceFolders)) {
vscode.commands.executeCommand('setContext', 'powerpages.websiteYmlExists', true);
}
else {
vscode.commands.executeCommand('setContext', 'powerpages.websiteYmlExists', false);
}
}
function showNotificationForCopilot(telemetry: TelemetryReporter, telemetryData: string, countOfActivePortals: string) {
if (vscode.workspace.getConfiguration('powerPlatform').get('experimental.copilotEnabled') === false) {
return;
}
const isCopilotNotificationDisabled = _context.globalState.get(COPILOT_NOTIFICATION_DISABLED, false);
if (!isCopilotNotificationDisabled) {
telemetry.sendTelemetryEvent(CopilotNotificationShown, { listOfOrgs: telemetryData, countOfActivePortals });
oneDSLoggerWrapper.getLogger().traceInfo(CopilotNotificationShown, { listOfOrgs: telemetryData, countOfActivePortals });
copilotNotificationPanel(_context, telemetry, telemetryData, countOfActivePortals);
}
}
// allow for DI without direct reference to vscode's d.ts file: that definintions file is being generated at VS Code runtime
class CliAcquisitionContext implements ICliAcquisitionContext {
public constructor(
private readonly _context: vscode.ExtensionContext,
private readonly _telemetry: ITelemetry
) { }
public get extensionPath(): string {
return this._context.extensionPath;
}
public get globalStorageLocalPath(): string {
return this._context.globalStorageUri.fsPath;
}
public get telemetry(): ITelemetry {
return this._telemetry;
}
showInformationMessage(message: string, ...items: string[]): void {
vscode.window.showInformationMessage(message, ...items);
}
showErrorMessage(message: string, ...items: string[]): void {
vscode.window.showErrorMessage(message, ...items);
}
showCliPreparingMessage(version: string): void {
vscode.window.showInformationMessage(
vscode.l10n.t({
message: "Preparing pac CLI (v{0})...",
args: [version],
comment: ["{0} represents the version number"]
})
);
}
showCliReadyMessage(): void {
vscode.window.showInformationMessage(
vscode.l10n.t('The pac CLI is ready for use in your VS Code terminal!'));
}
showCliInstallFailedError(err: string): void {
vscode.window.showErrorMessage(
vscode.l10n.t({
message: "Cannot install pac CLI: {0}",
args: [err],
comment: ["{0} represents the error message returned from the exception"]
})
);
}
showGeneratorInstallingMessage(version: string): void {
vscode.window.showInformationMessage(
vscode.l10n.t({
message: "Installing Power Pages generator(v{0})...",
args: [version],
comment: ["{0} represents the version number"]
}))
}
locDotnetNotInstalledOrInsufficient(): string {
return vscode.l10n.t({
message: "dotnet sdk 6.0 or greater must be installed",
comment: ["Do not translate 'dotnet' or 'sdk'"]
});
}
}