/
inject.js
282 lines (242 loc) · 9.15 KB
/
inject.js
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
const fs = require('node:fs')
const path = require('node:path')
const chalk = require('chalk')
const { spawn } = require('node:child_process')
const readline = require('node:readline')
const YAML = require('js-yaml')
const gzipSize = require('gzip-size')
const prettierBytes = require('@transloadit/prettier-bytes')
const esbuild = require('esbuild')
const touch = require('touch')
const glob = require('glob')
const webRoot = __dirname
const uppyRoot = path.join(__dirname, '../packages/uppy')
const robodogRoot = path.join(__dirname, '../packages/@uppy/robodog')
const localesRoot = path.join(__dirname, '../packages/@uppy/locales')
const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
// eslint-disable-next-line import/no-dynamic-require
const { version } = require(path.join(uppyRoot, '/package.json'))
const regionalDisplayNames = new Intl.DisplayNames('en-US', { type: 'region' })
const languageDisplayNames = new Intl.DisplayNames('en-US', { type: 'language' })
const defaultConfig = {
comment: 'Auto updated by inject.js',
uppy_version_anchor: '001',
uppy_version: '0.0.1',
uppy_bundle_kb_sizes: {},
config: {},
}
// Keeping a whitelist so utils etc are excluded
// It may be easier to maintain a blacklist instead
const packages = [
// Bundles
'uppy',
'@uppy/robodog',
// Integrations
'@uppy/react',
// Core
'@uppy/core',
// Plugins -- please keep these sorted alphabetically
'@uppy/aws-s3',
'@uppy/aws-s3-multipart',
'@uppy/dashboard',
'@uppy/drag-drop',
'@uppy/dropbox',
'@uppy/file-input',
'@uppy/form',
'@uppy/golden-retriever',
'@uppy/google-drive',
'@uppy/informer',
'@uppy/instagram',
'@uppy/image-editor',
'@uppy/progress-bar',
'@uppy/screen-capture',
'@uppy/status-bar',
'@uppy/thumbnail-generator',
'@uppy/transloadit',
'@uppy/tus',
'@uppy/url',
'@uppy/webcam',
'@uppy/xhr-upload',
'@uppy/drop-target',
// Stores
'@uppy/store-default',
'@uppy/store-redux',
]
const excludes = {
'@uppy/react': ['react'],
}
// eslint-disable-next-line no-use-before-define
inject().catch((err) => {
console.error(err)
process.exit(1)
})
async function getMinifiedSize (pkg, name) {
const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
// eslint-disable-next-line no-shadow
const { main, version } = JSON.parse(packageJSON)
const external = excludes[name] ?? []
if (name !== '@uppy/core' && name !== 'uppy') {
// Preact is already unconditionally included through @uppy/core
external.unshift('@uppy/core', 'preact')
}
const { outputFiles:[{ contents: bundle }] } = await esbuild.build({
write: false,
bundle: true,
entryPoints: [path.resolve(pkg, main)],
minify: true,
external,
})
const gzipped = await gzipSize(bundle)
return {
minified: bundle.length,
gzipped,
version,
}
}
async function injectSizes (config) {
console.info(chalk.grey('Generating bundle sizes…'))
const padTarget = Math.max(...packages.map((cur) => cur.length)) + 2
const sizesPromise = Promise.all(
packages.map(async (pkg) => {
const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
console.info(chalk.green(
// ✓ @uppy/pkgname: 10.0 kB min / 2.0 kB gz
` ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}${
`${prettierBytes(result.minified)} min`.padEnd(10)
} / ${prettierBytes(result.gzipped)} gz`,
))
return [pkg, {
...result,
prettyMinified: prettierBytes(result.minified),
prettyGzipped: prettierBytes(result.gzipped),
}]
}),
).then(Object.fromEntries)
// eslint-disable-next-line no-param-reassign
config.uppy_bundle_kb_sizes = await sizesPromise
}
const sourceUppy = path.join(webRoot, '/themes/uppy/source/uppy/')
const sourceUppyLocales = path.join(sourceUppy, 'locales')
async function injectBundles () {
await Promise.all([
fs.promises.mkdir(sourceUppy, { recursive:true }),
fs.promises.mkdir(sourceUppyLocales, { recursive:true }),
])
const cmds = [
`cp -vfR ${path.join(uppyRoot, '/dist/*')} ${sourceUppy}`,
`cp -vfR ${path.join(robodogRoot, '/dist/*')} ${sourceUppy}`,
`cp -vfR ${path.join(localesRoot, '/dist/*')} ${sourceUppyLocales}`,
].join(' && ')
const cp = spawn(cmds, { stdio:['ignore', 'pipe', 'inherit'], shell: true })
await Promise.race([
new Promise((resolve, reject) => cp.on('error', reject)),
(async () => {
const stdout = readline.createInterface({
input: cp.stdout,
})
for await (const line of stdout) {
console.info(chalk.green('✓ injected: '), chalk.grey(line))
}
})(),
])
}
// re-enable after rate limiter issue is fixed
//
async function injectGhStars () {
const opts = {}
if ('GITHUB_TOKEN' in process.env) {
opts.auth = process.env.GITHUB_TOKEN
}
// eslint-disable-next-line global-require
const { Octokit } = require('@octokit/rest')
const octokit = new Octokit(opts)
const { headers, data } = await octokit.repos.get({
owner: 'transloadit',
repo: 'uppy',
})
console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)
const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')
console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
}
async function injectMarkdown () {
const sources = {
'.github/CONTRIBUTING.md': 'src/_template/contributing.md',
}
for (const src of Object.keys(sources)) {
const dst = sources[src]
// strip yaml frontmatter:
const srcpath = path.join(uppyRoot, `/../../${src}`)
const dstpath = path.join(webRoot, dst)
const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
if (parts.length >= 3) {
parts.shift()
parts.shift()
}
let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
content += parts.join('---\n')
fs.writeFileSync(dstpath, content, 'utf-8')
console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
}
touch(path.join(webRoot, '/src/support.md'))
}
function injectLocaleList () {
const mdTable = [
`<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
'| %count% Locales | NPM | CDN | Source on GitHub |',
'| --------------- | ------------------ | ------------------- | ---------------- |',
]
const mdRows = []
const localeList = {}
const localePackagePath = path.join(localesRoot, 'src', '*.js')
// eslint-disable-next-line import/no-dynamic-require, global-require
const localePackageVersion = require(path.join(localesRoot, 'package.json')).version
glob.sync(localePackagePath).forEach((localePath) => {
const localeName = path.basename(localePath, '.js')
const [languageCode, regionCode, variant] = localeName.split(/[-_]/)
const languageName = languageDisplayNames.of(languageCode)
const regionName = regionalDisplayNames.of(regionCode)
const npmPath = `<code class="raw"><a href="https://www.npmjs.com/package/@uppy/locales">@uppy/locales</a>/lib/${localeName}</code>`
const cdnPath = `[\`${localeName}.min.js\`](https://releases.transloadit.com/uppy/locales/v${localePackageVersion}/${localeName}.min.js)`
const githubSource = `[\`${localeName}.js\`](https://github.com/transloadit/uppy/blob/main/packages/%40uppy/locales/src/${localeName}.js)`
const mdTableRow = `| ${languageName}<br/> <small>${regionName}</small>${variant ? `<br /><small>(${variant})</small>` : ''} | ${npmPath} | ${cdnPath} | ✏️ ${githubSource} |`
mdRows.push(mdTableRow)
localeList[localeName] = `${languageName} (${regionName}${variant ? `, ${variant}` : ''})`
})
const resultingMdTable = mdTable.concat(mdRows.sort()).join('\n').replace('%count%', mdRows.length)
const dstpath = path.join(webRoot, 'src', '_template', 'list_of_locale_packs.md')
const localeListDstPath = path.join(webRoot, 'src', 'examples', 'locale_list.json')
fs.writeFileSync(dstpath, `${resultingMdTable}\n`, 'utf-8')
console.info(chalk.green('✓ injected: '), chalk.grey(dstpath))
fs.writeFileSync(localeListDstPath, JSON.stringify(localeList), 'utf-8')
console.info(chalk.green('✓ injected: '), chalk.grey(localeListDstPath))
}
async function readConfig () {
try {
const buf = await fs.promises.readFile(configPath, 'utf8')
return YAML.safeLoad(buf)
} catch (err) {
return {}
}
}
async function inject () {
const config = await readConfig()
await injectGhStars()
await injectMarkdown()
injectLocaleList()
config.uppy_version = version
config.uppy_version_anchor = version.replace(/[^\d]+/g, '')
await injectSizes(config)
const saveConfig = { ...defaultConfig, ...config }
await fs.promises.writeFile(configPath, YAML.safeDump(saveConfig), 'utf-8')
console.info(chalk.green('✓ rewritten: '), chalk.grey(configPath))
try {
await injectBundles()
} catch (error) {
console.error(
chalk.red('x failed to inject: '),
chalk.grey(`uppy bundle into site, because: ${error}`),
)
process.exit(1)
}
}