-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathutils.ts
228 lines (184 loc) · 6.04 KB
/
utils.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
import { parse } from 'node:path'
import process from 'node:process'
import { minimatch } from 'minimatch'
import resolve from 'resolve'
import { slash, toArray } from '@antfu/utils'
import {
getPackageInfo,
isPackageExists,
} from 'local-pkg'
import type { ComponentInfo, ImportInfo, ImportInfoLegacy, Options, ResolvedOptions } from '../types'
import type { Context } from './context'
import { DISABLE_COMMENT } from './constants'
export const isSSR = Boolean(process.env.SSR || process.env.SSG || process.env.VITE_SSR || process.env.VITE_SSG)
export interface ResolveComponent {
filename: string
namespace?: string
}
export function pascalCase(str: string) {
return capitalize(camelCase(str))
}
export function camelCase(str: string) {
return str.replace(/-(\w)/g, (_, c) => (c ? c.toUpperCase() : ''))
}
export function kebabCase(key: string) {
const result = key.replace(/([A-Z])/g, ' $1').trim()
return result.split(' ').join('-').toLowerCase()
}
export function capitalize(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
export function parseId(id: string) {
const index = id.indexOf('?')
if (index < 0) {
return { path: id, query: {} }
}
else {
const query = Object.fromEntries(new URLSearchParams(id.slice(index)) as any)
return {
path: id.slice(0, index),
query,
}
}
}
export function isEmpty(value: any) {
if (!value || value === null || value === undefined || (Array.isArray(value) && Object.keys(value).length <= 0))
return true
else
return false
}
export function matchGlobs(filepath: string, globs: string[]) {
for (const glob of globs) {
if (minimatch(slash(filepath), glob))
return true
}
return false
}
export function getTransformedPath(path: string, importPathTransform?: Options['importPathTransform']): string {
if (importPathTransform) {
const result = importPathTransform(path)
if (result != null)
path = result
}
return path
}
export function stringifyImport(info: ImportInfo | string) {
if (typeof info === 'string')
return `import '${info}'`
if (!info.as)
return `import '${info.from}'`
else if (info.name)
return `import { ${info.name} as ${info.as} } from '${info.from}'`
else
return `import ${info.as} from '${info.from}'`
}
export function normalizeComponetInfo(info: ImportInfo | ImportInfoLegacy | ComponentInfo): ComponentInfo {
if ('path' in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects,
}
}
return info
}
export function stringifyComponentImport({ as: name, from: path, name: importName, sideEffects }: ComponentInfo, ctx: Context) {
path = getTransformedPath(path, ctx.options.importPathTransform)
const imports = [
stringifyImport({ as: name, from: path, name: importName }),
]
if (sideEffects)
toArray(sideEffects).forEach(i => imports.push(stringifyImport(i)))
return imports.join(';')
}
export function getNameFromFilePath(filePath: string, options: ResolvedOptions): string {
const { resolvedDirs, directoryAsNamespace, globalNamespaces, collapseSamePrefixes, root } = options
const parsedFilePath = parse(slash(filePath))
let strippedPath = ''
// remove include directories from filepath
for (const dir of resolvedDirs) {
if (parsedFilePath.dir.startsWith(dir)) {
strippedPath = parsedFilePath.dir.slice(dir.length)
break
}
}
let folders = strippedPath.slice(1).split('/').filter(Boolean)
let filename = parsedFilePath.name
// set parent directory as filename if it is index
if (filename === 'index' && !directoryAsNamespace) {
// when use `globs` option, `resolvedDirs` will always empty, and `folders` will also empty
if (isEmpty(folders))
folders = parsedFilePath.dir.slice(root.length + 1).split('/').filter(Boolean)
filename = `${folders.slice(-1)[0]}`
return filename
}
if (directoryAsNamespace) {
// remove namesspaces from folder names
if (globalNamespaces.some((name: string) => folders.includes(name)))
folders = folders.filter(f => !globalNamespaces.includes(f))
folders = folders.map(f => f.replace(/[^a-zA-Z0-9\-]/g, ''))
if (filename.toLowerCase() === 'index')
filename = ''
if (!isEmpty(folders)) {
// add folders to filename
let namespaced = [...folders, filename]
if (collapseSamePrefixes) {
const collapsed: string[] = []
for (const fileOrFolderName of namespaced) {
let cumulativePrefix = ''
let didCollapse = false
for (const parentFolder of [...collapsed].reverse()) {
cumulativePrefix = `${capitalize(parentFolder)}${cumulativePrefix}`
if (pascalCase(fileOrFolderName).startsWith(pascalCase(cumulativePrefix))) {
const collapseSamePrefix = fileOrFolderName.slice(cumulativePrefix.length)
collapsed.push(collapseSamePrefix)
didCollapse = true
break
}
}
if (!didCollapse)
collapsed.push(fileOrFolderName)
}
namespaced = collapsed
}
filename = namespaced.filter(Boolean).join('-')
}
return filename
}
return filename
}
export function resolveAlias(filepath: string, alias: any) {
const result = filepath
if (Array.isArray(alias)) {
for (const { find, replacement } of alias)
result.replace(find, replacement)
}
return result
}
export async function getPkgVersion(pkgName: string, defaultVersion: string): Promise<string> {
try {
const isExist = isPackageExists(pkgName)
if (isExist) {
const pkg = await getPackageInfo(pkgName)
return pkg?.version ?? defaultVersion
}
else {
return defaultVersion
}
}
catch (err) {
console.error(err)
return defaultVersion
}
}
export function shouldTransform(code: string) {
if (code.includes(DISABLE_COMMENT))
return false
return true
}
export function resolveImportPath(importName: string): string | undefined {
return resolve.sync(importName, {
preserveSymlinks: false,
})
}