-
Notifications
You must be signed in to change notification settings - Fork 5
/
services.ts
3720 lines (3709 loc) · 224 KB
/
services.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
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
/*jslint node:true */
/*eslint-env node*/
/*eslint no-console: 0*/
/* This file exists to consolidate the various Node service offerings in
this application. */
import { Stats } from "fs";
import * as http from "http";
type directoryItem = [string, "file" | "directory" | "link" | "screen", number, number, Stats];
interface directoryList extends Array<directoryItem> {
[key:number]: directoryItem;
}
(function node() {
"use strict";
const startTime:[number, number] = process.hrtime(),
node = {
child : require("child_process").exec,
crypto: require("crypto"),
fs : require("fs"),
http : require("http"),
https : require("https"),
os : require("os"),
path : require("path")
},
cli:string = process.argv.join(" "),
sep:string = node.path.sep,
projectPath:string = (function node_project() {
const dirs:string[] = __dirname.split(sep);
return dirs.slice(0, dirs.length - 1).join(sep) + sep;
}()),
js:string = `${projectPath}js${sep}`,
libFiles:string[] = [`${js}lexers`, `${js}libs`],
text:any = {
angry : "\u001b[1m\u001b[31m",
blue : "\u001b[34m",
bold : "\u001b[1m",
clear : "\u001b[24m\u001b[22m",
cyan : "\u001b[36m",
diffchar : "\u001b[1m\u001b[4m",
green : "\u001b[32m",
nocolor : "\u001b[39m",
none : "\u001b[0m",
purple : "\u001b[35m",
red : "\u001b[31m",
underline: "\u001b[4m",
yellow : "\u001b[33m"
},
commands:commandList = {
build: {
description: "Rebuilds the application.",
example: [
{
code: "sparser build",
defined: "Compiles from TypeScript into JavaScript and puts libraries together."
},
{
code: "sparser build incremental",
defined: "Use the TypeScript incremental build, which takes about half the time."
},
{
code: "sparser build local",
defined: "The default behavior assumes TypeScript is installed globally. Use the 'local' argument if TypeScript is locally installed in node_modules."
}
]
},
commands: {
description: "List all supported commands to the console or examples of a specific command.",
example: [
{
code: "sparser commands",
defined: "Lists all commands and their definitions to the shell."
},
{
code: "sparser commands directory",
defined: "Details the mentioned command with examples."
}
]
},
debug: {
description: "Prepares a formal report in markdown format with information to assist in troubleshooting.",
example: [{
code: "sparser debug",
defined: "Generates markdown format report directly to standard output."
}]
},
directory: {
description: "Traverses a directory in the local file system and generates a list.",
example: [
{
code: "sparser directory source:\"my/directory/path\"",
defined: "Returns an array where each index is an array of [absolute path, type, parent index, file count, stat]. Type can refer to 'file', 'directory', or 'link' for symbolic links. The parent index identify which index in the array is the objects containing directory and the file count is the number of objects a directory type object contains."
},
{
code: "sparser directory source:\"my/directory/path\" shallow",
defined: "Does not traverse child directories."
},
{
code: "sparser directory source:\"my/directory/path\" listonly",
defined: "Returns an array of strings where each index is an absolute path"
},
{
code: "sparser directory source:\"my/directory/path\" symbolic",
defined: "Identifies symbolic links instead of the object the links point to"
},
{
code: "sparser directory source:\"my/directory/path\" ignore [.git, node_modules, \"program files\"]",
defined: "Sets an exclusion list of things to ignore"
},
{
code: "sparser directory source:\"my/path\" typeof",
defined: "returns a string describing the artifact type"
}
]
},
get: {
description: "Retrieve a resource via an absolute URI.",
example: [
{
code: "sparser get http://example.com/file.txt",
defined: "Gets a resource from the web and prints the output to the shell."
},
{
code: "sparser get http://example.com/file.txt path/to/file",
defined: "Get a resource from the web and writes the resource as UTF8 to a file at the specified path."
}
]
},
help: {
description: "Introductory information to Sparser on the command line.",
example: [{
code: "sparser help",
defined: "Writes help text to shell."
}]
},
inventory : {
description: "List the currently supplied lexers and their language's in language specific logic.",
example: [{
code: "sparser inventory",
defined: "The generated list is computed by scraping the code for the 'options.language' data property. This means the specified supported languages are languages that demand unique instructions. Other languages that aren't in this list may also be supported. This command accepts no options."
}]
},
lint: {
description: "Use ESLint against all JavaScript files in a specified directory tree.",
example: [
{
code: "sparser lint ../tools",
defined: "Lints all the JavaScript files in that location and in its subdirectories."
},
{
code: "sparser lint",
defined: "Specifying no location defaults to the Sparser application directory."
},
{
code: "sparser lint ../tools ignore [node_modules, .git, test, units]",
defined: "An ignore list is also accepted if there is a list wrapped in square braces following the word 'ignore'."
}
]
},
options: {
description: "List all Sparser's options to the console or gather instructions on a specific option.",
example: [
{
code: "sparser options",
defined: "List all options and their definitions to the shell."
},
{
code: "sparser options performance",
defined: "Writes details about the specified option to the shell."
},
{
code: "sparser options type:boolean lexer:script values",
defined: "The option list can be queried against key and value (if present) names. This example will return only options that work with the script lexer, takes specific values, and aren't limited to a certain API environment."
}
]
},
parse: {
description: "Parses a file and returns to standard output.",
example: [
{
code: "sparser parse tsconfig.json",
defined: "Runs the parse job against a file system object returns to standard output."
},
{
code: "sparser parse libs",
defined: "The job can run against files in a directory."
},
{
code: "sparser parse libs ignore [node_modules, .git, test, units]",
defined: "Ignore file system objects by name using the ignore argument and a comma separated list in square braces."
},
{
code: "sparser parse tsconfig.json format:output quote_convert:double",
defined: "Options are accepted as separated arguments to the standard input."
},
{
code: "sparser parse tsconfig.json format:output quote_convert:double output:filepath",
defined: "Instead of standard output the result can be written to a file if using the 'output' argument. If there is nothing at the path specified a file will be created. If a file already exists at that location it will be overwritten. If something exists at the specified location that isn't a file an error will be thrown."
}
]
},
performance: {
description: "Executes the Sparser application 11 times. The first execution is dropped and the remaining 10 are averaged. Specify a complete Sparser terminal command.",
example: [
{
code: "sparser performance parse source:\"js/services.js\" method_chain:3",
defined: "Just specify the actual command to execute. Sparser will execute the provided command as though the 'performance' command weren't there."
},
{
code: "sparser performance lint js/lexers",
defined: "The command to test may be any command supported by Sparser's terminal services."
}
]
},
server: {
description: "Launches a HTTP service and web sockets so that the web tool is automatically refreshed once code changes in the local file system.",
example: [
{
code: "sparser server",
defined: "Launches the server on default port 9999 and web sockets on port 10000."
},
{
code: "sparser server 8080",
defined: "If a numeric argument is supplied the web server starts on the port specified and web sockets on the following port."
}
]
},
simulation: {
description: "Launches a test runner to execute the various commands of the services file.",
example: [{
code: "sparser simulation",
defined: "Runs tests against the commands offered by the services file."
}]
},
sparser_debug: {
description: "Generates a debug statement in markdown format.",
example: [{
code: "sparser sparser_debug",
defined: "Produces a report directly to the shell that can be copied to anywhere else. This report contains environmental details."
}]
},
test: {
description: "Builds the application and then runs all the test commands",
example: [{
code: "sparser test",
defined: "After building the code, it will lint the JavaScript output, test Node.js commands as simulations, and validate the Sparser code units against test samples."
}]
},
testprep: {
description: "Produces a formatted parse table for the validation test cases.",
example: [{
code: "sparser testprep test/sample_code/script/jsx_recurse.txt",
defined: "Produces a parse table for the specified file where each line is a record in object format."
}]
},
validation: {
description: "Runs Sparser against various code samples and compares the generated output against known good output looking for regression errors.",
example: [{
code: "sparser validation",
defined: "Runs the unit test runner against Sparser"
}]
},
version: {
description: "Prints the current version number and date of prior modification to the console.",
example: [{
code: "sparser version",
defined: "Prints the current version number and date to the shell."
}]
}
},
exclusions = (function node_exclusions():string[] {
const args = process.argv.join(" "),
match = args.match(/\signore\s*\[/);
if (match !== null) {
const list:string[] = [],
listBuilder = function node_exclusions_listBuilder():void {
do {
if (process.argv[a] === "]" || process.argv[a].charAt(process.argv[a].length - 1) === "]") {
if (process.argv[a] !== "]") {
list.push(process.argv[a].replace(/,$/, "").slice(0, process.argv[a].length - 1));
}
process.argv.splice(igindex, (a + 1) - igindex);
break;
}
list.push(process.argv[a].replace(/,$/, ""));
a = a + 1;
} while (a < len);
};
let a:number = 0,
len:number = process.argv.length,
igindex:number = process.argv.indexOf("ignore");
if (igindex > -1 && igindex < len - 1 && process.argv[igindex + 1].charAt(0) === "[") {
a = igindex + 1;
if (process.argv[a] !== "[") {
process.argv[a] = process.argv[a].slice(1).replace(/,$/, "");
}
listBuilder();
} else {
do {
if (process.argv[a].indexOf("ignore[") === 0) {
igindex = a;
break;
}
a = a + 1;
} while (a < len);
if (process.argv[a] !== "ignore[") {
process.argv[a] = process.argv[a].slice(7);
if (process.argv[a].charAt(process.argv[a].length - 1) === "]") {
list.push(process.argv[a].replace(/,$/, "").slice(0, process.argv[a].length - 1));
} else {
listBuilder();
}
}
}
return list;
}
return [];
}()),
performance:performance = {
codeLength: 0,
diff: "",
end: [0,0],
index: 0,
source: "",
start: [0,0],
store: [],
test: false
},
apps:any = {},
args = function node_args():void {
const readOptions = function node_args_readOptions():void {
const list:string[] = process.argv,
def:optionDef = sparser.libs.optionDef,
keys:string[] = (command === "options")
? Object.keys(def.format)
: [],
obj = (command === "options")
? def.format
: options,
optionName = function node_args_optionName(bindArgument:boolean):void {
if (a === 0 || options[list[a]] === undefined) {
if (keys.indexOf(list[a]) < 0 && def[list[a]] === undefined) {
list.splice(a, 1);
len = len - 1;
a = a - 1;
}
return;
}
if (bindArgument === true && list[a + 1] !== undefined && list[a + 1].length > 0) {
list[a] = `${list[a]}:${list[a + 1]}`;
list.splice(a + 1, 1);
len = len - 1;
}
list.splice(0, 0, list[a]);
list.splice(a + 1, 1);
};
let split:string = "",
value:string = "",
name:string = "",
a:number = 0,
si:number = 0,
len:number = list.length;
do {
list[a] = list[a].replace(/^(-+)/, "");
if (list[a] === "verbose") {
verbose = true;
list.splice(a, 1);
len = len - 1;
a = a - 1;
} else {
si = list[a].indexOf("=");
if (
si > 0 &&
(list[a].indexOf("\"") < 0 || si < list[a].indexOf("\"")) &&
(list[a].indexOf("'") < 0 || si < list[a].indexOf("'")) &&
(si < list[a].indexOf(":") || list[a].indexOf(":") < 0)
) {
split = "=";
} else {
split = ":";
}
if (list[a + 1] === undefined) {
si = 99;
} else {
si = list[a + 1].indexOf(split);
}
if (
obj[list[a]] !== undefined &&
list[a + 1] !== undefined &&
obj[list[a + 1]] === undefined &&
(
si < 0 ||
(si > list[a + 1].indexOf("\"") && list[a + 1].indexOf("\"") > -1) ||
(si > list[a + 1].indexOf("'") && list[a + 1].indexOf("'") > -1)
)
) {
if (command === "options") {
optionName(true);
} else {
options[list[a]] = list[a + 1];
a = a + 1;
}
} else if (list[a].indexOf(split) > 0 || (list[a].indexOf(split) < 0 && list[a + 1] !== undefined && (list[a + 1].charAt(0) === ":" || list[a + 1].charAt(0) === "="))) {
if (list[a].indexOf(split) > 0) {
name = list[a].slice(0, list[a].indexOf(split)).toLowerCase();
value = list[a].slice(list[a].indexOf(split) + 1);
} else {
name = list[a].toLowerCase();
value = list[a + 1].slice(1);
list.splice(a + 1, 1);
len = len - 1;
}
if (command === "options") {
if (keys.indexOf(name) > -1) {
if (value !== undefined && value.length > 0) {
list[a] = `${name}:${value}`;
} else {
list[a] = name;
}
} else {
list.splice(a, 1);
len = len - 1;
}
} else if (options[name] !== undefined) {
if (value === "true" && def[name].type === "boolean") {
options[name] = true;
} else if (value === "false" && def[name].type === "boolean") {
options[name] = false;
} else if (isNaN(Number(value)) === false && def[name].type === "number") {
options[name] = Number(value);
} else if (def[name].values !== undefined && def[name].values[value] !== undefined) {
options[name] = value;
} else if (def[name].values === undefined) {
options[name] = value;
}
}
} else if (command === "options") {
optionName(false);
}
}
a = a + 1;
} while (a < len);
if (options.source === "" && process.argv.length > 0 && process.argv[0].indexOf("=") < 0 && process.argv[0].replace(/^[a-zA-Z]:\\/, "").indexOf(":") < 0) {
if (command === "performance") {
options.source = (process.argv.length < 1)
? ""
: process.argv[1];
} else {
options.source = process.argv[0];
}
}
};
options = sparser.options;
options.api = "node";
options.binary_check = (
// eslint-disable-next-line
/\u0000|\u0001|\u0002|\u0003|\u0004|\u0005|\u0006|\u0007|\u000b|\u000e|\u000f|\u0010|\u0011|\u0012|\u0013|\u0014|\u0015|\u0016|\u0017|\u0018|\u0019|\u001a|\u001c|\u001d|\u001e|\u001f|\u007f|\u0080|\u0081|\u0082|\u0083|\u0084|\u0085|\u0086|\u0087|\u0088|\u0089|\u008a|\u008b|\u008c|\u008d|\u008e|\u008f|\u0090|\u0091|\u0092|\u0093|\u0094|\u0095|\u0096|\u0097|\u0098|\u0099|\u009a|\u009b|\u009c|\u009d|\u009e|\u009f/g
);
if (process.argv.length > 0) {
readOptions();
}
apps[command]();
};
let verbose:boolean = false,
errorflag:boolean = false,
command:string = (function node_command():string {
let comkeys:string[] = Object.keys(commands),
filtered:string[] = [],
a:number = 0,
b:number = 0;
if (process.argv[2] === undefined) {
console.log("");
console.log("Sparser requires a command. Try:");
console.log(`global install - ${text.cyan}sparser help${text.none}`);
console.log(`local install - ${text.cyan}node js/services help${text.none}`);
console.log("");
console.log("To see a list of commands try:");
console.log(`global install - ${text.cyan}sparser commands${text.none}`);
console.log(`local install - ${text.cyan}node js/services commands${text.none}`);
console.log("");
process.exit(1);
return;
}
const arg:string = process.argv[2],
boldarg:string = text.angry + arg + text.none,
len:number = arg.length + 1,
commandFilter = function node_command_commandFilter(item:string):boolean {
if (item.indexOf(arg.slice(0, a)) === 0) {
return true;
}
return false;
};
if (process.argv[2] === "debug") {
process.argv = process.argv.slice(3);
return "debug";
}
process.argv = process.argv.slice(3);
// trim empty values
b = process.argv.length;
do {
if (process.argv[a] === "") {
process.argv.splice(a, 1);
b = b - 1;
}
a = a + 1;
} while (a < b);
// filter available commands against incomplete input
a = 1;
do {
filtered = comkeys.filter(commandFilter);
a = a + 1;
} while (filtered.length > 1 && a < len);
if (filtered.length < 1 || (filtered[0] === "debug" && filtered.length < 2)) {
console.log(`Command ${boldarg} is not a supported command.`);
console.log("");
console.log("Please try:");
console.log(` ${text.angry}*${text.none} globally installed - ${text.cyan}sparser commands${text.none}`);
console.log(` ${text.angry}*${text.none} locally installed - ${text.cyan}node js/services commands${text.none}`);
console.log("");
process.exit(1);
return "";
}
if (filtered.length > 1 && comkeys.indexOf(arg) < 0) {
console.log(`Command '${boldarg}' is ambiguous as it could refer to any of: [${text.cyan + filtered.join(", ") + text.none}]`);
process.exit(1);
return "";
}
if (arg !== filtered[0]) {
console.log("");
console.log(`${boldarg} is not a supported command. Sparser is assuming command ${text.bold + text.cyan + filtered[0] + text.none}.`);
console.log("");
}
return filtered[0];
}()),
sparser:sparser,
options:any = {},
writeflag:string = ""; // location of written assets in case of an error and they need to be deleted
(function node_sparsertest():void {
node.fs.stat(`${js}parse.js`, function node_sparsertest_stat(ers:Error) {
if (ers !== null) {
let err:string = ers.toString();
if (err.indexOf("no such file or directory") > 0) {
if (command === "build") {
global.sparser = (function node_sparsertest_stat_dummy():sparser {
let func:any = function () {};
func.lexers = {};
func.libs = {};
func.options = {};
func.parse = {};
func.parseerror = "";
func.version = {
date: "",
number: ""
};
return func;
}());
require(`${js}libs${sep}options.js`);
sparser = global.sparser;
args();
} else {
console.log(`The file js/parse.js has not been written. Please run the build: ${text.cyan}node js/services build${text.none}`);
process.exit(1);
return;
}
} else {
console.log(err);
process.exit(1);
return;
}
} else {
sparser = require(`${js}parse.js`);
args();
}
});
}());
// build/test system
apps.build = function node_apps_build(test:boolean):void {
let firstOrder:boolean = true,
sectionTime:[number, number] = [0, 0],
langlist:{} = {};
const order = {
build: [
"npminstall",
"typescript",
"libraries",
"inventory",
"demo",
"options_markdown",
"docshtml"
],
test: [
"lint",
"simulation",
"validation"
]
},
type:string = (test === true)
? "test"
: "build",
orderlen:number = order[type].length,
def:optionDef = sparser.libs.optionDef,
optkeys:string[] = Object.keys(def),
keyslen:number = optkeys.length,
// a short title for each build/test phase
heading = function node_apps_build_heading(message:string):void {
if (firstOrder === true) {
console.log("");
firstOrder = false;
} else if (order[type].length < orderlen) {
console.log("________________________________________________________________________");
console.log("");
}
console.log(text.cyan + message + text.none);
console.log("");
},
// indicates how long each phase took
sectionTimer = function node_apps_build_sectionTime(input:string):void {
let now:string[] = input.replace(`${text.cyan}[`, "").replace(`]${text.none} `, "").split(":"),
numb:[number, number] = [(Number(now[0]) * 3600) + (Number(now[1]) * 60) + Number(now[2].split(".")[0]), Number(now[2].split(".")[1])],
difference:[number, number],
times:string[] = [],
time:number = 0,
str:string = "";
difference = [numb[0] - sectionTime[0], (numb[1] + 1000000000) - (sectionTime[1] + 1000000000)];
sectionTime = numb;
if (difference[1] < 0) {
difference[0] = difference[0] - 1;
difference[1] = difference[1] + 1000000000;
}
if (difference[0] < 3600) {
times.push("00");
} else {
time = Math.floor(difference[0] / 3600);
difference[0] = difference[0] - (time * 3600);
if (time < 10) {
times.push(`0${time}`);
} else {
times.push(String(time));
}
}
if (difference[0] < 60) {
times.push("00");
} else {
time = Math.floor(difference[0] / 60);
difference[0] = difference[0] - (time * 60);
if (time < 10) {
times.push(`0${time}`);
} else {
times.push(String(time));
}
}
if (difference[0] < 1) {
times.push("00");
} else if (difference[0] < 10) {
times.push(`0${difference[0]}`);
} else {
times.push(String(difference[0]));
}
str = String(difference[1]);
if (str.length < 9) {
do {
str = `0${str}`;
} while (str.length < 9);
}
times[2] = `${times[2]}.${str}`;
console.log(`${text.cyan + text.bold}[${times.join(":")}]${text.none} ${text.green}Total section time.${text.none}`);
},
// the transition to the next phase or completion
next = function node_apps_build_next(message:string):void {
let phase = order[type][0],
time:string = apps.humantime(false);
if (message !== "") {
console.log(time + message);
sectionTimer(time);
}
if (order[type].length < 1) {
verbose = true;
heading(`${text.none}All ${text.green + text.bold + type + text.none} tasks complete... Exiting clean!\u0007`);
apps.log([""]);
process.exit(0);
return;
}
order[type].splice(0, 1);
phases[phase]();
},
// if content should be injected between two points of a file
injection = function node_apps_build_injection(inject:inject):string {
const thirds:[string, string, string] = [
inject.file.slice(0, inject.file.indexOf(inject.start) + inject.start.length) + node.os.EOL,
inject.message,
inject.file.slice(inject.file.indexOf(inject.end))
];
return thirds.join("");
},
// These are all the parts of the execution cycle, but their order is dictated by the 'order' object.
phases = {
// add version and option data to the demo tool html
demo: function node_apps_build_demo():void {
heading("Adding version and options to the demo tool");
node.fs.readFile(`${projectPath}demo${sep}index.xhtml`, "utf8", function node_apps_build_demo_read(er:Error, html:string):void {
const opts:string[] = ["<ul>"];
let a:number = 0,
b:number = 0,
optName:string = "",
opt:option,
vals:string[] = [],
vallen:number = 0,
select:boolean = false;
if (er !== null) {
apps.errout([er.toString()]);
return;
}
do {
optName = optkeys[a];
if (optName !== "source") {
opt = def[optName];
opts.push(`<li id="${optName}">`);
if (opt.type === "boolean") {
opts.push(`<h3>${opt.label}</h3>`);
if (opt.default === true) {
opts.push(`<span><input type="radio" id="option-false-${optName}" name="option-${optName}" value="false"/> <label for="option-false-${optName}">false</label></span>`);
opts.push(`<span><input type="radio" checked="checked" id="option-true-${optName}" name="option-${optName}" value="true"/> <label for="option-true-${optName}">true</label></span>`);
} else {
opts.push(`<span><input type="radio" checked="checked" id="option-false-${optName}" name="option-${optName}" value="false"/> <label for="option-false-${optName}">false</label></span>`);
opts.push(`<span><input type="radio" id="option-true-${optName}" name="option-${optName}" value="true"/> <label for="option-true-${optName}">true</label></span>`);
}
select = false;
} else {
opts.push(`<h3><label for="option-${optName}" class="label">${opt.label}</label></h3>`);
if (opt.type === "number" || (opt.type === "string" && opt.values === undefined)) {
if (optName === "language" || optName === "lexer") {
opts.push(`<input type="text" id="option-${optName}" value="auto" data-type="${opt.type}"/>`);
} else {
opts.push(`<input type="text" id="option-${optName}" value="${opt.default}" data-type="${opt.type}"/>`);
}
select = false;
} else {
opts.push(`<select id="option-${optName}">`);
if (optName === "format") {
opts.push("<option data-description=\"html\" selected=\"selected\">html</option>");
}
vals = Object.keys(opt.values);
vallen = vals.length;
b = 0;
do {
opts.push(`<option data-description="${opt.values[vals[b]].replace(/"/g, """)}" ${
(opt.default === vals[b] && optName !== "format")
? "selected=\"selected\""
: ""
}>${vals[b]}</option>`);
b = b + 1;
} while (b < vallen);
opts.push(`</select>`);
select = true;
}
}
opts.push("<table><tbody>");
opts.push(`<tr><th>Name</th><td class="option-name">${optName}</td></tr>`);
opts.push(`<tr><th>Type</th><td>${def[optName].type}</td></tr>`);
opts.push(`<tr><th>Default</th><td>${def[optName].default.toString()}</td></tr>`);
opts.push("<tr><th>Usage</th><td class=\"option-usage\">");
if (def[optName].lexer[0] === "all") {
opts.push(`options.${optName}`);
} else {
b = 0;
vallen = def[optName].lexer.length;
if (vallen < 2) {
opts.push(`options.lexer_options.<strong>${def[optName].lexer[b]}</strong>.${optName}`);
} else {
vals = [];
do {
vals.push(`<span>options.lexer_options.<strong>${def[optName].lexer[b]}</strong>.${optName}</span>`);
b = b + 1;
} while (b < vallen);
opts.push(vals.join(""));
}
}
opts.push("</td></tr>");
opts.push(`<tr><th>Description</th><td class="option-description">${opt.definition.replace(/"/g, """)}`);
if (select === true) {
if (optName === "format") {
opts.push(` <span>• <strong>html</strong> — Renders the output into an HTML table. This option value is only available in this demo tool.</span>`);
} else if (opt.values[String(opt.default)].indexOf("example: ") > 0) {
opts.push(` <span>• <strong>${opt.default}</strong> — ${opt.values[String(opt.default)].replace("example: ", "example: <code>").replace(/\.$/, "</code>.")}</span>`);
} else {
opts.push(` <span>• <strong>${opt.default}</strong> — ${opt.values[String(opt.default)]}</span>`);
}
}
opts.push("</td></tr></tbody></table>");
opts.push(`</li>`);
}
a = a + 1;
} while (a < keyslen);
opts.push("</ul>");
html = injection({
end: "<!-- option data end -->",
file: html.replace(/<p\s+class="version">\d+\.\d+\.\d+<\/p>/, `<p class="version">${sparser.version.number}</p>`),
message: opts.join(""),
start: "<!-- option data start -->"
});
node.fs.writeFile(`${projectPath}demo${sep}index.xhtml`, html, {
encoding: "utf8"
}, function node_apps_build_demo_read_write(erw:Error):void {
if (erw !== null) {
apps.errout([erw.toString()]);
return;
}
next(`${text.green}Demo tool updated with currention options and version number.${text.none}`);
});
});
},
// phase documentation_html builds documentation in HTML format from the markdown files
docshtml: function node_apps_build_docshtml():void {
heading("Converting documentation from markdown to HTML.");
node.fs.readdir(`${projectPath}docs-markdown`, "utf8", function node_apps_build_docshtml_readdir(er:Error, filelist:string[]):void {
let lexerLinks:string = "",
total:number = 0,
a:number = 0;
const list:[string, boolean][] = [],
newDir = function node_apps_build_docshtml_newDir(path:string, callback:Function):void {
node.fs.stat(path, function node_apps_build_docshtml_stat(ers:nodeError, stat:Stats):void {
if (ers !== null) {
if (ers.code === "ENOENT") {
node.fs.mkdir(path, function node_apps_build_docshtml_stat_mkdir(erm:Error):void {
if (erm !== null) {
apps.errout([erm.toString()]);
return;
}
callback();
});
} else {
apps.errout([ers.toString()]);
}
return;
}
if (stat.isDirectory() === false) {
apps.errout([`Path ${path + text.angry}exists but is not a directory${text.none}!`]);
return;
}
callback();
});
},
lexers = function node_apps_build_docshtml_lexers():void {
filelist.forEach(function node_apps_build_docshtml_lexers(value:string):void {
list.push([value, false]);
});
node.fs.readdir(`${projectPath}lexers`, function node_apps_build_docshtml_lexers_readdir(erd:Error, lexerList:string[]):void {
if (erd !== null) {
apps.errout([erd.toString()]);
return;
}
let b:number = lexerList.length,
c:number = 0;
const links:string[] = ["<li>Lexers <ol>"];
lexerList.sort();
do {
b = b - 2;
c = b;
if ((/\.md$/).test(lexerList[b + 1]) === true) {
c = b + 1;
} else if ((/\.md$/).test(lexerList[b]) === false) {
apps.errout([`Lexer file ${lexerList[b]} does not have a matching markdown documentation file.`, "The markdown file must share the same file name as the corresponding lexer file except for file extension."]);
return;
}
list.push([lexerList[c], true]);
links.push(`<li><a href="lexers/${lexerList[c].replace(".md", ".xhtml")}">${lexerList[c].replace(".md", "")}</a></li>`);
} while (b > 0);
links.push("</ol></li>");
lexerLinks = links.join("");
total = list.length;
convert(list[a]);
});
},
convert = function node_apps_build_docshtml_readdir_convert(fileitem:[string, boolean]) {
let fileOutput:string = "";
const readPath = (fileitem[1] === true)
? `${projectPath}lexers${sep + fileitem[0]}`
: `${projectPath}docs-markdown${sep + fileitem[0]}`,
writePath = (fileitem[1] === true)
? `${projectPath}docs-html${sep}lexers${sep + fileitem[0].replace(".md", ".xhtml")}`
: `${projectPath}docs-html${sep + fileitem[0].replace(".md", ".xhtml")}`;
options.lexer = "markdown";
node.fs.readFile(readPath, "utf8", function node_apps_build_docshtml_readdir_convert_readfile(erf:Error, filedata:string):void {
const doc:string[] = [],
attribute = function node_apps_build_docshtml_readdir_convert_readfile_attribute():void {
const index = doc.length - 1,
add = function node_apps_build_docshtml_readdir_convert_readfile_attribute_add(ending:string):string {
return ` ${parse.token[b].replace(/\.md"$/, ".xhtml\"") + ending}`;
};
doc[index] = doc[index].replace(/\/?>$/, add);
};
let parse:data,
b:number = 1,
len:number = 0;
if (erf !== null) {
apps.errout([erf.toString()]);
return;
}
options.source = filedata;
parse = sparser.parser();
len = parse.token.length - 1;
doc.push("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE html><html xml:lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<!-- Automatically generated file. Do not manually alter! -->\n\n<head><title>");
doc.push("Sparser");
doc.push("</title> <link href=\"https://sparser.io/docs-html/");
if (fileitem[1] === true) {
doc.push("lexers/");
}
doc.push(fileitem[0].replace(".md", ".xhtml"));
doc.push("\" rel=\"canonical\" type=\"application/xhtml+xml\"/> <meta content=\"width=device-width, initial-scale=1\" name=\"viewport\"/> <meta content=\"index, follow\" name=\"robots\"/> <meta content=\"Sparser - Universal Parser\" name=\"DC.title\"/> <meta content=\"#fff\" name=\"theme-color\"/> <meta content=\"Austin Cheney\" name=\"author\"/> <meta content=\"Sparser is a programming language parsing utility that can interpret many different languages using a single simple data model.\" name=\"description\"/> <meta content=\"Global\" name=\"distribution\"/> <meta content=\"en\" http-equiv=\"Content-Language\"/> <meta content=\"application/xhtml+xml;charset=UTF-8\" http-equiv=\"Content-Type\"/> <meta content=\"blendTrans(Duration=0)\" http-equiv=\"Page-Enter\"/> <meta content=\"blendTrans(Duration=0)\" http-equiv=\"Page-Exit\"/> <meta content=\"text/css\" http-equiv=\"content-style-type\"/> <meta content=\"application/javascript\" http-equiv=\"content-script-type\"/> <meta content=\"google515f7751c9f8a155\" name=\"google-site-verification\"/> <meta content=\"#bbbbff\" name=\"msapplication-TileColor\"/> <link href=\"/website.css\" media=\"all\" rel=\"stylesheet\" type=\"text/css\"/> </head><body id=\"documentation\"><div id=\"top_menu\"><h1><a href=\"/\">Sparser</a></h1>\n<ul><li class=\"donate\"><a href=\"https://liberapay.com/prettydiff/donate\"><svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 80 80\" height=\"16\" width=\"16\" x=\"7\" y=\"7\"><g transform=\"translate(-78.37-208.06)\" fill=\"#111\"><path d=\"m104.28 271.1c-3.571 0-6.373-.466-8.41-1.396-2.037-.93-3.495-2.199-4.375-3.809-.88-1.609-1.308-3.457-1.282-5.544.025-2.086.313-4.311.868-6.675l9.579-40.05 11.69-1.81-10.484 43.44c-.202.905-.314 1.735-.339 2.489-.026.754.113 1.421.415 1.999.302.579.817 1.044 1.546 1.395.729.353 1.747.579 3.055.679l-2.263 9.278\"/><path d=\"m146.52 246.14c0 3.671-.604 7.03-1.811 10.07-1.207 3.043-2.879 5.669-5.01 7.881-2.138 2.213-4.702 3.935-7.693 5.167-2.992 1.231-6.248 1.848-9.767 1.848-1.71 0-3.42-.151-5.129-.453l-3.394 13.651h-11.162l12.52-52.19c2.01-.603 4.311-1.143 6.901-1.622 2.589-.477 5.393-.716 8.41-.716 2.815 0 5.242.428 7.278 1.282 2.037.855 3.708 2.024 5.02 3.507 1.307 1.484 2.274 3.219 2.904 5.205.627 1.987.942 4.11.942 6.373m-27.378 15.461c.854.202 1.91.302 3.167.302 1.961 0 3.746-.364 5.355-1.094 1.609-.728 2.979-1.747 4.111-3.055 1.131-1.307 2.01-2.877 2.64-4.714.628-1.835.943-3.858.943-6.071 0-2.161-.479-3.998-1.433-5.506-.956-1.508-2.615-2.263-4.978-2.263-1.61 0-3.118.151-4.525.453l-5.28 21.948\"/></g></svg> Donate</a></li> <li><a href=\"/demo/?scrolldown\">Demo</a></li> <li><a href=\"/docs-html/tech-documentation.xhtml\">Documentation</a></li> <li><a href=\"https://github.com/unibeautify/sparser\">Github</a></li> <li><a href=\"https://www.npmjs.com/package/sparser\">NPM</a></li></ul><span class=\"clear\"></span></div><div id=\"content\"><h1>");
doc.push("<span>Sparser</span></h1>");
do {
if (parse.stack[b] === "h1" && parse.types[b] === "content" && parse.token[b].indexOf(" - ") > 0) {
doc[1] = parse.token[b];
if (parse.token[b].indexOf("Sparser") > -1) {
doc[doc.length - 1] = `<span>Sparser</span>${parse.token[b].split(" - ")[1]}</h1>`;
} else {
doc[doc.length - 1] = `<span>Sparser</span>${parse.token[b]}</h1>`;
}
} else if (parse.token[b] === "</h1>") {
b = b + 1;
break;
}
b = b + 1;
} while (b < len);
doc.push("\n");
do {
if (parse.types[b] === "attribute") {
attribute();
} else if (parse.stack[b] === "code" && parse.types[b] === "content") {
parse.token[b] = `<![CDATA[${parse.token[b].replace(/\s+$/, "")}]]>`;
doc.push(parse.token[b]);
} else if (parse.token[b] === "<h2>") {
if (parse.token[b - 1] === "</h1>") {
doc.push("<div class=\"section\"><h2>");
} else if (fileitem[0] === "options.md") {
doc.push("</div><div class=\"section\" id=\"option_list\"><h2>");
} else {
doc.push("</div><div class=\"section\"><h2>");
}
} else {
if (fileitem[0] === "options.md" && parse.token[b] === "<td>" && parse.token[b - 1] === "<tr>") {
doc.push("<th>");
} else if (fileitem[0] === "options.md" && parse.token[b] === "</td>" && parse.token[b + 1] === "<td>") {
doc.push("</th>");
} else if (parse.types[b] === "start" && parse.types[b - 1] === "content" && b > 0 && "{[(".indexOf(parse.token[b - 1].charAt(parse.token[b - 1].length - 1)) < 0) {
doc.push(` ${parse.token[b]}`);
} else if (parse.types[b] === "end" && parse.types[b + 1] === "content" && b < len - 1 && ".,;:?!)]}".indexOf(parse.token[b + 1].charAt(0)) < 0) {
doc.push(`${parse.token[b]} `);
} else {
doc.push(parse.token[b].replace(/\\\\"/g, "\\\""));
}
}
if ((/<\/\w\d?>/).test(parse.token[b]) === true) {
doc.push("\n");
}
b = b + 1;
} while (b < len);
doc.push(`</div></div><div id="blobs"><span id="svg_left"></span><span id="svg_right"></span><div></div></div><script src="/js/website.js" type="application/javascript"></script></body></html>`);
fileOutput = doc.join("").replace(/<code>\n/g, "<code>").replace(/\n<\/code>/g, "</code>");
fileOutput = fileOutput.replace(/<\/ol><p>For\s+<a\s+href="lexers">lexer\s+specific\s+documentation<\/a>\s+please\s+review\s+the\s+markdown\s+files\s+in\s+the\s+lexer\s+directory.<\/p>/, `${lexerLinks}</ol>`);
node.fs.writeFile(writePath, fileOutput, "utf8", function node_apps_build_docshtml_readdir_convert_readfile_attribute_add_write(err:Error) {
if (err !== null) {
apps.errout([err.toString()]);
return;
}
a = a + 1;
if (a === total) {
next(`${text.green}Converted ${text.cyan + text.bold + total + text.none + text.green} files from markdown to HTML.${text.none}`);
} else {
node_apps_build_docshtml_readdir_convert(list[a]);
}
});
});
};
if (er !== null) {
apps.errout([er.toString()]);
return;
}
newDir(`${projectPath}docs-html`, function node_apps_build_docshtml_callbackDocs():void {
newDir(`${projectPath}docs-html${sep}lexers`, function node_apps_build_docshtml_callbackLexers():void {
lexers();
});
});
});
},
// document the current inventory of supported languages
inventory: function node_apps_build_inventory():void {
heading("Gathering inventory of supported languages...");
apps.inventory(function node_apps_build_inventory_callback(list:inventory) {
const keys:string[] = Object.keys(list),
keylen:number = keys.length,
index = function node_apps_build_inventory_index():void {
node.fs.readFile(`${projectPath}index.xhtml`, "utf8", function node_apps_build_inventory_website(erw:Error, filedata:string):void {
const inv:string[] = ["<ul>"];
let a:number = 0,