forked from intersystems-community/vscode-objectscript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
869 lines (806 loc) · 29.9 KB
/
index.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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
import path = require("path");
import { exec } from "child_process";
import * as vscode from "vscode";
import { lt } from "semver";
import {
config,
schemas,
workspaceState,
terminals,
extensionContext,
lsExtensionId,
OBJECTSCRIPT_FILE_SCHEMA,
documentContentProvider,
filesystemSchemas,
} from "../extension";
import { getCategory } from "../commands/export";
import { isCSPFile } from "../providers/FileSystemProvider/FileSystemProvider";
import { AtelierAPI } from "../api";
export const outputChannel = vscode.window.createOutputChannel("ObjectScript", "vscode-objectscript-output");
/**
* A map of all CSP web apps in a server-namespace.
* The key is either `serverName:ns`, or `host:port/pathPrefix:ns`, lowercase.
* The value is an array of CSP apps as returned by GET %25SYS/cspapps.
*/
export const cspApps: Map<string, string[]> = new Map();
/**
* A map of all Studio Abstract Document extensions in a server-namespace.
* The key is either `serverName:ns`, or `host:port/pathPrefix:ns`, lowercase.
* The value is lowercase array of file extensions, without the dot.
*/
export const otherDocExts: Map<string, string[]> = new Map();
/**
* The URI strings for all documents that are open in a custom editor.
*/
export const openCustomEditors: string[] = [];
/**
* Array of stringified `Uri`s that have been exported.
* Used by the documentIndex to determine if a created/changed
* file needs to be synced with the server. If the documentIndex
* finds a match in this array, the element is then removed.
*/
export const exportedUris: string[] = [];
/**
* Return a string represenattion of `error`.
* If `error` is `undefined`, returns the empty string.
*/
export function stringifyError(error): string {
try {
return (
error == undefined
? ""
: error.errorText
? <string>error.errorText
: typeof error == "string"
? error
: error instanceof Error
? error.toString()
: JSON.stringify(error)
).trim();
} catch {
// Need to catch errors from JSON.stringify()
return "";
}
}
/** The last error string written to the Output channel */
let lastErrorStr = "";
/**
* Stringify `error` and append it to the Output channel, followed by line feed character.
* Doesn't append `error` if it's a duplicate of the last error appended, or if it's
* stringified value is the empty string. If `message` is defined, calls
* `vscode.window.showErrorMessage()` with that message plus a reminder to check
* the Output channel, if an error was appended to it.
*/
export function handleError(error, message?: string): void {
if (!error) return;
const errorStr = stringifyError(error);
if (errorStr.length) {
if (errorStr != lastErrorStr) {
lastErrorStr = errorStr;
outputChannel.appendLine(errorStr);
}
outputChannel.show(true);
if (message) message += " Check the 'ObjectScript' Output channel for details.";
}
if (message) vscode.window.showErrorMessage(message, "Dismiss");
}
export function outputConsole(data: string[]): void {
data.forEach((line): void => {
outputChannel.appendLine(line);
});
}
export interface CurrentFile {
name: string;
fileName: string;
uri: vscode.Uri;
unredirectedUri?: vscode.Uri;
workspaceFolder: string;
uniqueId: string;
}
export interface CurrentTextFile extends CurrentFile {
content: string;
eol: vscode.EndOfLine;
}
export interface CurrentBinaryFile extends CurrentFile {
content: Buffer;
}
/**
* For workspace roots in the local filesystem, configName is the root's name
* which defaults to the folder name, and apiTarget is the same.
* For isfs roots, configName is the uri.authority (i.e. isfs://this-bit/...)
* which is normally the server name as looked up in intersystems.servers, and
* apiTarget is the uri.
*/
export interface ConnectionTarget {
apiTarget: string | vscode.Uri;
configName: string;
}
/** Get a list of all CSP web apps in the server-namespace that `uri` is connected to. */
export function cspAppsForUri(uri: vscode.Uri): string[] {
return cspAppsForApi(new AtelierAPI(uri));
}
/** Get a list of all CSP web apps in the server-namespace that `api` is connected to. */
export function cspAppsForApi(api: AtelierAPI): string[] {
return (
cspApps.get(
(api.config.serverName && api.config.serverName != ""
? `${api.config.serverName}:${api.config.ns}`
: `${api.config.host}:${api.config.port}${api.config.pathPrefix}:${api.config.ns}`
).toLowerCase()
) ?? []
);
}
/**
* Get a list of Studio Abstract Document extensions in the server-namespace that `uri` is connected to.
*/
function otherDocExtsForUri(uri: vscode.Uri): string[] {
const api = new AtelierAPI(uri);
return otherDocExts.get(`${api.serverId}:${api.config.ns}`.toLowerCase()) ?? [];
}
/** Determine the server name of a non-`isfs` non-ObjectScript file (any file that's not CLS,MAC,INT,INC). */
export function getServerDocName(uri: vscode.Uri): string {
const wsFolder = vscode.workspace.getWorkspaceFolder(uri);
if (!wsFolder) return;
const cspIdx = uri.path.lastIndexOf(cspAppsForUri(uri).find((cspApp) => uri.path.includes(cspApp + "/")));
if (cspIdx != -1) {
return uri.path.slice(cspIdx);
} else if (uri.path.toLowerCase().endsWith(".dfi")) {
// Determine the file path relative to the workspace folder path
const wsPath = wsFolder.uri.path + wsFolder.uri.path.endsWith("/") ? "" : "/";
const relativeFilePath = uri.path.startsWith(wsPath) ? uri.path.slice(wsPath.length) : "";
if (relativeFilePath == "") return;
// Check for matching export settings first. If no match, use base name.
const config = vscode.workspace.getConfiguration("objectscript.export", uri);
const folder: string = config.get("folder");
const addCategory: boolean = config.get("addCategory");
let root = [
typeof folder == "string" && folder.length ? folder : null,
addCategory ? getCategory(uri.fsPath, addCategory) : null,
]
.filter(notNull)
.join("/")
.replace(/\\/g, "/");
if (!root.endsWith("/")) root += "/";
if (relativeFilePath.startsWith(root)) {
// Convert any folders into "-"
return relativeFilePath.slice(root.length).replace(/\//g, "-");
} else {
// Use the last part of the path since it didn't match the export settings
return uri.path.split("/").pop();
}
} else {
// Use the last part of the path without checking the export settings
return uri.path.split("/").pop();
}
}
/**
* Determine if this non-ObjectScript local file is importable.
* @param uri The file to check.
*/
export function isImportableLocalFile(uri: vscode.Uri): boolean {
// A non-class or routine file is only importable
// if it's in a web application folder or it's a
// known Studio abstract document type within a workspace folder
if (!vscode.workspace.getWorkspaceFolder(uri)) return false;
return (
cspAppsForUri(uri).some((cspApp) => uri.path.includes(cspApp + "/")) ||
otherDocExtsForUri(uri).includes(uri.path.split(".").pop().toLowerCase())
);
}
/** A regex for extracting the name of a class from its content */
export const classNameRegex = /^[ \t]*Class[ \t]+(%?[\p{L}\d\u{100}-\u{ffff}]+(?:\.[\p{L}\d\u{100}-\u{ffff}]+)+)/imu;
/** A regex for extracting the name and type of a routine from its content */
export const routineNameTypeRegex = /^ROUTINE ([^\s]+)(?:\s*\[\s*Type\s*=\s*\b([a-z]{3})\b)?/i;
export function currentFileFromContent(uri: vscode.Uri, content: string | Buffer): CurrentTextFile | CurrentBinaryFile {
const fileName = uri.fsPath;
const workspaceFolder = workspaceFolderOfUri(uri);
if (!workspaceFolder) {
// No workspace folders are open
return null;
}
const fileExt = fileName.split(".").pop().toLowerCase();
if (
notIsfs(uri) &&
!["cls", "mac", "int", "inc"].includes(fileExt) &&
// This is a non-class or routine local file, so check if we can import it
!isImportableLocalFile(uri)
) {
return null;
}
let name = "";
let ext = "";
if (fileExt === "cls" && typeof content === "string") {
// Allow Unicode letters
const match = content.match(classNameRegex);
if (match) {
[, name, ext = "cls"] = match;
}
} else if (fileExt.match(/(mac|int|inc)/i) && typeof content === "string") {
const match = content.match(routineNameTypeRegex);
if (match) {
[, name, ext = "mac"] = match;
}
} else {
if (notIsfs(uri)) {
name = getServerDocName(uri);
} else {
name = uri.path;
}
// Need to strip leading / for custom Studio documents which should not be treated as files.
// e.g. For a custom Studio document Test.ZPM, the variable name would be /Test.ZPM which is
// not the document name. The document name is Test.ZPM so requests made to the Atelier APIs
// using the name with the leading / would fail to find the document.
if (name?.charAt(0) == "/") {
name = name.slice(1);
}
}
if (!name) {
return null;
}
name += ext ? "." + ext.toLowerCase() : "";
if (typeof content === "string") {
const firstLF = content.indexOf("\n");
return {
content,
fileName,
uri,
workspaceFolder,
name,
uniqueId: `${workspaceFolder}:${name}`,
eol: firstLF > 0 && content[firstLF - 1] === "\r" ? vscode.EndOfLine.CRLF : vscode.EndOfLine.LF,
};
} else {
return {
content,
fileName,
uri,
workspaceFolder,
name,
uniqueId: `${workspaceFolder}:${name}`,
};
}
}
export function currentFile(document?: vscode.TextDocument): CurrentTextFile {
document =
document ||
(vscode.window.activeTextEditor && vscode.window.activeTextEditor.document
? vscode.window.activeTextEditor.document
: null);
if (!document) {
return null;
}
const fileName = document.fileName;
const fileExt = fileName.split(".").pop().toLowerCase();
if (
notIsfs(document.uri) &&
!["cls", "mac", "int", "inc"].includes(fileExt) &&
// This is a non-class or routine local file, so check if we can import it
!isImportableLocalFile(document.uri)
) {
return null;
}
const eol = document.eol || vscode.EndOfLine.LF;
const uri = redirectDotvscodeRoot(document.uri);
const content = document.getText();
let name = "";
let ext = "";
if (fileExt === "cls") {
// Allow Unicode letters
const match = content.match(classNameRegex);
if (match) {
[, name, ext = "cls"] = match;
}
} else if (fileExt.match(/(mac|int|inc)/i)) {
const match = content.match(routineNameTypeRegex);
if (match) {
[, name, ext = "mac"] = match;
}
} else {
if (notIsfs(document.uri)) {
name = getServerDocName(document.uri);
} else {
name = uri.path;
}
// Need to strip leading / for custom Studio documents which should not be treated as files.
// e.g. For a custom Studio document Test.ZPM, the variable name would be /Test.ZPM which is
// not the document name. The document name is Test.ZPM so requests made to the Atelier APIs
// using the name with the leading / would fail to find the document.
if (name?.charAt(0) == "/") {
name = name.slice(1);
}
}
if (!name) {
return null;
}
name += ext ? "." + ext.toLowerCase() : "";
const workspaceFolder = currentWorkspaceFolder(document);
const uniqueId = `${workspaceFolder}:${name}`;
return {
content,
fileName,
name,
uri,
unredirectedUri: document.uri,
eol,
workspaceFolder,
uniqueId,
};
}
export function connectionTarget(uri?: vscode.Uri): ConnectionTarget {
const result: ConnectionTarget = { apiTarget: "", configName: "" };
uri = uri
? uri
: vscode.window.activeTextEditor && vscode.window.activeTextEditor.document
? vscode.window.activeTextEditor.document.uri
: undefined;
if (uri) {
if (notIsfs(uri)) {
const folder = vscode.workspace.getWorkspaceFolder(uri);
// Active document might not be from any folder in the workspace (e.g. user's settings.json)
if (folder) {
result.configName = folder.name;
result.apiTarget = result.configName;
}
} else if (schemas.includes(uri.scheme)) {
result.apiTarget = uri;
const parts = uri.authority.split(":");
result.configName = parts.length === 2 ? parts[0] : uri.authority;
}
}
// Fall back to the connection for the first folder in the workspace
if (result.apiTarget === "") {
const firstFolder =
vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length
? vscode.workspace.workspaceFolders[0]
: undefined;
if (firstFolder && schemas.includes(firstFolder.uri.scheme)) {
const parts = firstFolder.uri.authority.split(":");
result.configName = parts.length === 2 ? parts[0] : firstFolder.uri.authority;
result.apiTarget = firstFolder.uri;
} else {
result.configName = workspaceState.get<string>("workspaceFolder") || firstFolder ? firstFolder.name : "";
result.apiTarget = result.configName;
}
}
return result;
}
/**
* Given a URI, returns a server name for it if it is under isfs[-readonly] or null if it is not an isfs file.
* @param uri URI to evaluate
*/
export function getServerName(uri: vscode.Uri): string {
if (!schemas.includes(uri.scheme)) {
return null;
}
if (isCSPFile(uri)) {
// The full file path is the server name of the file.
return uri.path;
} else {
// Complex case: replace folder slashes with dots.
const filePath = uri.path.slice(1);
let serverName = filePath.replace(/\//g, ".");
if (!filePath.split("/").pop().includes(".")) {
// This is a package so add the .PKG extension
serverName += ".PKG";
}
return serverName;
}
}
export function currentWorkspaceFolder(document?: vscode.TextDocument): string {
document = document ? document : vscode.window.activeTextEditor && vscode.window.activeTextEditor.document;
if (document) {
const folder = workspaceFolderOfUri(document.uri);
// document might not be part of the workspace (e.g. the XXX.code-workspace JSON file)
if (folder) {
return folder;
} else {
return "";
}
}
const firstFolder =
vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length
? vscode.workspace.workspaceFolders[0]
: undefined;
if (firstFolder && schemas.includes(firstFolder.uri.scheme)) {
return firstFolder.uri.authority;
} else {
return workspaceState.get<string>("workspaceFolder") || firstFolder ? firstFolder.name : "";
}
}
export function workspaceFolderOfUri(uri: vscode.Uri): string {
if (notIsfs(uri)) {
if (vscode.workspace.getWorkspaceFolder(uri)) {
return vscode.workspace.getWorkspaceFolder(uri).name;
}
} else {
const rootUri = uri.with({ path: "/" }).toString();
const foundFolder = vscode.workspace.workspaceFolders.find(
(workspaceFolder) => workspaceFolder.uri.toString() == rootUri
);
return foundFolder ? foundFolder.name : uri.authority;
}
return "";
}
export function uriOfWorkspaceFolder(workspaceFolder: string = currentWorkspaceFolder()): vscode.Uri | undefined {
if (!workspaceFolder || !vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length == 0) {
// There are no workspace folders open
return undefined;
}
return (
vscode.workspace.workspaceFolders.find((el): boolean => el.name.toLowerCase() === workspaceFolder.toLowerCase()) ||
vscode.workspace.workspaceFolders.find((el): boolean => el.uri.authority == workspaceFolder)
).uri;
}
export function onlyUnique(value: { name: string }, index: number, self: { name: string }[]): boolean {
if (value && value.name) {
return self.findIndex((el): boolean => el.name === value.name) === index;
}
return self.indexOf(value) === index;
}
export function notNull(el: any): boolean {
return el !== null;
}
/** Determine the compose command to use (`docker-compose` or `docker compose`). */
async function composeCommand(cwd?: string): Promise<string> {
return new Promise<string>((resolve) => {
let cmd = "docker compose";
exec(`${cmd} version`, { cwd }, (error) => {
if (error) {
// 'docker compose' is not present, so default to 'docker-compose'
cmd = "docker-compose";
}
resolve(cmd);
});
});
}
export async function portFromDockerCompose(
workspaceFolderName?: string
): Promise<{ port: number; docker: boolean; service?: string }> {
// When running remotely, behave as if there is no docker-compose object within objectscript.conn
if (extensionContext.extension.extensionKind === vscode.ExtensionKind.Workspace) {
return { docker: false, port: null };
}
// Seek a valid docker-compose object within objectscript.conn
const { "docker-compose": dockerCompose = {} } = config("conn", workspaceFolderName);
const { service, file = "docker-compose.yml", internalPort = 52773, envFile } = dockerCompose;
if (!internalPort || !file || !service || service === "") {
return { docker: false, port: null };
}
const result = { port: null, docker: true, service };
const workspaceFolder = uriOfWorkspaceFolder(workspaceFolderName);
if (!workspaceFolder) {
// No workspace folders are open
return { docker: false, port: null };
}
const workspaceFolderPath = workspaceFolder.fsPath;
const workspaceRootPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
const cwd: string = await fileExists(vscode.Uri.file(path.join(workspaceFolderPath, file))).then(async (exists) => {
if (exists) {
return workspaceFolderPath;
}
if (workspaceFolderPath !== workspaceRootPath) {
exists = await fileExists(vscode.Uri.file(path.join(workspaceRootPath, file)));
if (exists) {
return workspaceRootPath;
}
throw new Error(`File '${file}' not found in ${workspaceFolderPath} or ${workspaceRootPath}.`);
}
throw new Error(`File '${file}' not found in ${workspaceFolderPath}.`);
});
if (!cwd) {
return result;
}
const envFileParam = envFile ? `--env-file ${envFile}` : "";
const cmd = `${await composeCommand(cwd)} -f ${file} ${envFileParam} `;
return new Promise((resolve, reject) => {
exec(`${cmd} ps --services --filter status=running`, { cwd }, (error, stdout) => {
if (error) {
reject(error.message);
}
if (!stdout.replaceAll("\r", "").split("\n").includes(service)) {
reject(`Service '${service}' not found in '${path.join(cwd, file)}', or not running.`);
}
exec(`${cmd} port --protocol=tcp ${service} ${internalPort}`, { cwd }, (error, stdout) => {
if (error) {
reject(error.message);
}
const [, port] = stdout.match(/:(\d+)/) || [];
if (!port) {
reject(`Port ${internalPort} not published for service '${service}' in '${path.join(cwd, file)}'.`);
}
resolve({ port: parseInt(port, 10), docker: true, service });
});
});
});
}
export async function terminalWithDocker(): Promise<vscode.Terminal> {
const { ns, "docker-compose": dockerCompose } = config("conn");
const { service, file = "docker-compose.yml" } = dockerCompose;
const workspace = currentWorkspaceFolder();
const terminalName = `ObjectScript:${workspace}`;
let terminal = terminals.find((t) => t.name == terminalName && t.exitStatus == undefined);
if (!terminal) {
let exe = await composeCommand();
const argsArr: string[] = [];
if (exe == "docker compose") {
const exeSplit = exe.split(" ");
exe = exeSplit[0];
argsArr.push(exeSplit[1]);
}
terminal = vscode.window.createTerminal(
terminalName,
`${exe}${process.platform == "win32" ? ".exe" : ""}`,
argsArr.concat([
"-f",
file,
"exec",
service,
"/bin/bash",
"-c",
`[ -f /tmp/vscodesession.pid ] && kill $(cat /tmp/vscodesession.pid) >/dev/null 2>&1 ; echo $$ > /tmp/vscodesession.pid;
$(command -v ccontrol || command -v iris) session $ISC_PACKAGE_INSTANCENAME -U ${ns}`,
])
);
terminals.push(terminal);
}
terminal.show(true);
return terminal;
}
export async function shellWithDocker(): Promise<vscode.Terminal> {
const { "docker-compose": dockerCompose } = config("conn");
const { service, file = "docker-compose.yml" } = dockerCompose;
const workspace = currentWorkspaceFolder();
const terminalName = `Shell:${workspace}`;
let terminal = terminals.find((t) => t.name == terminalName && t.exitStatus == undefined);
if (!terminal) {
let exe = await composeCommand();
const argsArr: string[] = [];
if (exe == "docker compose") {
const exeSplit = exe.split(" ");
exe = exeSplit[0];
argsArr.push(exeSplit[1]);
}
terminal = vscode.window.createTerminal(
terminalName,
`${exe}${process.platform == "win32" ? ".exe" : ""}`,
argsArr.concat(["-f", file, "exec", service, "/bin/bash"])
);
terminals.push(terminal);
}
terminal.show(true);
return terminal;
}
/**
* Alter isfs-type uri.path of /.vscode/* files or subdirectories.
* Rewrite `/.vscode/path/to/file` as `/_vscode/XYZ/path/to/file`
* where XYZ comes from the `ns` queryparam of uri.
* Also alter query to specify `ns=%SYS&csp=1`
* Also handles the alternative syntax isfs://server:namespace/
* in which there is no ns queryparam
* For both syntaxes the namespace folder name is uppercased
*
* @returns uri, altered if necessary.
* @throws if `ns` queryparam is missing but required.
*/
export function redirectDotvscodeRoot(uri: vscode.Uri): vscode.Uri {
if (!schemas.includes(uri.scheme)) {
return uri;
}
const dotMatch = uri.path.match(/^\/(\.[^/]*)(\/.*)?$/);
if (dotMatch && dotMatch[1] === ".vscode") {
let namespace: string;
const nsMatch = `&${uri.query}&`.match(/&ns=([^&]+)&/);
if (nsMatch) {
namespace = nsMatch[1].toUpperCase();
const newQueryString = (("&" + uri.query).replace(`ns=${namespace}`, "ns=%SYS") + "&csp").slice(1);
return uri.with({ path: `/_vscode/${namespace}${dotMatch[2] || ""}`, query: newQueryString });
} else {
const parts = uri.authority.split(":");
if (parts.length === 2) {
namespace = parts[1].toUpperCase();
return uri.with({
authority: `${parts[0]}:%SYS`,
path: `/_vscode/${namespace}${dotMatch[2] || ""}`,
query: uri.query + "&csp",
});
}
}
throw new Error("No namespace determined from uri");
} else {
return uri;
}
}
/** Check if local `file` exists using vscode's `workspace.fs` FileSystem. */
export async function fileExists(file: vscode.Uri): Promise<boolean> {
try {
await vscode.workspace.fs.stat(file);
return true;
} catch {
// Only error thown is "FileNotFound"
return false;
}
}
/** Check if class `cls` is Deployed in using server connection `api`. */
export async function isClassDeployed(cls: string, api: AtelierAPI): Promise<boolean> {
const clsname = cls.slice(-4).toLowerCase() == ".cls" ? cls.slice(0, -4) : cls;
return (
api
.actionQuery("SELECT Deployed FROM %Dictionary.ClassDefinition WHERE Name = ?", [clsname])
.then((data) => data.result.content[0]?.Deployed > 0)
// Query failure is probably due to a permissions error, so fall back to index
.catch(() => api.actionIndex([`${clsname}.cls`]).then((data) => data.result.content[0].content?.depl ?? false))
);
}
/** Strip quotes from class member `name` if present */
export function stripClassMemberNameQuotes(name: string): string {
return name.charAt(0) == '"' && name.charAt(name.length - 1) == '"' ? name.slice(1, -1).replaceAll('""', '"') : name;
}
/** Returns `true` if `uri1` is a parent of `uri2`. */
export function uriIsParentOf(uri1: vscode.Uri, uri2: vscode.Uri): boolean {
uri1 = uri1.with({ path: !uri1.path.endsWith("/") ? `${uri1.path}/` : uri1.path });
return (
uri2
.with({ query: "", fragment: "" })
.toString()
.startsWith(uri1.with({ query: "", fragment: "" }).toString()) &&
uri1.query == uri2.query &&
uri1.fragment == uri2.fragment
);
}
/** Get the text of file `uri`. Works for all file systems and the `objectscript` `DocumentContentProvider`. */
export async function getFileText(uri: vscode.Uri): Promise<string> {
if (uri.scheme == OBJECTSCRIPT_FILE_SCHEMA) {
return await documentContentProvider.provideTextDocumentContent(uri, new vscode.CancellationTokenSource().token);
} else {
return new TextDecoder().decode(await vscode.workspace.fs.readFile(uri));
}
}
/** Determine the exact line of `method` and `offset` within a class. If the line could be determined, it is returned one-indexed. */
export function methodOffsetToLine(
members: vscode.DocumentSymbol[],
fileText: string,
method: string,
offset = 0
): number | undefined {
let line: number;
const languageServer: boolean = vscode.extensions.getExtension(lsExtensionId)?.isActive ?? false;
// Find the DocumentSymbol for this method
let currentSymbol: vscode.DocumentSymbol;
for (const symbol of members) {
if (stripClassMemberNameQuotes(symbol.name) === method && symbol.detail.toLowerCase().includes("method")) {
currentSymbol = symbol;
break;
}
}
if (currentSymbol !== undefined) {
const fileTextLines = fileText.split(/\r?\n/);
if (languageServer) {
for (
let methodlinenum = currentSymbol.selectionRange.start.line;
methodlinenum <= currentSymbol.range.end.line;
methodlinenum++
) {
// Find the offset of this breakpoint in the method
const methodlinetext: string = fileTextLines[methodlinenum].trim();
if (methodlinetext.endsWith("{")) {
// This is the last line of the method definition, so count from here
line = methodlinenum + offset + 1;
break;
}
}
} else {
line = currentSymbol.selectionRange.start.line + offset;
}
}
return line;
}
/** Return `true` if this username signals unauthenticated access */
export function isUnauthenticated(username: string): boolean {
return username == undefined || username == "" || username.toLowerCase() == "unknownuser";
}
/** Returns `true` if `uri.scheme` is neither `isfs` nor `isfs-readonly` */
export function notIsfs(uri: vscode.Uri): boolean {
return !filesystemSchemas.includes(uri.scheme);
}
/** Base64 encoding must be in chunk size multiple of 3 and within the server's potential 32K string limit */
export function base64EncodeContent(content: Buffer): string[] {
// Output is 4 chars for each 3 input, so 24573/3*4 = 32764
const chunkSize = 24573;
let start = 0;
const result = [];
while (start < content.byteLength) {
result.push(content.toString("base64", start, start + chunkSize));
start += chunkSize;
}
return result;
}
interface ConnQPItem extends vscode.QuickPickItem {
uri: vscode.Uri;
ns: string;
}
/**
* Prompt the user to pick an active server connection that's used in this workspace.
* Returns the uri of the workspace folder corresponding to the chosen connection.
* Returns `undefined` if there are no active server connections in this workspace,
* or if the user dismisses the QuickPick. If there is only one active server
* connection, that will be returned without prompting the user.
*
* @param minVersion Optional minimum server version to enforce, in semantic version form (20XX.Y.Z).
* @returns `undefined` if there were no suitable server connections and `null` if the
* user explicitly escaped from the QuickPick.
*/
export async function getWsServerConnection(minVersion?: string): Promise<vscode.Uri> {
if (!vscode.workspace.workspaceFolders?.length) return;
const conns: ConnQPItem[] = [];
for (const wsFolder of vscode.workspace.workspaceFolders) {
const api = new AtelierAPI(wsFolder.uri);
if (!api.active) continue;
const config = api.config;
if (minVersion && lt(config.serverVersion, minVersion)) continue;
const conn = {
label: api.connInfo,
description: isUnauthenticated(config.username) ? "Unauthenticated" : config.username,
detail: `http${config.https ? "s" : ""}://${config.host}:${config.port}${config.pathPrefix}`,
uri: wsFolder.uri,
ns: api.ns,
};
if (!conns.some((c) => c.detail == conn.detail && c.description == conn.description && c.ns == conn.ns))
conns.push(conn);
}
if (!conns.length) return;
if (conns.length == 1) return conns[0].uri;
return vscode.window
.showQuickPick(conns, {
canPickMany: false,
ignoreFocusOut: true,
matchOnDescription: true,
matchOnDetail: true,
title: "Pick a server connection from the current workspace",
})
.then((c) => c?.uri ?? null);
}
// ---------------------------------------------------------------------
// Source: https://github.com/amsterdamharu/lib/blob/master/src/index.js
const promiseLike = (x) => x !== undefined && typeof x.then === "function";
const ifPromise = (fn) => (x) => (promiseLike(x) ? x.then(fn) : fn(x));
/*
causes a promise returning function not to be called
until less than max are active
usage example:
max2 = throttle(2);
urls = [url1,url2,url3...url100]
Promise.all(//even though a 100 promises are created, only 2 are active
urls.map(max2(fetch))
)
*/
const throttle = (max: number): ((fn: any) => (arg: any) => Promise<any>) => {
let que = [];
let queIndex = -1;
let running = 0;
const wait = (resolve, fn, arg) => () => resolve(ifPromise(fn)(arg)) || true; //should always return true
const nextInQue = () => {
++queIndex;
if (typeof que[queIndex] === "function") {
return que[queIndex]();
} else {
que = [];
queIndex = -1;
running = 0;
return "Does not matter, not used";
}
};
const queItem = (fn, arg) => new Promise((resolve, reject) => que.push(wait(resolve, fn, arg)));
return (fn) => (arg) => {
const p = queItem(fn, arg).then((x) => nextInQue() && x);
running++;
if (running <= max) {
nextInQue();
}
return p;
};
};
// ---------------------------------------------------------------------
/**
* Wrap around each promise in array to avoid overloading the server.
*/
export const throttleRequests = throttle(50);