-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.js
More file actions
3328 lines (2843 loc) · 108 KB
/
interface.js
File metadata and controls
3328 lines (2843 loc) · 108 KB
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*\
* MIT License
*
*
* Copyright (c) 2023 Meekness Adesina
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
\*/
'use strict';
import fsExtra from 'fs-extra';
const {move: moveAll, copy: duplicate} = fsExtra;
import os from 'node:os';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import readline from 'node:readline/promises';
import zlib from 'node:zlib';
import path from 'node:path';
import process from 'node:process';
import {fileURLToPath} from 'node:url';
import {Transform} from 'node:stream';
import http from 'node:http';
import https from 'node:https';
import jsdom from 'jsdom';
import {rimraf} from 'rimraf';
import util from 'util';
import tar from 'tar';
import yauzl from 'yauzl';
import {dirname} from 'path';
import mimeDB from 'mime-db';
import {isBinary} from 'istextorbinary';
// Import constants
import {
supportedSchemes,
metaTags,
linkTags,
projectDependencyInjectionTags,
selfClosingTags,
reactAttributesLookup,
modifyLock
} from './constants.js';
// Import project information
import {
PROJECT_NAME,
PROJECT_VERSION,
PROJECT_DESCRIPTION
} from './project-info.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const SESSION_ID = randomCounter(8);
const temporaryDir = path.join(os.tmpdir(), PROJECT_NAME, SESSION_ID);
// Logger dependencies
import winston from 'winston';
const {combine, colorize, align, printf, timestamp} = winston.format;
// Assertion dependencies
import assert from 'assert';
// Augmentation constant
const REPL_ID = 'hTmL';
modifyLock(REPL_ID);
// --- Replacement Tags --- //
const STYLE_TAG = 'STYLE_CONTENT';
const APP_TAG = 'APP_CONTENT';
const TITLE_TAG = 'TITLE_CONTENT';
const META_TAG = 'META_CONTENT';
const LINK_TAG = 'LINK_CONTENT';
const ROUTES_TAG = 'ROUTES_CONTENT';
const REACT_IMPORT_TAG = 'REACT_IMPORT';
const PAGE_CONTENT_TAG = 'PAGE_CONTENT';
const PAGE_SCRIPT_TAG = 'PAGE_SCRIPT';
modifyLock(
REPL_ID, STYLE_TAG, APP_TAG, TITLE_TAG, META_TAG, LINK_TAG, ROUTES_TAG,
REACT_IMPORT_TAG, PAGE_CONTENT_TAG, PAGE_SCRIPT_TAG);
const STYLE_INC_TAG = 'STYLE_INCLUDE';
const SCRIPT_INC_TAG = 'SCRIPT_INCLUDE';
const ROUTES_INC_TAG = 'ROUTES_INCLUDE';
const USE_IMPORT_TAG = 'USE_IMPORT';
modifyLock(STYLE_INC_TAG, SCRIPT_INC_TAG, ROUTES_INC_TAG);
const ROOT_ATTR_TAG = 'ROOT_ATTRIBUTES';
modifyLock(ROOT_ATTR_TAG);
const BUILD_DIR_TAG = 'BUILD_DIR';
const ENV_PRE_TAG = 'ENV_PRESENT';
const ASSETS_DIR_TAG = 'ASSETS_DIR';
const ASSETS_PRESENT_TAG = 'ASSET_PRESENT';
const FAVICON_DIR_TAG = 'FAVICON_DIR';
modifyLock(
BUILD_DIR_TAG, ENV_PRE_TAG, ASSETS_DIR_TAG, ASSETS_PRESENT_TAG,
FAVICON_DIR_TAG);
// Inject the meta description and title into App.jsx
const PAGE_ROUTE_TAG = 'PAGE_ROUTE';
const PAGE_NAME_TAG = 'PAGE_NAME';
modifyLock(PAGE_ROUTE_TAG, PAGE_NAME_TAG);
// --- Replacement Tags --- //
const BUILD_DIR = 'build';
const ASSETS_DIR = 'assets';
modifyLock(BUILD_DIR, ASSETS_DIR);
// --- (C|De)ompression -- //
const Decompressor = {
Zip: Symbol('zip'),
Gzip: Symbol('gz|tgz|tar.gz'),
};
const Magic = {
Zip: new Uint8Array([0x50, 0x4B, 0x03, 0x04]),
Gzip: new Uint8Array([0x1F, 0x8B, 0x08]),
};
const MAX_MAGIC_LENGTH = 40;
const MAX_REDIRECT = 5;
// Make it unmodifiable.
modifyLock(Decompressor, Magic);
// --- (C|De)ompression -- //
// --- Logger --- //
// Logger setup
const logger = winston.createLogger({
level: 'error',
format: combine(
timestamp({format: 'YYYY-MM-DD hh:mm:ss.SSS A'}), align(),
printf((info) => {
return `[${info.timestamp}] ${info.level}: ${info.message}`;
})),
transports: [new winston.transports.File({
filename: `logs/progress-${new Date().toISOString().slice(0, 10)}.log`,
maxsize: 1024 * 1024 * 10 // 10MB
})]
});
const {error, warn, info, verbose, debug, silly} = logger;
logger.info = function() {
info(logWrapper(arguments));
};
logger.error = function() {
error(logWrapper(arguments));
};
function logWrapper() {
return util.format.apply(null, arguments);
}
// --- Logger --- //
// This is the projects root directory
let mainSourceDir;
/*\
* The converterConfig was moved
* here so as not to make the assertions
* in the functions trigger during testing
* phase.
\*/
const converterConfig = {
searchDepth: -1,
deduceAssetsFromBasePath: true,
usePathRelativeIndex: true,
archive: true,
entryPoint: 'index.html',
subdirectory: '.',
weakReplacement: false,
useAsciiDisplay: false
};
export async function generateAllPages(config) {
let allPageMetas = [], allStyles = '', allLinks = [], allScripts = [],
allPages = [];
Object.assign(converterConfig, config);
const mainSourceFile = await resolveLandingPage(config.initialPath);
mainSourceDir = getRootDirectory(mainSourceFile, config.initialPath);
/*\
* Program starting point.
* We try to simulate an page element
* since we don't have access to a
* page generator yet.
\*/
const landingPage = {
href: mainSourceFile,
isLanding: true,
...parseFile(mainSourceFile),
dir: '',
};
async function generateAllPagesImpl(pages, resourcePath) {
let pagesStream = [].concat(pages);
let currentPageStyle = '';
const qLookup = {};
const resolvedLinks = {};
try {
for (let i = 0; i < pagesStream.length; ++i) {
const page = pagesStream[i];
const pageID = removeAbsoluteRef(mainSourceDir, page.href);
// Check if we have the page queued already.
if (qLookup[pageID]) {
continue;
}
qLookup[pageID] = true;
/*\
* The landing page has an href property.
* The path to this property is expected
* to be a valid path.
* The other extracted pages already have
* an href property hence, their resolved
* realpath property is used as their real
* location.
\*/
const pageLocationFile = page?.res?.realpath ?? page.href;
const pageLocation = path.dirname(pageLocationFile);
logger.info(
'\n\n', '='.repeat(50), pageLocationFile, '='.repeat(50),
'\n\n');
const content = await fsp.readFile(pageLocationFile);
const dom = new jsdom.JSDOM(content);
const doc = dom.window.document;
const root = doc.querySelector('html');
/*\
* We don't need edited attributes
* since we know that we are not going to
* be loaded in a react sensitive context
\*/
const pageMetas = extractMetas(doc, pageLocation);
const currentPageLinks = extractLinks(doc, pageLocation);
const pageTitle = extractTitle(doc, root);
const otherPages = uniquefyPages(
await extractAllPageLinks(
doc, pageLocationFile, resourcePath),
pagesStream, mainSourceDir);
await reconstructTree(root, pageLocationFile);
const scripts = await extractAllScripts(doc);
const pageStyles = extractStyles(doc);
await updateMissingLinks(
doc, pageLocationFile, resourcePath, currentPageLinks,
scripts);
/*\
* Wrap scripts with anonymous function to
* prevent variables declared in the
* global scope from being redeclared
* when a component is remounted.
\*/
await wrapScriptsWithAnon(scripts, resourcePath);
const pageLinks = uniquefy(
[],
await updateLinksFromLinksContent(
pageLocationFile, resourcePath, currentPageLinks,
resolvedLinks),
'href');
const pageStyle = await updateStyleLinks(
pageLocationFile, resourcePath, pageStyles);
allStyles = strJoin(allStyles, pageStyle, '\n');
// We have to delay the write of the transformed
// html because we need to resolve all pages that
// exists so as to replace their hrefs with an
// onClick handler.
const rawHTML = closeSelfClosingTags(
refitTags(dom.window.document.body.innerHTML));
logger.info('All scripts for page:', page.realpath, scripts);
logger.info('All styles for page:', page.realpath, pageStyles);
const pageDescription = extractDescription(pageMetas);
const pageName =
deriveNameFrom(pageID, {strip: true, suffix: 'Page'});
/*\
* For the initial page, resource info (res) is not
* available since we are simulating it, that is it doesn't
* have an HTMLElement that can be attributed to it.
*
* Remove the `Page` suffix from page name.
\*/
const pageFile = removeBackLinks(
path.join((page.dir ?? ''), pageName.slice(0, -4)) +
'.jsx');
const pageInfo = {
pageID: pageID,
name: pageName,
title: pageTitle,
description: pageDescription,
path: pageFile
};
Object.assign(page, {...page, html: rawHTML, info: pageInfo});
logger.info('PageInfo: ', pageInfo);
const pagePath = getPagePath(page.info.path, resourcePath);
await duplicatePageTemplate(pageFile, resourcePath);
// If this is the landing page
if (i === 0) {
await emplaceRootAttrs(root, resourcePath);
}
/*\
* We use Helmet to resolve scripts, metas and links
* instead of loading them directly into the head.
* This way, we can be sure that the react page
* is as close as possible to the HTML page we
* are generating from, hence, introducing minimal
* errors if any.
\*/
await emplaceTitle(pageTitle, pagePath);
await emplaceMetas(pageMetas, pagePath, resourcePath);
await emplaceLinks(pageLinks, pagePath, resourcePath);
await emplaceScripts(scripts, pagePath, resourcePath);
// Queue newly fetched pages to the stream.
pagesStream = pagesStream.concat(otherPages);
allPages.push(page);
logger.info(
'\n\n', '='.repeat(50), pageLocationFile, '='.repeat(50),
'\n\n');
}
} catch (err) {
console.error(err);
logger.error(err);
throw err;
}
return allPages;
}
try {
await cleanOldFiles();
const processingParams = await initializeProjectStructure();
const allPages =
await generateAllPagesImpl([landingPage], processingParams);
logger.info('allPages: ', allPages);
await emplaceStyles(allStyles, processingParams);
await emplaceApp(allPages, processingParams);
await relinkPages(allPages, processingParams);
await emplaceHTML(allPages, processingParams);
await fixupWebpack(processingParams);
await finalizeWriter(allPages, processingParams);
await removeTemplates(processingParams);
if (converterConfig.archive) {
const {buildB} = processingParams;
assert(isDefined(buildB));
const projectName =
deriveProjectNameFrom(mainSourceDir, SESSION_ID);
await bundleProject(buildB, projectName);
}
} catch (err) {
console.error(
'Unable to generate project:', converterConfig.initialPath);
logger.error(err);
await cleanOldFiles();
await cleanTemporaryFiles();
process.exit(1);
}
// Clear the indexer output
// Move down; clear the line; move up;
// Move cursor to beginning.
process.stdout.write('\x1B[1B\x1B[2K\x1B[1A\x1B[10000D');
await cleanTemporaryFiles();
process.stdout.write(
'\x1B[2KSuccess! Generated projects has been written to `' + BUILD_DIR +
'` directory\n');
process.exit(0);
}
async function resolveLandingPage(providedPath) {
try {
if (isNotDefined(providedPath)) {
throw new Error(strJoin(
'Unable to find entry file: ', converterConfig.entryPoint, ''));
}
// Make sure to create temporary directory
// if we need it.
if (!fs.existsSync(temporaryDir)) {
await fsp.mkdir(temporaryDir, {recursive: true});
}
// The provided path is a directory, we can try to find
// an index file from the path.
if (fs.existsSync(providedPath) &&
fs.statSync(providedPath).isDirectory()) {
return await resolveLandingPage(await findIndexFile(providedPath));
}
if (isAbsoluteURI(providedPath)) {
return await downloadProject(providedPath);
}
const functions = {
[Decompressor.Zip]: unzipProject,
[Decompressor.Gzip]: unGzipProject
};
// Build up an extension lookup for all registered archive file types.
const associations =
Object.values(Decompressor)
.map(
dc => dc.toString()
.replace(/^.+\((.+)\)$/, '$1')
.split('|')
.map(ext => ({[ext]: functions[dc]})))
.flat()
// Sort the listings by extension length in decending order
// so that longer extension names are matched first.
.sort((one, other) => {
const oneLen = Object.keys(one)[0].length;
const otherLen = Object.keys(other)[0].length;
return otherLen < oneLen ? -1 : oneLen === otherLen ? 0 : 1;
})
.reduce((acc, cur) => ({...acc, ...cur}), {});
const {extv2, base} = parseFile(providedPath);
if (extv2 === 'html') {
return providedPath;
}
// Match the longest extension name that can be derived from the
// basename
const ext = Object.keys(associations)
.find(ex => providedPath.slice(-ex.length) === ex);
let selector = associations[ext];
if (isNotDefined(selector)) {
selector = await tryDecodeFromMagic(providedPath, functions);
}
if (selector) {
const dir = await selector(providedPath, ext);
if (isNotDefined(dir)) {
throw new Error(strJoin(
'Could not find', converterConfig.entryPoint,
'file in the provided path', providedPath, ' '));
}
return dir;
}
} catch (err) {
console.error(err.message);
logger.error(err);
process.exit(1);
}
console.error('Unable to resolve provided path:', providedPath);
process.exit(1);
}
async function tryDecodeFromMagic(providedPath, lookup) {
const [size, filePiece] = await readFile(providedPath, MAX_MAGIC_LENGTH);
for (const type of Object.keys(Magic)) {
const magic = Magic[type];
if (size < magic.length) {
continue;
}
const sameSizedBuf = filePiece.slice(0, magic.length);
if (Buffer.from(magic).equals(sameSizedBuf)) {
return lookup[Decompressor[type]];
}
}
}
async function readFile(filepath, maxLength) {
return new Promise(async (resolve, reject) => {
fs.open(filepath, 'r', (oErr, fd) => {
if (oErr) {
reject(oErr);
return;
}
const buffer = new Uint8Array(maxLength);
fs.read(fd, buffer, 0, maxLength, 0, (rErr, read, buffer) => {
if (rErr) {
reject(rErr);
return;
}
resolve([read, buffer]);
});
});
});
}
function getRootDirectory(file, startingPath) {
const dir = path.dirname(file);
if (!isAbsoluteURI(startingPath) &&
fs.statSync(startingPath).isDirectory()) {
/*\
* Check if the initial supplied path
* is parent of the point where the file is found.
\*/
if (path.relative(dir, startingPath).startsWith('..')) {
return startingPath;
}
}
return dir;
}
async function gzipProject(providedPath, outputName) {
return await compressGZipImpl(providedPath, outputName);
}
async function compressGZipImpl(providedPath, finalName) {
assert(fs.existsSync(providedPath));
assert(fs.statSync(providedPath).isDirectory());
const outputFullPath =
path.join(temporaryDir, BUILD_DIR, finalName + '.tar.gz');
await fsp.mkdir(path.dirname(outputFullPath), {recursive: true});
await tar.create(
{gzip: true, file: outputFullPath, cwd: providedPath}, ['']);
return outputFullPath;
}
async function unzipProject(providedPath) {
return await decompressZipOrGzipImpl(providedPath, Decompressor.Zip);
}
async function unGzipProject(providedPath) {
return await decompressZipOrGzipImpl(providedPath, Decompressor.Gzip);
}
async function decompressZipOrGzipImpl(archivePath, decompressor) {
assert(
decompressor === Decompressor.Zip ||
decompressor === Decompressor.Gzip);
const {subdirectory} = converterConfig;
assert(isDefined(subdirectory) && isString(subdirectory));
const decomps = Object.values(Decompressor);
const rootPath = await[decompressZipImpl, decompressGzipImpl].at(
decomps.indexOf(decompressor))(archivePath);
logger.info('rootPath:', rootPath);
let filePath = path.join(temporaryDir, rootPath);
const info = fs.statSync(filePath);
if (info.isDirectory()) {
/*\
* If a subdirectory argument is provided,
* we have to find the entry point in the
* subdirectory provided.
\*/
const extendedFilePath = path.join(filePath, subdirectory);
const extendedIsDirectory = fs.existsSync(extendedFilePath) &&
fs.statSync(extendedFilePath).isDirectory();
if (extendedFilePath === filePath || extendedIsDirectory) {
return findIndexFile(extendedFilePath);
} else {
const shortpath = path.relative(temporaryDir, extendedFilePath);
throw new Error(strJoin(
'Error: provided subdirectory`', shortpath,
'` is not a valid directory.', ''));
}
} else {
// For nested archives such as .tar.gz
// or previously resolved path cyling
// back to this point.
return await resolveLandingPage(filePath);
}
}
async function decompressGzipImpl(archivePath) {
let seenRootDir = false;
let rootDir = '';
let progress = 0;
let receivedBytes = 0;
return new Promise(async (resolve, reject) => {
const readStream = fs.createReadStream(archivePath);
const unzipStream = zlib.createGunzip();
const ext = extensionsOf(archivePath, 2);
/*
* `node-tar` cannot handle recursively compressed
* archives (e.g .zip.gz). Give `node-tar` only
* archives it can process then use the builtin
* zlib facility to deflate .gz archive.
*/
if (ext.indexOf('.tar.gz') !== -1 || ext.indexOf('.tgz') !== -1) {
unzipStream.pipe(tar.extract({
cwd: temporaryDir,
onentry: (entry) => {
[rootDir, seenRootDir] =
checkIfActuallyRoot(rootDir, entry.path);
}
}));
unzipStream.on('finish', async () => {
resolve(seenRootDir ? rootDir : './');
});
} else {
const ext = path.extname(archivePath);
assert(ext === '.gz');
const writeFile = archivePath.slice(0, -ext.length);
const writeStream = fs.createWriteStream(writeFile);
unzipStream.pipe(writeStream);
writeStream.on('error', reject);
unzipStream.on('finish', () => {
resolve(path.relative(temporaryDir, writeFile));
});
}
readStream.pipe(unzipStream);
readStream.on('data', (received) => {
receivedBytes += received.length;
progress =
displayProgress('Extracting', progress, -1, receivedBytes);
});
readStream.on('error', reject);
unzipStream.on('error', reject);
})
};
function extensionsOf(file, level) {
assert(isDefined(file) && isString(file));
assert(isNumber(level) && level >= 1);
let jExt = '';
for (let i = 0; i < level; ++i) {
const {ext} = path.parse(file);
if (isEmpty(ext)) {
return jExt;
}
jExt = ext + jExt;
file = file.slice(0, -ext.length);
}
return jExt;
}
async function decompressZipImpl(archivePath) {
let handleCount = 0;
let rootDir = '';
let seenRootDir = false;
let progress = 0;
let receivedBytes = 0;
return new Promise((resolve, reject) => {
yauzl.open(archivePath, {lazyEntries: true}, async (err, zipfile) => {
if (err) {
reject(err);
return;
}
// track when we've closed all our file handles
function incrementHandleCount() {
handleCount++;
}
function decrementHandleCount() {
handleCount--;
if (handleCount === 0) {
resolve(seenRootDir ? rootDir : './');
}
}
incrementHandleCount();
zipfile.on('close', function() {
decrementHandleCount();
});
zipfile.readEntry();
zipfile.on('entry', async (entry) => {
const destPath = path.join(temporaryDir, entry.fileName);
[rootDir, seenRootDir] =
checkIfActuallyRoot(rootDir, entry.fileName);
logger.info('Processing:', destPath);
if (/\/$/.test(entry.fileName)) {
// directory file names end with '/'
await fsp.mkdir(destPath, {recursive: true});
zipfile.readEntry();
} else {
// ensure parent directory exists
if (!fs.existsSync(path.dirname(destPath))) {
await fsp.mkdir(path.dirname(destPath));
}
zipfile.openReadStream(entry, function(err, readStream) {
if (err) {
reject(err);
return;
}
const filter = new Transform();
filter._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
filter._flush = function(cb) {
cb();
zipfile.readEntry();
};
// pump file contents
const writeStream = fs.createWriteStream(destPath);
incrementHandleCount();
writeStream.on('close', decrementHandleCount);
readStream.pipe(filter).pipe(writeStream);
readStream.on('data', (received) => {
receivedBytes += received.length;
progress = displayProgress(
'Extracting', progress, -1, receivedBytes);
});
});
}
});
});
});
}
/*\
* From continuously calling this function
* with stream of paths, it returns if
* the list of all files passed have the
* same root path. It selects the first
* provided path as the supposed root path
* if it is not provided.
*
* It is useful when decoding compressed
* files. The first read path from the
* compressed files will be the root
* directory if it exists.
\*/
function checkIfActuallyRoot(maybeRootDir, readPath) {
if (isEmpty(maybeRootDir)) {
if (numberOfComponents(readPath) > 1) {
const root = readPath.slice(0, nextOf(0, readPath, path.sep));
maybeRootDir = root;
} else {
maybeRootDir = readPath;
}
}
if (path.relative(maybeRootDir, readPath).startsWith('..')) {
return [maybeRootDir, false];
}
return [maybeRootDir, true];
}
async function findIndexFile(providedPath) {
const {entryPoint} = converterConfig;
assert(isDefined(entryPoint) && isString(entryPoint));
return await findFile(entryPoint, providedPath);
}
async function findFile(filename, providedPath) {
assert(isDefined(filename));
assert(filename === '*' || isString(filename));
async function findFileImpl(initialPath) {
const directoryQueue = [];
const directoryIterator = await fsp.readdir(initialPath);
for (const file of directoryIterator) {
const filePath = path.join(initialPath, file);
const stat = fs.statSync(filePath);
const isDirectory = stat.isDirectory(filePath);
// If we found the file or user
// didn't specify any particular file,
// return the first file found.
if (filename === '*' || file === filename) {
return filePath;
} else if (isDirectory) {
directoryQueue.push(filePath);
}
}
/*\
* Convert a depth-first-search into a
* breadth-first search by keeping the
* next nodes to explore in a queue.
\*/
for (const directory of directoryQueue) {
const file = await findFileImpl(directory);
if (isDefined(file)) {
return file;
}
}
}
const file = await findFileImpl(providedPath);
return file;
}
async function downloadProject(url, original, redirectDepth) {
const {base} = path.parse(original ?? url);
const scheme = url.slice(0, url.indexOf('://'));
assert(scheme === 'http' || scheme === 'https');
const protocol = [http, https].at(scheme === 'https');
const downloadPath = path.join(temporaryDir, base);
let totalBytes = 0, receivedBytes = 0, progress = 0;
return new Promise((resolve, reject) => {
protocol
.get(
url,
(response) => {
const {statusCode} = response;
// We have been redirected
if (statusCode === 302) {
resolve({
redirectUrl: response.headers.location,
depth: redirectDepth ?? 1
});
response.resume();
return;
} else if (statusCode !== 200) {
reject(new Error(
'Error: Request failed with status code: ' +
statusCode));
response.resume();
return;
}
totalBytes = parseInt(
response.headers['content-length'] ?? '-1');
const stream = fs.createWriteStream(downloadPath);
response.pipe(stream);
response.on('data', (chunk) => {
receivedBytes += chunk.length;
progress = displayProgress(
'Downloading', progress, totalBytes,
receivedBytes);
});
stream.on('finish', () => {
stream.close();
resolve({path: downloadPath});
});
stream.on('error', (err) => {
reject(err);
});
response.on('error', (err) => {
reject(err);
});
})
.on('error', (err) => {
if (err.code === 'ETIMEDOUT') {
reject(new Error('Error: Connection timed out'));
return;
} else if (err.code === 'EAI_AGAIN') {
reject(new Error(strJoin(
'Error: Unable to connect to host.',
'Check your internet conectivity and try again.',
'\n')));
}
reject(err);
});
})
.then(/* If we are redirected, recurse with the new path */
(next) => {
if (next.redirectUrl && next.depth <= MAX_REDIRECT) {
return downloadProject(
next.redirectUrl, url, next.depth + 1);
} else if (next.depth > MAX_REDIRECT) {
return Promise.reject(
new Error('Maximum redirection reached'));
} else {
return resolveLandingPage(next.path);
}
});
}
function displayProgress(prefix, progress, total, received) {
const {useAsciiDisplay} = converterConfig;
assert(isDefined(useAsciiDisplay) && isBoolean(useAsciiDisplay));
const LOADING_INDICATORS = 25;
const MOTION_INTERVAL = 70;
const SPACING = 4;
if (total == -1) {
if (progress > 1 && progress % MOTION_INTERVAL !== 0) {
return ++progress;
}
const value = (progress / MOTION_INTERVAL + 1) % LOADING_INDICATORS;
const pointer = useAsciiDisplay ? '*-*-*' : '◉·●·◉';
let indicators =
pointer + '-'.repeat(LOADING_INDICATORS - pointer.length);
indicators =
indicators.slice(-1 * value) + indicators.slice(0, -1 * value);
indicators = '[' + indicators + ']';
const suffix = isDefined(received) ?
' '.repeat(SPACING) + humanReadableFormOf(received) :
'';
process.stdout.write(
`\x1B[2K${prefix}... ` + indicators + suffix + '\x1B[10000D');
return ++progress;
} else {
const suffix =
humanReadableFormOf(received) + ' / ' + humanReadableFormOf(total);
const nBars =
Math.ceil((received * LOADING_INDICATORS / total)) - progress;
// Clean current line;
// Write progress indicator `#`;
// Write the remaining to be filled ` `;
// Write the suffix `1MB / 10MB`;
// Move cursor to start of line;
process.stdout.write(
`\x1B[2K${prefix}... [` +
'#'.repeat(progress + nBars) +
' '.repeat(LOADING_INDICATORS - progress - nBars) + '] ' + suffix +
'\x1B[10000D');
return nBars + progress;
}
}
function humanReadableFormOf(bytes) {
const BYTE_SCALING = 1024;
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const MAX_CONV = 1024 ** (units.length - 1);
const EPSILON = 1e-6;
assert(bytes <= MAX_CONV);
let i;
for (i = 0; bytes >= BYTE_SCALING && i < units.length - 1; i++) {
bytes /= BYTE_SCALING;
}
// If we are close to an integer print the integer without a `.00` suffix
if(bytes - Math.floor(bytes) <= EPSILON)
return `${bytes}${units[i]}`;
return `${bytes.toFixed(2)}${units[i]}`;
}
async function bundleProject(projectPath, projectName) {
const zipFilePath = await gzipProject(projectPath, projectName);
const zipFileNewPath = path.join(projectPath, path.basename(zipFilePath));
await deleteDirectory(projectPath);
await fsp.mkdir(path.dirname(zipFileNewPath), {recursive: true});
await fsp.rename(zipFilePath, zipFileNewPath);
}
async function removeTemplates(resourcePath) {
const {pageB} = resourcePath;
assert(isString(pageB));
const pageTemplateFullPath = path.join(
pageB,
'page-base' +
'.jsx');
logger.info(
'removeTemplates() -- pageTemplateFullPath:', pageTemplateFullPath);
await removePath(pageTemplateFullPath);
}