forked from pnp/cli-microsoft365
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.ts
More file actions
650 lines (570 loc) · 18.4 KB
/
Utils.ts
File metadata and controls
650 lines (570 loc) · 18.4 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
import * as fs from 'fs';
import * as path from 'path';
import * as url from 'url';
export default class Utils {
public static escapeXml(s: any | undefined): any | undefined {
if (!s) {
return s;
}
return s.toString().replace(/[<>&"]/g, (c: string): string => {
let char: string = c;
switch (c) {
case '<':
char = '<';
break;
case '>':
char = '>';
break;
case '&':
char = '&';
break;
case '"':
char = '"';
break;
}
return char;
});
}
public static restore(method: any | any[]): void {
if (!method) {
return;
}
if (!Array.isArray(method)) {
method = [method];
}
method.forEach((m: any): void => {
if (m && m.restore) {
m.restore();
}
});
}
public static isValidGuid(guid: string): boolean {
const guidRegEx: RegExp = new RegExp(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
return guidRegEx.test(guid);
}
public static isValidTeamsChannelId(guid: string): boolean {
const guidRegEx: RegExp = new RegExp(/^19:[0-9a-zA-Z]+@thread\.(skype|tacv2)$/i);
return guidRegEx.test(guid);
}
public static isValidUserPrincipalName(upn: string): boolean {
const upnRegEx = new RegExp(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/i);
return upnRegEx.test(upn);
}
public static isDateInRange(date: string, monthOffset: number): boolean {
const d: Date = new Date(date);
const cutoffDate: Date = new Date();
cutoffDate.setMonth(cutoffDate.getMonth() - monthOffset);
return d > cutoffDate;
}
public static isValidISODate(date: string): boolean {
const dateRegEx: RegExp = new RegExp(
/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/i
);
return dateRegEx.test(date);
}
public static isValidISODateDashOnly(date: string): boolean {
const dateTimeRegEx: RegExp = new RegExp(
/^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$/i
);
const dateOnlyRegEx: RegExp = new RegExp(
/^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/i
);
return dateTimeRegEx.test(date) ? true : dateOnlyRegEx.test(date);
}
public static isValidISODateTime(dateTime: string): boolean {
const withMilliSecsPattern: RegExp = new RegExp(
/^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))T(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])\.[0-9]{3}Z$/);
if (withMilliSecsPattern.test(dateTime)) {
return true;
}
const withSecsPattern: RegExp = new RegExp(
/^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))T(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])Z$/);
if (withSecsPattern.test(dateTime)) {
return true;
}
const withMinutesPattern: RegExp = new RegExp(
/^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))T(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])Z$/);
if (withMinutesPattern.test(dateTime)) {
return true;
}
const withHoursPattern: RegExp = new RegExp(
/^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))T(0[0-9]|1[0-9]|2[0-3])Z$/);
if (withHoursPattern.test(dateTime)) {
return true;
}
const withoutTimePattern: RegExp = new RegExp(
/^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))$/);
if (withoutTimePattern.test(dateTime)) {
return true;
}
return false;
}
public static isValidBoolean(value: string): boolean {
return value.toLowerCase() === 'true' || value.toLowerCase() === 'false';
}
public static getTenantIdFromAccessToken(accessToken: string): string {
let tenantId: string = '';
if (!accessToken || accessToken.length === 0) {
return tenantId;
}
const chunks = accessToken.split('.');
if (chunks.length !== 3) {
return tenantId;
}
const tokenString: string = Buffer.from(chunks[1], 'base64').toString();
try {
const token: any = JSON.parse(tokenString);
tenantId = token.tid;
}
catch {
}
return tenantId;
}
public static getUserNameFromAccessToken(accessToken: string): string {
let userName: string = '';
if (!accessToken || accessToken.length === 0) {
return userName;
}
const chunks = accessToken.split('.');
if (chunks.length !== 3) {
return userName;
}
const tokenString: string = Buffer.from(chunks[1], 'base64').toString();
try {
const token: any = JSON.parse(tokenString);
// if authenticated using certificate, there is no upn so use
// app display name instead
userName = token.upn || token.app_displayname;
}
catch {
}
return userName;
}
/**
* Returns server relative path.
* @param webUrl web full or web relative url e.g. https://contoso.sharepoint.com/sites/team1
* @param folderRelativePath folder relative path e.g. /Shared Documents
* @example
* // returns "/sites/team1"
* Utils.getServerRelativePath("https://contoso.sharepoint.com/sites/team1", "");
* @example
* // returns "/sites/team1/Shared Documents"
* Utils.getServerRelativePath("https://contoso.sharepoint.com/sites/team1", "/Shared Documents");
* @example
* // returns "/sites/team1/Shared Documents"
* Utils.getServerRelativePath("/sites/team1/", "/Shared Documents");
*/
public static getServerRelativePath(webUrl: string, folderRelativePath: string): string {
const tenantUrl: string = `${url.parse(webUrl).protocol}//${url.parse(webUrl).hostname}`;
// if webUrl is a server-relative URL then tenantUrl will resolve to null//null
// in which case we should keep webUrl
let webRelativePath: string = tenantUrl !== 'null//null' ? webUrl.substr(tenantUrl.length) : webUrl;
// will be used to remove relative path from the folderRelativePath
// in case the web relative url is included
let relativePathToRemove: string = webRelativePath;
// add '/' at 0
if (webRelativePath[0] !== '/') {
webRelativePath = `/${webRelativePath}`;
}
else {
relativePathToRemove = webRelativePath.substring(1);
}
// remove last '/' of webRelativePath
const webPathLastCharPos: number = webRelativePath.length - 1;
if (webRelativePath.length > 1 &&
webRelativePath[webPathLastCharPos] === '/') {
webRelativePath = webRelativePath.substring(0, webPathLastCharPos);
}
// remove the web relative path if it is contained in the folder relative path
const relativePathToRemoveIdx: number = folderRelativePath.toLowerCase().indexOf(relativePathToRemove.toLowerCase());
if (relativePathToRemoveIdx > -1) {
const pos: number = relativePathToRemoveIdx + relativePathToRemove.length;
folderRelativePath = folderRelativePath.substring(pos, folderRelativePath.length);
}
if (folderRelativePath !== '') {
// add '/' at 0 for siteRelativePath
if (folderRelativePath[0] !== '/') {
folderRelativePath = `/${folderRelativePath}`;
}
// remove last '/' of siteRelativePath
const folderPathLastCharPos: number = folderRelativePath.length - 1;
if (folderRelativePath[folderPathLastCharPos] === '/') {
folderRelativePath = folderRelativePath.substring(0, folderPathLastCharPos);
}
if (webRelativePath === '/' && folderRelativePath !== '') {
webRelativePath = folderRelativePath;
}
else {
webRelativePath = `${webRelativePath}${folderRelativePath}`;
}
}
return webRelativePath.replace('//', '/');
}
/**
* Returns server relative site url.
* @param webUrl web full or web relative url e.g. https://contoso.sharepoint.com/sites/team1
* @example
* // returns "/sites/team1"
* Utils.getServerRelativeSiteUrl("https://contoso.sharepoint.com/sites/team1";
* @example
* // returns ""
* Utils.getServerRelativeSiteUrl("https://contoso.sharepoint.com");
* @example
* // returns "/sites/team1/Shared Documents"
* Utils.getServerRelativePath("/sites/team1/", "/Shared Documents");
*/
public static getServerRelativeSiteUrl(webUrl: string): string {
const serverRelativeSiteUrl = Utils.getServerRelativePath(webUrl, '');
// return an empty string instead of / to prevent // replies
return serverRelativeSiteUrl === '/' ? "" : serverRelativeSiteUrl;
}
/**
* Returns web relative path from webUrl and folderUrl.
* @param webUrl web full or web relative url e.g. https://contoso.sharepoint.com/sites/team1/
* @param folderUrl folder server relative url e.g. /sites/team1/Lists/MyList
* @example
* // returns "/Lists/MyList"
* Utils.getWebRelativePath("https://contoso.sharepoint.com/sites/team1/", "/sites/team1/Lists/MyList");
* @example
* // returns "/Shared Documents"
* Utils.getWebRelativePath("/sites/team1/", "/sites/team1/Shared Documents");
*/
public static getWebRelativePath(webUrl: string, folderUrl: string): string {
let folderWebRelativePath: string = '';
const tenantUrl: string = `${url.parse(webUrl).protocol}//${url.parse(webUrl).hostname}`;
// if webUrl is a server-relative URL then tenantUrl will resolve to null//null
// in which case we should keep webUrl
let webRelativePath: string = tenantUrl !== 'null//null' ? webUrl.substr(tenantUrl.length) : webUrl;
// will be used to remove relative path from the folderRelativePath
// in case the web relative url is included
let relativePathToRemove: string = webRelativePath;
// add '/' at 0
if (webRelativePath[0] !== '/') {
webRelativePath = `/${webRelativePath}`;
}
else {
relativePathToRemove = webRelativePath.substring(1);
}
// remove last '/' of webRelativePath
const webPathLastCharPos: number = webRelativePath.length - 1;
if (webRelativePath.length > 1 &&
webRelativePath[webPathLastCharPos] === '/') {
webRelativePath = webRelativePath.substring(0, webPathLastCharPos);
}
// remove the web relative path if it is contained in the folder relative path
const relativePathToRemoveIdx: number = folderUrl.toLowerCase().indexOf(relativePathToRemove.toLowerCase());
if (relativePathToRemoveIdx > -1) {
const pos: number = relativePathToRemoveIdx + relativePathToRemove.length;
folderWebRelativePath = folderUrl.substring(pos, folderUrl.length);
}
else {
folderWebRelativePath = folderUrl;
}
// add '/' at 0 for folderWebRelativePath
if (folderWebRelativePath[0] !== '/') {
folderWebRelativePath = `/${folderWebRelativePath}`;
}
// remove last '/' of folderWebRelativePath
const folderPathLastCharPos: number = folderWebRelativePath.length - 1;
if (folderWebRelativePath.length > 1 && folderWebRelativePath[folderPathLastCharPos] === '/') {
folderWebRelativePath = folderWebRelativePath.substring(0, folderPathLastCharPos);
}
return folderWebRelativePath.replace('//', '/');
}
/**
* Returns the absolute URL according to a Web URL and the server relative URL of a folder
* @param webUrl The full URL of a web
* @param serverRelativeUrl The server relative URL of a folder
* @example
* // returns "https://contoso.sharepoint.com/sites/team1/Lists/MyList"
* Utils.getAbsoluteUrl("https://contoso.sharepoint.com/sites/team1/", "/sites/team1/Lists/MyList");
*/
public static getAbsoluteUrl(webUrl: string, serverRelativeUrl: string): string {
const uri: url.UrlWithStringQuery = url.parse(webUrl);
const tenantUrl: string = `${uri.protocol}//${uri.hostname}`;
if (serverRelativeUrl[0] !== '/') {
serverRelativeUrl = `/${serverRelativeUrl}`;
}
return `${tenantUrl}${serverRelativeUrl}`;
}
public static isJavascriptReservedWord(input: string): boolean {
const javascriptReservedWords: string[] = [
"arguments",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"static",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"yield",
"Array",
"Date",
"eval",
"function",
"hasOwnProperty",
"Infinity",
"isFinite",
"isNaN",
"isPrototypeOf",
"length",
"Math",
"NaN",
"name",
"Number",
"Object",
"prototype",
"String",
"toString",
"undefined",
"valueOf",
"alert",
"all",
"anchor",
"anchors",
"area",
"assign",
"blur",
"button",
"checkbox",
"clearInterval",
"clearTimeout",
"clientInformation",
"close",
"closed",
"confirm",
"constructor",
"crypto",
"decodeURI",
"decodeURIComponent",
"defaultStatus",
"document",
"element",
"elements",
"embed",
"embeds",
"encodeURI",
"encodeURIComponent",
"escape",
"event",
"fileUpload",
"focus",
"form",
"forms",
"frame",
"innerHeight",
"innerWidth",
"layer",
"layers",
"link",
"location",
"mimeTypes",
"navigate",
"navigator",
"frames",
"frameRate",
"hidden",
"history",
"image",
"images",
"offscreenBuffering",
"open",
"opener",
"option",
"outerHeight",
"outerWidth",
"packages",
"pageXOffset",
"pageYOffset",
"parent",
"parseFloat",
"parseInt",
"password",
"pkcs11",
"plugin",
"prompt",
"propertyIsEnum",
"radio",
"reset",
"screenX",
"screenY",
"scroll",
"secure",
"select",
"self",
"setInterval",
"setTimeout",
"status",
"submit",
"taint",
"text",
"textarea",
"top",
"unescape",
"untaint",
"window",
"onblur",
"onclick",
"onerror",
"onfocus",
"onkeydown",
"onkeypress",
"onkeyup",
"onmouseover",
"onload",
"onmouseup",
"onmousedown",
"onsubmit"
];
return !!input && !input.split('.').every(value => !~javascriptReservedWords.indexOf(value));
}
public static isValidFileName(input: string): boolean {
return !!input && !/^((\..*)|COM\d|CLOCK\$|LPT\d|AUX|NUL|CON|PRN|(.*[\u{d800}-\u{dfff}]+.*))$/iu.test(input) && !/^(.*\.\..*)$/i.test(input);
}
public static getSafeFileName(input: string): string {
return input
.replace(/'/g, "''");
}
public static isValidTheme(input: string): boolean {
const validThemeProperties = [
"themePrimary",
"themeLighterAlt",
"themeLighter",
"themeLight",
"themeTertiary",
"themeSecondary",
"themeDarkAlt",
"themeDark",
"themeDarker",
"neutralLighterAlt",
"neutralLighter",
"neutralLight",
"neutralQuaternaryAlt",
"neutralQuaternary",
"neutralTertiaryAlt",
"neutralTertiary",
"neutralSecondary",
"neutralPrimaryAlt",
"neutralPrimary",
"neutralDark",
"black",
"white"
];
let theme: any;
try {
theme = JSON.parse(input);
}
catch {
return false;
}
if (Array.isArray(theme)) {
return false;
}
const hasInvalidProperties = validThemeProperties.map((property) => {
return theme.hasOwnProperty(property);
}).includes(false);
if (hasInvalidProperties) {
return false;
}
const regex = new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/);
const hasInvalidValues = validThemeProperties.map((property: string) => {
return regex.test(theme[property]);
}).includes(false);
if (hasInvalidValues) {
return false;
}
return true;
}
public static parseJsonWithBom(s: string): any {
return JSON.parse(s.replace(/^\uFEFF/, ''));
}
public static filterObject(obj: any, propertiesToInclude: string[]): any {
return Object.keys(obj)
.filter(key => propertiesToInclude.includes(key))
.reduce((filtered: any, key: string) => {
filtered[key] = obj[key];
return filtered;
}, {});
}
public static readdirR(dir: string): string | string[] {
return fs.statSync(dir).isDirectory()
? Array.prototype.concat(...fs.readdirSync(dir).map(f => Utils.readdirR(path.join(dir, f))))
: dir;
}
// from: https://stackoverflow.com/a/22185855
public static copyRecursiveSync(src: string, dest: string, replaceTokens?: (s: string) => string): void {
const exists: boolean = fs.existsSync(src);
const stats: false | fs.Stats = exists && fs.statSync(src);
const isDirectory: boolean = exists && (stats as fs.Stats).isDirectory();
if (replaceTokens) {
dest = replaceTokens(dest);
}
if (isDirectory) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).forEach(function (childItemName) {
Utils.copyRecursiveSync(path.join(src, childItemName),
path.join(dest, childItemName), replaceTokens);
});
}
else {
fs.copyFileSync(src, dest);
}
}
public static parseCsvToJson(s: string): any {
const rows: string[] = s.split('\n');
const jsonObj: any = [];
const headers: string[] = rows[0].split(',');
for (let i = 1; i < rows.length; i++) {
const data: string[] = rows[i].split(',');
const obj: any = {};
for (let j = 0; j < data.length; j++) {
const value = data[j].trim();
const numValue = parseInt(value);
obj[headers[j].trim()] = isNaN(numValue) || numValue.toString() !== value ? value : numValue;
}
jsonObj.push(obj);
}
return jsonObj;
}
}