This repository has been archived by the owner on Aug 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sandbox.js
441 lines (417 loc) · 14.2 KB
/
sandbox.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/env node
const fs = require('fs-extra');
const Axios = require('axios');
const chalk = require('chalk');
const path = require('path');
const http = require('http');
const os = require('os');
const cp = require('child_process');
const yargs = require('yargs');
const _ = require('lodash');
const prompt = require('prompt-sync')({ sigint: true });
const APP_NAME = 'react-sandbox';
const FILES = [
'package.json',
'.eslintignore',
'public/index.html',
'src',
];
const BINARY_EXT = [
'png',
'jpg',
'jpeg'
];
function bufferToBase64DataUrl(buffer, mimeType) {
return 'data:' + mimeType + ';base64,' + buffer.toString('base64');
}
function execGitCommand(context, cmd) {
return cp.execSync(cmd, { cwd: context.fabricPath }).toString()
.replace(/\n/g, ',')
.split(',')
.map(value => value.trim())
.filter(value => value.length > 0);
}
function getGitInfo(context) {
const branch = execGitCommand(context, 'git branch --show-current')[0];
const tag = execGitCommand(context, 'git describe --tags')[0];
const changes = execGitCommand(context, 'git status --porcelain').map(value => {
const [type, path] = value.split(' ');
return { type, path };
});
const userName = execGitCommand(context, 'git config user.name')[0];
return {
branch,
tag,
changes,
user: userName
}
}
/**
* writes the diff files to the app for version control
*/
function writeDiff(context) {
const diffFolder = path.resolve(context.appPath, 'src', 'diff');
const diffPath = path.resolve(diffFolder, 'upstream.diff');
const stagingDiffPath = path.resolve(diffFolder, 'staging.diff');
if (!fs.existsSync(path.resolve(diffFolder))) {
fs.mkdirSync(diffFolder);
}
console.log(`> writing diff files`);
cp.execSync(`git diff upstream/master > ${diffPath}`, { cwd: context.fabricPath });
cp.execSync(`git diff > ${stagingDiffPath}`, { cwd: context.fabricPath });
}
function buildDist(context) {
cp.execSync('node build.js modules=ALL requirejs fast', { cwd: context.fabricPath });
}
function copyBuildToApp(context) {
const fabricSource = path.resolve(context.fabricPath, 'dist', 'fabric.js');
const fabricDest = path.resolve(context.appPath, 'src', 'fabric', 'build.js');
console.log(`> building dist`);
buildDist(context);
let content = fs.readFileSync(fabricSource).toString();
const gitInfo = getGitInfo(context);
content += `\n// fabric react sandbox`;
content += `\n// last git tag ${gitInfo.tag}`;
content += `\nfabric.version='#${gitInfo.tag}';\n`;
fs.writeFileSync(fabricDest, content);
console.log(`> generated ${fabricDest}`);
}
function validateFabricPath(fabricPath) {
if (!fabricPath) return false;
const packagePath = path.resolve(fabricPath, 'package.json');
if (fabricPath && fs.existsSync(fabricPath) && fs.existsSync(packagePath)) {
const packageJSON = require(packagePath);
return packageJSON.name === 'fabric';
}
return false;
}
function promptFabricPath() {
const fabricPath = path.resolve(process.cwd(), prompt('enter the path pointing to fabric folder: '));
if (!validateFabricPath(fabricPath)) {
console.log(chalk.red.bold(`> couldn't find fabric at given path: ${fabricPath}`));
return promptFabricPath();
}
console.log(`> fabric has been found, thanks!`);
return fabricPath;
}
function updateFabricPath(appPath, fabricPath) {
const packagePath = path.resolve(appPath, 'package.json');
const package = require(packagePath);
package.sandboxConfig = { ...package.sandboxConfig, fabric: fabricPath };
fs.writeFileSync(packagePath, JSON.stringify(package, null, '\t'));
}
function ensureFabric(context) {
if (!validateFabricPath(context.fabricPath)) {
let validPath;
const presumedFabricLocation = path.resolve(process.cwd(), '..', 'fabric.js');
if (validateFabricPath(presumedFabricLocation)) {
validPath = presumedFabricLocation;
console.log(`> fabric has been found here: ${validPath}`);
} else {
console.log('> this app relies on fabric to function');
context.fabricPath && console.log(`> couldn't find fabric at given path: ${context.fabricPath}`);
validPath = promptFabricPath();
}
context.fabricPath = validPath;
updateFabricPath(context.appPath, validPath);
}
}
function createReactApp(context) {
const { template, appPath } = context;
if (!fs.existsSync(appPath)) {
const templateDir = process.cwd();
console.log(chalk.blue(`> creating sandbox using cra-template-${template}`));
template === 'js' && console.log(chalk.yellow(`> if you want to use typescript re-run with --typescript flag`));
// patch https://github.com/facebook/create-react-app/issues/11756 by downgrading react-scripts
const args = [appPath, '--template', `file:${path.resolve(templateDir, template)}`, '--scripts-version', '4.0.3'].join(' ');
try {
// bug https://github.com/facebook/create-react-app/issues/5647
cp.execSync(`yarn create react-app --use-pnp ${args}`, {
stdio: 'inherit'
});
} catch (error) {
console.log(chalk.red('\n> failed creating the app with yarn, defaulting to npm'));
fs.rmSync(appPath, { recursive: true, force: true });
cp.execSync(`npx create-react-app ${args}`, {
stdio: 'inherit'
});
}
} else {
console.log(chalk.yellow(`> ${appPath} already exists`));
process.exit(1);
}
}
async function startReactSandbox(context) {
const { appPath, fabricPath } = context;
copyBuildToApp(context);
writeDiff(context);
console.log(chalk.yellow(`\n> watching for changes in fabric ${fabricPath}`));
fs.watch(path.resolve(fabricPath, 'src'), { recursive: true }, _.debounce(() => {
try {
copyBuildToApp(context);
//writeDiff(context);
} catch (error) {
console.log(chalk.blue('> error listening to/building fabric'));
}
}, 500, { trailing: true }));
const port = await createServer(context, 5000);
const packagePath = path.resolve(appPath, 'package.json');
const package = JSON.parse(fs.readFileSync(packagePath).toString());
package.proxy = `http://localhost:${port}`;
fs.writeFileSync(packagePath, JSON.stringify(package, null, '\t'));
try {
cp.spawn('npm', ['run', 'app'], { shell: true, cwd: appPath, stdio: 'inherit' });
} catch (error) {
console.log(chalk.yellow('\n> stopped watching for changes in fabric'));
process.exit(1);
}
}
function createDeployedEnv(context) {
let env = fs.readFileSync(path.resolve(context.appPath, '.env')).toString();
env += '\nREACT_APP_SANDBOX_DEPLOYED=true\n';
return env;
}
/**
* https://codesandbox.io/docs/api/#define-api
*/
async function createCodeSandbox(context, json) {
const { appPath } = context;
copyBuildToApp(context);
writeDiff(context);
const files = {
'.env': { content: createDeployedEnv(context) },
'src/git.json': { content: getGitInfo(context) },
};
const processFile = (fileName) => {
const filePath = path.resolve(appPath, fileName);
const ext = path.extname(fileName).slice(1);
if (fs.lstatSync(filePath).isDirectory()) {
fs.readdirSync(filePath)
.forEach(file => {
processFile(path.join(fileName, file).replace(/\\/g, '/'));
});
} else if (BINARY_EXT.some(x => x === ext)) {
files[fileName] = {
content: bufferToBase64DataUrl(fs.readFileSync(filePath), `image/${ext}`),
isBinary: true
};
} else {
files[fileName] = { content: fs.readFileSync(filePath).toString() };
}
}
FILES.forEach(processFile);
json && (files['src/snapshot.json'] = { content: json });
const isTypescript = fs.existsSync(path.resolve(appPath, 'src', 'App.tsx'));
try {
const { data: { sandbox_id } } = await Axios.post("https://codesandbox.io/api/v1/sandboxes/define?json=1", {
template: isTypescript ? 'create-react-app-typescript' : 'create-react-app',
files
});
const uri = `https://codesandbox.io/s/${sandbox_id}`;
console.log(chalk.yellow(`> created code sandbox ${uri}`));
return uri;
} catch (error) {
throw error.toJSON();
}
}
async function createAndOpenCodeSandbox(context) {
const uri = await createCodeSandbox(context);
runApplication(uri);
}
function runApplication(cmd) {
cp.execSync(`${os.platform().startsWith('win') ? 'start' : 'open'} ${cmd}`);
}
/**
*
* @param {number} [port]
* @returns {Promise<number>} port
*/
function createServer(context, port = 5000) {
const { appPath } = context;
const server = http.createServer(async (req, res) => {
switch (req.url) {
case '/codesandbox':
try {
const json = await new Promise((resolve, reject) => {
let rawData = '';
req.on('data', (chunk) => { rawData += chunk; });
req.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (e) {
reject(e);
}
});
})
const uri = await createCodeSandbox(context, json);
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({ uri }, null, '\t'));
} catch (error) {
res.writeHead(500, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({ error }, null, '\t'));
}
break;
case '/git':
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(getGitInfo(context), null, '\t'));
break;
case '/open-ide':
let appFile = path.resolve(appPath, 'src', 'App.tsx');
if (!fs.existsSync(appFile)) {
appFile = path.resolve(appPath, 'src', 'App.js');
}
if (fs.existsSync(appFile)) {
runApplication(appFile);
}
res.writeHead(200);
res.end();
break;
default:
res.writeHead(400, {
'Content-Type': 'text/plain'
});
res.end(`unknown endpoint ${req.url}`);
break;
}
});
return new Promise((resolve, reject) => {
const initialPort = port;
const listen = () => {
server.listen(port)
.on('listening', () => {
resolve(port);
})
.on('error', (error) => {
server.close();
if (error.code === 'EADDRINUSE' && port - initialPort < 100) {
port++;
listen();
} else {
console.error(error);
reject(error);
process.exit(1);
}
});
};
listen();
}).then(port => {
console.log(chalk.yellow(`> sandbox server is listening on port ${port}`));
return port;
});
}
function runInContext(appPath, cb) {
const package = require(path.resolve(appPath, 'package.json'));
const context = {
appPath,
fabricPath: package.sandboxConfig.fabric,
template: package.sandboxConfig.template
}
ensureFabric(context);
Object.freeze(context);
cb(context);
}
yargs
.scriptName('fabric.js react sandbox')
.usage('$0 <cmd> [args]')
.command('build <app>',
'build the sandbox',
yargs => {
return yargs
.positional('app', {
type: 'string',
describe: 'the path where you want the sandbox to be created at',
default: `./${APP_NAME}`,
})
.option('fabric', {
type: 'string',
describe: 'the path pointing to fabric folder'
})
.option('typescript', {
type: 'boolean',
describe: 'build the sandbox with typescript',
default: false
})
.option('start', {
type: 'boolean',
describe: 'start the sandbox after building has completed',
default: false
});
},
argv => {
const context = {
fabricPath: argv.fabric ? path.resolve(process.cwd(), argv.fabric) : null,
appPath: path.resolve(process.cwd(), argv.app),
template: argv.typescript ? 'ts' : 'js',
}
if (context.fabricPath && !validateFabricPath(context.fabricPath)) {
console.log(chalk.red.bold(`> couldn't find fabric at given path: ${context.fabricPath}`));
process.exit(1);
return;
}
createReactApp(context);
context.fabricPath && updateFabricPath(context.appPath, context.fabricPath);
if (argv.start) {
ensureFabric(context);
startReactSandbox(context);
}
}
)
.command('dev', 'start the dev environment', {}, argv => {
const common = path.resolve(__dirname, 'common', 'template');
const devApp = path.resolve(__dirname, 'dev-sandbox');
const context = {
appPath: devApp,
template: 'ts',
}
if (!fs.existsSync(devApp)) {
createReactApp(context);
}
fs.watch(common, { recursive: true }, (eventType, filename) => {
try {
const src = path.resolve(common, filename);
const dest = path.resolve(devApp, filename);
if (fs.lstatSync(src).isDirectory()) return;
if (fs.existsSync(src)) {
fs.writeFileSync(dest, fs.readFileSync(src));
} else {
fs.unlinkSync(dest);
}
console.log(
`> updated ${filename}${!filename.startsWith('src') ? ', you may need to restart the dev server for changes to take place' : ''}`
);
} catch (error) {
// console.log(error);
}
});
// copy relevant files in case they have changed after the app had been built
fs.copySync(common, devApp, {
filter: (src, dest) => {
return fs.existsSync(dest);
}
});
// update app .env
const envPath = path.resolve(devApp, '.env');
let env = fs.readFileSync(envPath).toString();
env += `\nREACT_APP_TEMPLATE=${context.template}\n`;
fs.writeFileSync(envPath, env);
runInContext(devApp, startReactSandbox);
console.log(chalk.bold(`> Edit files under ./common, they will be written to the app`));
})
.command('start', 'start the sandbox', {}, runInContext.bind(undefined, process.cwd(), startReactSandbox))
.command('deploy', 'deploy to codesandbox.io', {}, runInContext.bind(undefined, process.cwd(), createAndOpenCodeSandbox))
.command('serve', 'start the sandbox server', {}, runInContext.bind(undefined, process.cwd(), async context => {
const port = await createServer(context);
runApplication(`http://localhost:${port}`);
})
)
.help()
.demandCommand()
.recommendCommands()
.strict()
.argv;