1 | import path from 'path';
|
2 | import { promisify } from 'util';
|
3 | import fs from 'fs';
|
4 | const readFile = promisify(fs.readFile);
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | export const toLowerCase = (str) => str.toLowerCase();
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export const dashToPascalCase = (str) => toLowerCase(str)
|
17 | .split('-')
|
18 | .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
19 | .join('');
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | export function flatOne(array) {
|
27 | if (array.flat) {
|
28 | return array.flat(1);
|
29 | }
|
30 | return array.reduce((result, item) => {
|
31 | result.push(...item);
|
32 | return result;
|
33 | }, []);
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | export function sortBy(array, prop) {
|
42 | return array.slice().sort((a, b) => {
|
43 | const nameA = prop(a);
|
44 | const nameB = prop(b);
|
45 | if (nameA < nameB)
|
46 | return -1;
|
47 | if (nameA > nameB)
|
48 | return 1;
|
49 | return 0;
|
50 | });
|
51 | }
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | export function normalizePath(str) {
|
58 |
|
59 |
|
60 |
|
61 | if (typeof str !== 'string') {
|
62 | throw new Error(`invalid path to normalize`);
|
63 | }
|
64 | str = str.trim();
|
65 | if (EXTENDED_PATH_REGEX.test(str) || NON_ASCII_REGEX.test(str)) {
|
66 | return str;
|
67 | }
|
68 | str = str.replace(SLASH_REGEX, '/');
|
69 |
|
70 |
|
71 | if (str.charAt(str.length - 1) === '/') {
|
72 | const colonIndex = str.indexOf(':');
|
73 | if (colonIndex > -1) {
|
74 | if (colonIndex < str.length - 2) {
|
75 | str = str.substring(0, str.length - 1);
|
76 | }
|
77 | }
|
78 | else if (str.length > 1) {
|
79 | str = str.substring(0, str.length - 1);
|
80 | }
|
81 | }
|
82 | return str;
|
83 | }
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 | export function relativeImport(pathFrom, pathTo, ext) {
|
92 | let relativePath = path.relative(path.dirname(pathFrom), path.dirname(pathTo));
|
93 | if (relativePath === '') {
|
94 | relativePath = '.';
|
95 | }
|
96 | else if (relativePath[0] !== '.') {
|
97 | relativePath = './' + relativePath;
|
98 | }
|
99 | return normalizePath(`${relativePath}/${path.basename(pathTo, ext)}`);
|
100 | }
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 | export async function readPackageJson(rootDir) {
|
107 | const pkgJsonPath = path.join(rootDir, 'package.json');
|
108 | let pkgJson;
|
109 | try {
|
110 | pkgJson = await readFile(pkgJsonPath, 'utf8');
|
111 | }
|
112 | catch (e) {
|
113 | throw new Error(`Missing "package.json" file for distribution: ${pkgJsonPath}`);
|
114 | }
|
115 | let pkgData;
|
116 | try {
|
117 | pkgData = JSON.parse(pkgJson);
|
118 | }
|
119 | catch (e) {
|
120 | throw new Error(`Error parsing package.json: ${pkgJsonPath}, ${e}`);
|
121 | }
|
122 | return pkgData;
|
123 | }
|
124 | const EXTENDED_PATH_REGEX = /^\\\\\?\\/;
|
125 | const NON_ASCII_REGEX = /[^\x00-\x80]+/;
|
126 | const SLASH_REGEX = /\\/g;
|