-
Notifications
You must be signed in to change notification settings - Fork 10
/
bin.ts
217 lines (177 loc) · 6.52 KB
/
bin.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
#!/usr/bin/env node
import { copyFileSync, existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import { extname, resolve } from 'path';
import * as rimraf from 'rimraf';
import { rollup, watch } from 'rollup';
import parseAuthor from 'parse-author';
import copyFiles from './lib/copyFiles';
import parseLibs from './lib/parseLibs';
import rollupConfig from './lib/rollupConfig';
import defaultLibs from './libs.json';
import { minify } from 'html-minifier-terser';
import screenshot from './lib/screenshot';
import { safeName } from './lib/helpers';
import dotenv from 'dotenv';
import type { Module, Library } from './lib/types';
dotenv.config();
const BUILD = process.argv.indexOf('--build') > -1;
const DIR = process.cwd();
const CONFIG = JSON.parse(readFileSync(resolve(DIR, 'package.json'), 'utf8'));
if (!CONFIG) {
throw Error('No package.json file found');
}
const PATH_BUILD = resolve(DIR, './modules');
const PATH_PUBLIC = resolve(DIR, './public');
const PATH_MODULES = resolve(DIR, `./public/modules/${CONFIG.name.replace(/\//g, '-')}`);
const bin = async (): Promise<void> => {
const libs: Record<string, Library> = defaultLibs;
// Remove build outputs
rimraf.sync(PATH_BUILD);
rimraf.sync(PATH_PUBLIC);
// Copy public asset files
await copyFiles(resolve(__dirname, '../public'), PATH_PUBLIC);
// Update index file
let indexFile: string = readFileSync(resolve(PATH_PUBLIC, `index.html`), 'utf8');
// Add optional head content
if (process.env.PATCHCAB_HEAD) {
indexFile = indexFile.replace(`</head>`, `${process.env.PATCHCAB_HEAD}</head>`);
}
// Add optional body content
if (process.env.PATCHCAB_BODY) {
indexFile = indexFile.replace(`</body>`, `${process.env.PATCHCAB_BODY}</body>`);
}
// Update props
const props: Record<string, string> = {};
if (process.env.PATCHCAB_API) {
props['api'] = process.env.PATCHCAB_API;
}
// Check for default rack prop
const rackIndex = process.argv.indexOf('--rack');
const fileName = rackIndex > -1 ? resolve(DIR, process.argv[rackIndex + 1]) : '';
if (existsSync(fileName)) {
const rackContent = readFileSync(fileName, 'utf-8');
props['rack'] = JSON.parse(rackContent);
}
indexFile = await minify(indexFile.replace('props: {}', `props: ${JSON.stringify(props)}`), {
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
});
writeFileSync(resolve(PATH_PUBLIC, `index.html`), indexFile);
// Create empty public modules directory
mkdirSync(PATH_MODULES, { recursive: true });
// Look for patchcab modules in project dependencies and copy those to public modules directory
let dependencies = CONFIG.dependencies ? Object.keys(CONFIG.dependencies) : [];
if (CONFIG.devDependencies) {
dependencies = dependencies.concat(Object.keys(CONFIG.devDependencies));
}
const depModules: Module[] = [];
dependencies.forEach((dependency) => {
try {
const dependencyDir = resolve(DIR, `./node_modules/${dependency}`);
const dependencyConfig =
existsSync(resolve(dependencyDir, `./package.json`)) &&
JSON.parse(readFileSync(resolve(dependencyDir, `./package.json`), 'utf8'));
if (!dependencyConfig || !dependencyConfig.patchcab) {
return;
}
dependencyConfig.patchcab.forEach((item) => {
if (
typeof item === 'object' &&
item.name &&
existsSync(resolve(dependencyDir, `./modules/${safeName(item.name)}.js`))
) {
const setName = dependencyConfig.name.replace(/\//g, '-');
const author =
typeof dependencyConfig.author === 'string'
? parseAuthor(dependencyConfig.author)
: dependencyConfig.author || {};
depModules.push({
set: setName,
name: item.name,
tags: item.tags,
size: item.size,
author,
libs: parseLibs(item.name, item.libs, libs),
});
const targetDir = resolve(DIR, `./public/modules/${setName}/`);
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
copyFileSync(
resolve(dependencyDir, `./modules/${safeName(item.name)}.js`),
resolve(targetDir, `${safeName(item.name)}.js`)
);
copyFileSync(
resolve(dependencyDir, `./modules/${safeName(item.name)}.png`),
resolve(targetDir, `${safeName(item.name)}.png`)
);
}
});
} catch (err) {
console.log(err.message);
}
});
const ownModules: Module[] = [];
const input: Record<string, string> = {};
if (CONFIG.patchcab) {
CONFIG.patchcab.forEach((item) => {
const modulePath = resolve(DIR, `./src/${item.file}`);
input[safeName(item.name)] = extname(modulePath) !== '.svelte' ? `${modulePath}.svelte` : modulePath;
const author = typeof CONFIG.author === 'string' ? parseAuthor(CONFIG.author) : CONFIG.author || {};
ownModules.push({
set: CONFIG.name.replace(/\//g, '-'),
name: item.name,
tags: item.tags,
size: item.size,
author,
libs: parseLibs(item.name, item.libs, libs),
});
});
}
const config = {
...rollupConfig(input, libs, PATH_BUILD),
};
// Write modules files to public directory
writeFileSync(resolve(PATH_PUBLIC, 'modules.json'), JSON.stringify([...depModules, ...ownModules]));
if (CONFIG.patchcab && CONFIG.patchcab.length) {
console.log('Building Patchcab...');
const bundle = await rollup(config);
await bundle.write(config.output);
console.log('Taking screenshots...');
await copyFiles(PATH_BUILD, PATH_MODULES);
await screenshot(ownModules, PATH_BUILD, PATH_PUBLIC);
}
if (BUILD) {
console.log('Patchcab built 🎉');
process.exit();
} else {
console.log('Patchcab running at http://localhost:3000 🚀');
if (CONFIG.patchcab && CONFIG.patchcab.length) {
const watcher = watch(config);
let first = true;
watcher.on('event', async (event) => {
switch (event.code) {
case 'START':
if (!first) {
console.log('Rebuilding Patchcab...');
}
break;
case 'END':
await copyFiles(PATH_BUILD, PATH_MODULES);
if (!first) {
console.log('Done!');
}
first = false;
break;
case 'ERROR':
console.error(event.error);
break;
}
});
} else {
console.log('Patchcab running at http://localhost:3000');
}
}
};
bin();