-
Notifications
You must be signed in to change notification settings - Fork 170
/
helper.ts
224 lines (203 loc) · 6.27 KB
/
helper.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
import { dim, red, yellow } from 'https://deno.land/std@0.106.0/fmt/colors.ts'
import { createHash } from 'https://deno.land/std@0.106.0/hash/mod.ts'
import { dirname, basename, extname, join, relative } from 'https://deno.land/std@0.106.0/path/mod.ts'
import { minDenoVersion } from '../shared/constants.ts'
import { existsFile, existsDir } from '../shared/fs.ts'
import log from '../shared/log.ts'
import util from '../shared/util.ts'
import { SourceType } from '../compiler/mod.ts'
import { VERSION } from '../version.ts'
import { localProxy } from './localproxy.ts'
// inject browser navigator polyfill
Object.assign((globalThis as any).navigator, {
connection: {
downlink: 10,
effectiveType: '4g',
onchange: null,
rtt: 50,
saveData: false,
},
cookieEnabled: false,
language: 'en',
languages: ['en'],
onLine: true,
platform: Deno.build.os,
userAgent: `Deno/${Deno.version.deno}`,
vendor: 'Deno Land'
})
let _denoDir: string | null = null
let _localProxy = false
export function checkDenoVersion() {
const [currentMajor, currentMinor, currentPatch] = Deno.version.deno.split('.').map(p => parseInt(p))
const [major, minor, patch] = minDenoVersion.split('.').map(p => parseInt(p))
if (currentMajor > major) return
if (currentMajor === major && currentMinor > minor) return
if (currentMajor === major && currentMinor === minor && currentPatch >= patch) return
log.error(`Aleph.js needs Deno ${minDenoVersion}+, please upgrade Deno.`)
Deno.exit(1)
}
export function checkAlephDev() {
const v = Deno.env.get('ALEPH_DEV')
if (v !== undefined && !_localProxy) {
localProxy(Deno.cwd(), 2020)
_localProxy = true
}
}
export const moduleExclude = [
/(^|\/|\\)\./,
/\.d\.ts$/i,
/(\.|_)(test|spec|e2e)\.[a-z]+$/i
]
const reLocalUrl = /^https?:\/\/(localhost|0\.0\.0\.0|127\.0\.0\.1)(\:|\/|$)/
/** check whether it is a localhost url. */
export function isLocalUrl(url: string): boolean {
return reLocalUrl.test(url)
}
export async function findFile(wd: string, filenames: string[]) {
for (const filename of filenames) {
const fullPath = join(wd, filename)
if (await existsFile(fullPath)) {
return fullPath
}
}
return null
}
/** get the deno cache dir. */
export async function getDenoDir() {
if (_denoDir !== null) {
return _denoDir
}
const p = Deno.run({
cmd: [Deno.execPath(), 'info', '--json', '--unstable'],
stdout: 'piped',
stderr: 'null'
})
const output = (new TextDecoder).decode(await p.output())
const { denoDir } = JSON.parse(output)
p.close()
if (denoDir === undefined || !await existsDir(denoDir)) {
throw new Error(`can't find the deno dir`)
}
_denoDir = denoDir
return denoDir
}
/** get aleph pkg uri. */
export function getAlephPkgUri() {
const DEV_PORT = Deno.env.get('ALEPH_DEV_PORT')
if (DEV_PORT) {
return `http://localhost:${DEV_PORT}`
}
return `https://deno.land/x/aleph@v${VERSION}`
}
/** get the relative path from `from` to `to`. */
export function toRelativePath(from: string, to: string): string {
const r = relative(from, to).replaceAll('\\', '/')
if (!r.startsWith('.') && !r.startsWith('/')) {
return './' + r
}
return r
}
/** get source type by given url and content type. */
export function getSourceType(url: string, contentType?: string): SourceType {
if (util.isFilledString(contentType)) {
switch (contentType.split(';')[0].trim()) {
case 'application/javascript':
case 'text/javascript':
return SourceType.JS
case 'text/jsx':
return SourceType.JSX
case 'text/typescript':
if (url.endsWith('.tsx')) {
return SourceType.TSX
}
return SourceType.TS
case 'text/tsx':
return SourceType.TSX
case 'text/css':
return SourceType.CSS
}
}
switch (extname(url)) {
case '.mjs':
case '.js':
return SourceType.JS
case '.jsx':
return SourceType.JSX
case '.ts':
return SourceType.TS
case '.tsx':
return SourceType.TSX
case '.css':
case '.pcss':
case '.postcss':
return SourceType.CSS
}
return SourceType.Unknown
}
const reEndsWithVersion = /@\d+(\.\d+){0,2}(\-[a-z0-9]+(\.[a-z0-9]+)?)?$/
/**
* fix remote import url to local
* https://esm.sh/react.js?bundle -> /-/esm.sh/react.YnVuZGxl.js
*/
export function toLocalPath(url: string): string {
if (util.isLikelyHttpURL(url)) {
let { hostname, pathname, port, protocol, search } = new URL(url)
const isHttp = protocol === 'http:'
if ((isHttp && port === '80') || (protocol === 'https:' && port === '443')) {
port = ''
}
if (search !== '') {
const a = util.splitPath(pathname)
const basename = a.pop()!
const realext = extname(basename)
const ext = realext != "" && !basename.match(reEndsWithVersion) ? realext : "js"
const search64 = util.btoaUrl(search.slice(1))
a.push(util.trimSuffix(basename, ext) + `.${search64}.` + ext)
pathname = '/' + a.join('/')
}
return [
'/-/',
(isHttp ? 'http_' : ''),
hostname,
(port ? '_' + port : ''),
pathname
].join('')
}
return util.trimPrefix(url, 'file://')
}
/** compute hash of the content */
export function computeHash(content: string | Uint8Array, algorithm: 'md5' | 'sha1' = 'sha1'): string {
return createHash(algorithm).update(content).toString()
}
/**
* coloring the bytes string
* - dim: 0 - 1MB
* - yellow: 1MB - 10MB
* - red: > 10MB
*/
export function formatBytesWithColor(bytes: number) {
let cf = dim
if (bytes > 10 << 20) { // 10MB
cf = red
} else if (bytes > 1 << 20) { // 1MB
cf = yellow
}
return cf(util.formatBytes(bytes))
}
export async function clearBuildCache(filename: string, ext = 'js') {
const dir = dirname(filename)
const hashname = basename(filename)
const regHashExt = new RegExp(`\\.[0-9a-f]+\\.${ext}$`, 'i')
if (ext && !regHashExt.test(hashname) || !await existsDir(dir)) {
return
}
const jsName = hashname.split('.').slice(0, -2).join('.') + '.' + ext
for await (const entry of Deno.readDir(dir)) {
if (entry.isFile && regHashExt.test(entry.name)) {
const _jsName = entry.name.split('.').slice(0, -2).join('.') + '.' + ext
if (_jsName === jsName && hashname !== entry.name) {
await Deno.remove(join(dir, entry.name))
}
}
}
}