generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcopilot-webview.ts
More file actions
659 lines (523 loc) · 18.8 KB
/
copilot-webview.ts
File metadata and controls
659 lines (523 loc) · 18.8 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/**
* Copyright © 2022-2024, Oracle and/or its affiliates.
* This software is licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl.
*/
import { readFileSync } from "fs";
import * as vscode from 'vscode';
import path = require("path");
import { filter, firstValueFrom, from, iif, of, switchMap, tap } from "rxjs";
import { timeout as apiTimeout } from "../api";
import { callOpenAPIConversionApiAndShowDocument, openAPIConvertCallback } from "../commands/convert-openapi-document";
import { callPostmanConversionApiAndShowDocument, postmanConvertCallback } from "../commands/convert-postman-collection";
import { log } from "../logger";
import { fs, message, workspace } from '../utils';
import { detectIsADDValidRemote } from "../utils-api";
import { showErrorMessage, showInfoMessage } from "../utils/ui-utils";
import { OpenAPINS, PostmanNs, RabAddNs, SharedNs } from "../webview-shared-lib";
import { getAddFile } from "../workspace-manager";
export namespace UtilsNs {
export let panel: vscode.WebviewPanel | undefined;
const webFolder = `webview-helper`;
export const showWebview = (context: vscode.ExtensionContext) => {
if (!panel) {
panel = initWebview(context);
}
panel.reveal();
};
export const initWebview = (context: vscode.ExtensionContext) => {
if (panel) {
return panel;
}
const { extensionPath, extensionUri } = context;
const webroot = vscode.Uri.joinPath(extensionUri, webFolder);
// Create and show a new webview
panel = vscode.window.createWebviewPanel(
SharedNs.ExtensionCommandEnum.openCopilotAssistant, // Identifies the type of the webview. Used internally
'Oracle RAB', // Title of the panel displayed to the user
vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
{
enableScripts: true,
localResourceRoots: [
webroot
]
}
);
// And set its HTML content
// panel.webview.html = getWebviewContent(context, panel.webview);
let server = fs.serveStaticServer();
server.on('listening', () => {
if (!panel) {
showErrorMessage("❌ The webview panel is gone");
return;
}
panel.webview.html = getWebviewContentV2ForStaticIframe(context, panel.webview);
});
panel.onDidDispose(() => {
panel = undefined;
server.close();
server = undefined as any;
});
return panel;
};
const getStaticResourceUrl = (webview: vscode.Webview, extensionPath: vscode.Uri, fileName: string) => {
return webview.asWebviewUri(vscode.Uri.joinPath(extensionPath, webFolder, fileName));
};
function getWebviewContentV2ForStaticIframe(context: vscode.ExtensionContext, webview: vscode.Webview) {
let indexHtml = readFileSync(
path.resolve(
__dirname,
`..`,
`webview-helper`,
`index.html`
)
).toString().replace(/__WEBVIEW_URL__/, fs.WEBVIEW_URL);
const jsUrl = getStaticResourceUrl(webview, context.extensionUri, `index.js`);
const replace = [
[
/ src=".+?\.js">/,
` src="${jsUrl}">`
],
];
for (let entry of replace) {
indexHtml = indexHtml.replace(
entry[0],
//@ts-ignore
entry[1]
);
}
return indexHtml;
}
function getWebviewContent(context: vscode.ExtensionContext, webview: vscode.Webview) {
const webRootPath = path.join(context.extensionPath, webFolder);
// ext.readJson
const manifestJson = require(path.join(webRootPath, 'asset-manifest.json'));
let staticHtml = readFileSync(path.join(webRootPath, 'index.html')).toString();
const reactJsMainPath = manifestJson.files['main.js'];
const reactCssMainPath = manifestJson.files['main.css'];
const jsUrl = getStaticResourceUrl(webview, context.extensionUri, reactJsMainPath);
const replace = [
[
/ src=".+?\.js">/,
` src="${jsUrl}">`
],
];
if (reactCssMainPath) {
const cssUrl = getStaticResourceUrl(webview, context.extensionUri, reactCssMainPath);
replace.push(
[
/ href=".+?\.css" /,
` href="${cssUrl}" `
],
);
}
for (let entry of replace) {
staticHtml = staticHtml.replace(
entry[0],
//@ts-ignore
entry[1]
);
}
// console.log(staticHtml);
return staticHtml;
}
export const listenWebview = <T extends keyof typeof SharedNs.WebviewCommandEnum>(onCommand: T, callback: (payload: SharedNs.WebviewCommandPayload[T]) => any) => {
if (!panel) { return; }
return panel.webview.onDidReceiveMessage(
({
target,
command,
payload
}: {
target: 'vscode' | 'webview', command: T, payload: SharedNs.WebviewCommandPayload[T]
} = {} as any) => {
if (target !== 'vscode') {
return;
}
if (command === onCommand) {
callback(payload);
}
}
);
};
export const notifyWebview = <T extends keyof typeof SharedNs.ExtensionCommandEnum>(command: T, payload: SharedNs.VscodeCommandPayload[T]) => {
if (panel) {
panel.webview.postMessage({
target: 'webview',
command: command,
payload
});
}
};
const registryMap: Map<keyof typeof SharedNs.ExtensionCommandEnum, vscode.Disposable[]> = new Map();
export const registerCommandV2 = <T extends keyof typeof SharedNs.ExtensionCommandEnum>({
context,
command,
callback,
}: {
context: vscode.ExtensionContext;
command: T;
callback: (payload: SharedNs.VscodeCommandPayload[T]) => vscode.Disposable[]
}) => {
return vscode.commands.registerCommand(command, (...args) => {
const callBackSet = registryMap.get(command) ?? [];
callBackSet.forEach(disposable => disposable.dispose());
registryMap.set(command, callback?.(args[0] as any));
});
};
}
function handleWebviewRouting(href: SharedNs.WebviewRouteEnum) {
UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.routerNavigateTo, {
href
});
return UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.webviewRouterReady, (...args) => {
UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.routerNavigateTo, {
href
});
});
}
function handleWebviewLifecycle() {
return UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.webviewLifecycle, (payload) => {
if (payload.type === 'close') {
UtilsNs.panel!.dispose();
UtilsNs.panel = undefined;
}
});
}
const notifyPostmanWebview = (file: vscode.Uri, entryType: SharedNs.VscodeCommandPayload["updateEntryType"]) => {
UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.updatePostmanRawData, {
postman: JSON.parse(readFileSync(file.fsPath, 'utf8')) as PostmanNs.Root
});
UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.updateEntryType, entryType);
};
const notifyOpenAPIWebview = ({
openAPIFile,
addFile,
entryType
}: {
openAPIFile: vscode.Uri,
addFile?: vscode.Uri,
entryType: SharedNs.VscodeCommandPayload["updateEntryType"]
}) => {
let openAPIDoc: OpenAPINS.Root;
try {
openAPIDoc = JSON.parse(readFileSync(openAPIFile.fsPath, 'utf8'));
} catch (error) {
log.error(`Unable to parse OpenAPI document`, error);
return;
}
let ADD: RabAddNs.Root | undefined = undefined;
try {
if (addFile) {
ADD = JSON.parse(readFileSync(addFile.fsPath, 'utf8'));
}
} catch (error) {
log.error(`Unable to parse adapter definition document`, error);
return;
}
UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.updateOpenAPIRawData, {
openapi: openAPIDoc,
add: ADD
});
UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.updateEntryType, entryType);
};
const openWebview = ({
file,
context,
entryType,
addFile
}: {
file: vscode.Uri,
context: vscode.ExtensionContext,
entryType: SharedNs.VscodeCommandPayload["updateEntryType"];
addFile?: vscode.Uri,
}) => {
const isPostmanEvents = [
SharedNs.VscodeCommandPayloadEntryType.PostmanAddRequest,
SharedNs.VscodeCommandPayloadEntryType.PostmanConvertDocument,
].some(type => type === entryType);
const postmanEvents = () => [
handleWebviewRouting(SharedNs.WebviewRouteEnum.PostmanAdd),
handleWebviewLifecycle(),
notifyPostmanWebview(file, entryType),
UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.postmanSelectReady, () => notifyPostmanWebview(file, entryType)),
UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.postmanSelectRequests, (data) => {
const observable = fs.checkWorkspaceInitialized().pipe(
switchMap(
() => workspace.detectIsPostmanFileWithUILoading(context, file, () => of(file)
.pipe(
switchMap(() => callPostmanConversionApiAndShowDocument(file, data, addFile,))
)
)
)
);
const requestPromise = firstValueFrom(observable);
message.loading(
{
message: `Updating in progress. This may take 5-${apiTimeout} seconds. Don't edit the document before it's done.`,
hidePromise: requestPromise,
context,
isBlocking: false
}
);
}),
UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.postmanDoneConvertDocument, (data) => {
postmanConvertCallback(file, context, data);
})
];
const openAPIEvents = () => [
handleWebviewRouting(SharedNs.WebviewRouteEnum.OpenAPIAdd),
handleWebviewLifecycle(),
notifyOpenAPIWebview({
openAPIFile: file,
entryType,
addFile
}),
UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.openAPISelectReady, () => notifyOpenAPIWebview({
openAPIFile: file,
entryType,
addFile
}
)),
UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.openAPISelectRequests, (data) => {
const observable = fs.checkWorkspaceInitialized().pipe(
switchMap(
() => workspace.detectIsOpenAPIFileWithUILoading(context, file, () => of(file)
.pipe(
switchMap(() => callOpenAPIConversionApiAndShowDocument(file, data, addFile,))
)
)
)
);
const requestPromise = firstValueFrom(observable);
message.loading(
{
message: `Updating in progress. This may take 5-${apiTimeout} seconds. Don't edit the document before it's done.`,
hidePromise: requestPromise,
context,
isBlocking: false
}
);
}),
UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.openAPIDoneConvertDocument, (data) => {
openAPIConvertCallback(file, context, data);
})
];
const entryEvents = isPostmanEvents ? postmanEvents() : openAPIEvents();
return from([
...entryEvents,
]);
};
const registerPostmanConvertCallback = (context: vscode.ExtensionContext, entryType: SharedNs.VscodeCommandPayload["updateEntryType"]) => (file: vscode.Uri) => {
const disposableList: vscode.Disposable[] = [];
const observable = of(entryType).pipe(
switchMap(
() => iif(
() => entryType === SharedNs.VscodeCommandPayloadEntryType.PostmanAddRequest,
detectIsADDValidRemote(),
fs.checkWorkspaceInitialized()
)
),
switchMap(
() => workspace.detectIsPostmanFile(file, () => of(file)
.pipe(
tap(() => UtilsNs.showWebview(context)),
tap(() => showInfoMessage(
entryType === SharedNs.VscodeCommandPayloadEntryType.PostmanAddRequest ?
"Select the requests from the Postman collection to add"
: "Select the requests from the Postman collection to convert"
)),
switchMap(
() => openWebview(
{
file, context, entryType,
addFile: entryType === SharedNs.VscodeCommandPayloadEntryType.PostmanAddRequest ? getAddFile() : undefined
}
)
.pipe(
filter(disposible => !!disposible),
tap(disposable => disposableList.push(disposable!))
)
)
)
)
)
);
observable.subscribe();
return disposableList;
};
const registerOpenAPIConvertCallback = (context: vscode.ExtensionContext, entryType: SharedNs.VscodeCommandPayload["updateEntryType"]) => (file: vscode.Uri) => {
const disposableList: vscode.Disposable[] = [];
const observable = of(entryType).pipe(
switchMap(
() => iif(
() => entryType === SharedNs.VscodeCommandPayloadEntryType.OpenAPIAddRequest,
detectIsADDValidRemote(),
fs.checkWorkspaceInitialized()
)
),
switchMap(
() => workspace.detectIsOpenAPIFile(file, () => of(file)
.pipe(
tap(() => UtilsNs.showWebview(context)),
tap(() => showInfoMessage(
entryType === SharedNs.VscodeCommandPayloadEntryType.OpenAPIAddRequest ?
"Select the OpenAPI paths and methods to add"
: "Select the OpenAPI paths and methods to convert"
)),
switchMap(
() => openWebview({
file, context, entryType,
addFile: entryType === SharedNs.VscodeCommandPayloadEntryType.OpenAPIAddRequest ? getAddFile() : undefined
})
.pipe(
filter(disposible => !!disposible),
tap(disposable => disposableList.push(disposable!))
)
)
)
)
)
);
observable.subscribe();
return disposableList;
};
function registerPostmanConvertAddRequests(context: vscode.ExtensionContext) {
context.subscriptions.push(
UtilsNs.registerCommandV2({
context,
command: SharedNs.ExtensionCommandEnum.openCopilotPostmanConvert,
callback: registerPostmanConvertCallback(context, SharedNs.VscodeCommandPayloadEntryType.PostmanAddRequest)
})
);
}
function registerPostmanConvertConvertDocument(context: vscode.ExtensionContext) {
context.subscriptions.push(
UtilsNs.registerCommandV2({
context,
command: SharedNs.ExtensionCommandEnum.openPostmanConvertConverDocument,
callback: registerPostmanConvertCallback(context, SharedNs.VscodeCommandPayloadEntryType.PostmanConvertDocument)
})
);
}
function registerOpenAPIConvertAppendDocument(context: vscode.ExtensionContext) {
context.subscriptions.push(
UtilsNs.registerCommandV2({
context,
command: SharedNs.ExtensionCommandEnum.openOpenAPIConvertAppendDocument,
callback: registerOpenAPIConvertCallback(context, SharedNs.VscodeCommandPayloadEntryType.OpenAPIAddRequest)
})
);
}
function registerOpenAPIConvertNewDocument(context: vscode.ExtensionContext) {
context.subscriptions.push(
UtilsNs.registerCommandV2({
context,
command: SharedNs.ExtensionCommandEnum.openOpenAPIConvertNewDocument,
callback: registerOpenAPIConvertCallback(context, SharedNs.VscodeCommandPayloadEntryType.OpenAPIConvertDocument)
})
);
}
function moveCursor(props: {
editor: vscode.TextEditor,
} & SharedNs.VsCoderEditorConfig) {
const { editor, documentString, startTextPattern, endTextPattern, startOffset = 0, endOffset = 0 } = props;
const position = editor.selection.active;
const startLine = documentString.split('\n').map((lineText, lineNumber) => ([lineNumber, lineText,])).find(entry => `${entry[1]}`.match(startTextPattern));
if (startLine) {
let endLine;
if (endTextPattern) {
endLine = documentString.split('\n').map((lineText, lineNumber) => ([lineNumber, lineText,])).find(entry => entry[0] >= startLine[0] && `${entry[1]}`.match(endTextPattern));
}
var startPosition = position.with(startLine[0] as number + startOffset, 0);
const endLineNumber = endLine?.[0] ? +endLine[0] : +startLine[0];
var endPosition = position.with(endLineNumber + endOffset, 0);
var newSelection = new vscode.Selection(startPosition, endPosition);
editor.selection = newSelection;
editor.revealRange(editor.selection);
}
}
// const rabAddReady = () => {
// workspace.openADDDocument().pipe(
// tap((document) => {
// const addDoc = JSON.parse(document.getText());
// UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.loadRabAddData, addDoc);
// })
// );
// };
// const updatedAddDocFromWebviewV2 = (context: vscode.ExtensionContext, data: SharedNs.WebviewCommandPayloadRabAddSave) => workspace.showADDDocument().pipe(
// tap(
// (editor) => {
// let source = editor.document.getText();
// let range = new vscode.Range(editor.document.positionAt(0), editor.document.positionAt(source.length));
// editor.edit(edit => {
// const updatedAddDoc = SharedNs.ADDJsonStringify(data.addToSave);
// edit.replace(range, updatedAddDoc);
// setTimeout(() => {
// if (data.vsCodeEditorConfig) {
// moveCursor(
// {
// editor,
// ...data.vsCodeEditorConfig
// }
// );
// }
// }, 500);
// }).then(ret => {
// setTimeout(() => {
// vscode.commands.executeCommand('orab.explorer.outline.refresh');
// }, 1000);
// });
// }
// ),
// );
// const initCopilotEvents = (context: vscode.ExtensionContext) => from([
// UtilsNs.showWebview(context),
// handleWebviewRouting(SharedNs.WebviewRouteEnum.Root),
// handleWebviewLifecycle(),
// rabAddReady(),
// UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.rabAddReady, rabAddReady),
// UtilsNs.listenWebview(SharedNs.WebviewCommandEnum.rabAddSave, (data) => {
// workspace.createRabAddFileIfNotExist(
// {
// callback:
// (addFile) => from(
// vscode.workspace.openTextDocument(addFile)
// )
// }
// )
// .pipe(
// tap((document) => {
// const addDoc = JSON.parse(document.getText());
// UtilsNs.notifyWebview(SharedNs.ExtensionCommandEnum.loadRabAddData, addDoc);
// })
// )
// .subscribe();
// updatedAddDocFromWebviewV2(context, data)
// .subscribe();
// }),
// ]);
// const registerCopilotAssistantCallback = (context: vscode.ExtensionContext) => () => {
// const disposableList: vscode.Disposable[] = [];
// const observable = initCopilotEvents(context).pipe(
// filter(disposible => !!disposible),
// tap(disposable => disposableList.push(disposable!))
// );
// observable.subscribe();
// return disposableList;
// };
// function registerCopilotAssistant(context: vscode.ExtensionContext) {
// context.subscriptions.push(
// UtilsNs.registerCommandV2({
// context,
// command: SharedNs.ExtensionCommandEnum.openCopilotAssistant,
// callback: registerCopilotAssistantCallback(context)
// })
// );
// }
export function register(context: vscode.ExtensionContext) {
registerPostmanConvertAddRequests(context);
registerPostmanConvertConvertDocument(context);
registerOpenAPIConvertAppendDocument(context);
registerOpenAPIConvertNewDocument(context);
// registerCopilotAssistant(context);
}