-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
3385 lines (3184 loc) · 86.9 KB
/
index.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
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
window.htma = (() => {
// Enclose everything in a scope to avoid any globals
// String & Array helpers
const array_sliceAt = (arr, until) => {
const i = arr.findIndex(until)
if (i === -1)
return arr
return arr.slice(0,i)
}
const array_sliceAfter = (arr, until) => {
const i = arr.findIndex(until)
if (i === -1)
return arr
return arr.slice(0,i+1)
}
const array_partition = (arr, cond) =>
arr.reduce(([a,b], item, index, list) =>
cond(item, index, list)
? [[...a, item], b]
: [a, [...b, item]], [[],[]])
const string_repeat = (s, n) => {
let ret = ''
for (let i=0; i<n; i++)
ret += s
return ret
}
const string_is = (str, ...options) =>
[].concat(...options.map(option => Array.isArray(option) ? option : [option]))
.includes(str)
const filter_unique = (item, index, list) => list.indexOf(item) === index
const filter_truthy = val => val
// Helper to encode HTML entities when writing content
const encodeEntities = (() => {
// This list should be comprehensive, but may need maintenance
const HTMLEntities = {
"<": "lt",
">": "gt",
"&": "amp",
'"': "quot",
"'": "apos",
"¢": "cent",
"£": "pound",
"¥": "yen",
"€": "euro",
"©": "copy",
"®": "reg",
"Á": "Aacute",
"á": "aacute",
"Â": "Acirc",
"â": "acirc",
"´": "acute",
"Æ": "AElig",
"æ": "aelig",
"À": "Agrave",
"à": "agrave",
"Α": "Alpha",
"α": "alpha",
"∧": "and",
"∠": "ang",
"Å": "Aring",
"å": "aring",
"≈": "asymp",
"Ã": "Atilde",
"ã": "atilde",
"Ä": "Auml",
"ä": "auml",
"„": "bdquo",
"Β": "Beta",
"β": "beta",
"¦": "brvbar",
"•": "bull",
"∩": "cap",
"Ç": "Ccedil",
"ç": "ccedil",
"¸": "cedil",
"Χ": "Chi",
"χ": "chi",
"ˆ": "circ",
"♣": "clubs",
"≅": "cong",
"↵": "crarr",
"∪": "cup",
"¤": "curren",
"†": "dagger",
"‡": "Dagger",
"↓": "darr",
"°": "deg",
"Δ": "Delta",
"δ": "delta",
"♦": "diams",
"÷": "divide",
"É": "Eacute",
"é": "eacute",
"Ê": "Ecirc",
"ê": "ecirc",
"È": "Egrave",
"è": "egrave",
"∅": "empty",
" ": "emsp",
" ": "ensp",
"Ε": "Epsilon",
"ε": "epsilon",
"≡": "equiv",
"Η": "Eta",
"η": "eta",
"Ð": "ETH",
"ð": "eth",
"Ë": "Euml",
"ë": "euml",
"∃": "exist",
"ƒ": "fnof",
"∀": "forall",
"½": "frac12",
"¼": "frac14",
"¾": "frac34",
"Γ": "Gamma",
"γ": "gamma",
"≥": "ge",
"↔": "harr",
"♥": "hearts",
"…": "hellip",
"Í": "Iacute",
"í": "iacute",
"Î": "Icirc",
"î": "icirc",
"¡": "iexcl",
"Ì": "Igrave",
"ì": "igrave",
"∞": "infin",
"∫": "int",
"Ι": "Iota",
"ι": "iota",
"¿": "iquest",
"∈": "isin",
"Ï": "Iuml",
"ï": "iuml",
"Κ": "Kappa",
"κ": "kappa",
"Λ": "Lambda",
"λ": "lambda",
"«": "laquo",
"←": "larr",
"⌈": "lceil",
"“": "ldquo",
"≤": "le",
"⌊": "lfloor",
"∗": "lowast",
"◊": "loz",
"": "lrm",
"‹": "lsaquo",
"‘": "lsquo",
"¯": "macr",
"—": "mdash",
"µ": "micro",
"−": "minus",
"Μ": "Mu",
"μ": "mu",
"∇": "nabla",
" ": "nbsp",
"–": "ndash",
"≠": "ne",
"∋": "ni",
"¬": "not",
"∉": "notin",
"⊄": "nsub",
"Ñ": "Ntilde",
"ñ": "ntilde",
"Ν": "Nu",
"ν": "nu",
"Ó": "Oacute",
"ó": "oacute",
"Ô": "Ocirc",
"ô": "ocirc",
"Œ": "OElig",
"œ": "oelig",
"Ò": "Ograve",
"ò": "ograve",
"‾": "oline",
"Ω": "Omega",
"ω": "omega",
"Ο": "Omicron",
"ο": "omicron",
"⊕": "oplus",
"∨": "or",
"ª": "ordf",
"º": "ordm",
"Ø": "Oslash",
"ø": "oslash",
"Õ": "Otilde",
"õ": "otilde",
"⊗": "otimes",
"Ö": "Ouml",
"ö": "ouml",
"¶": "para",
"∂": "part",
"‰": "permil",
"⊥": "perp",
"Φ": "Phi",
"φ": "phi",
"Π": "Pi",
"π": "pi",
"ϖ": "piv",
"±": "plusmn",
"′": "prime",
"″": "Prime",
"∏": "prod",
"∝": "prop",
"Ψ": "Psi",
"ψ": "psi",
"√": "radic",
"»": "raquo",
"→": "rarr",
"⌉": "rceil",
"”": "rdquo",
"⌋": "rfloor",
"Ρ": "Rho",
"ρ": "rho",
"": "rlm",
"›": "rsaquo",
"’": "rsquo",
"‚": "sbquo",
"Š": "Scaron",
"š": "scaron",
"⋅": "sdot",
"§": "sect",
"": "shy",
"Σ": "Sigma",
"σ": "sigma",
"ς": "sigmaf",
"∼": "sim",
"♠": "spades",
"⊂": "sub",
"⊆": "sube",
"∑": "sum",
"⊃": "sup",
"¹": "sup1",
"²": "sup2",
"³": "sup3",
"⊇": "supe",
"ß": "szlig",
"Τ": "Tau",
"τ": "tau",
"∴": "there4",
"Θ": "Theta",
"θ": "theta",
"ϑ": "thetasym",
" ": "thinsp",
"Þ": "THORN",
"þ": "thorn",
"˜": "tilde",
"×": "times",
"™": "trade",
"Ú": "Uacute",
"ú": "uacute",
"↑": "uarr",
"Û": "Ucirc",
"û": "ucirc",
"Ù": "Ugrave",
"ù": "ugrave",
"¨": "uml",
"ϒ": "upsih",
"Υ": "Upsilon",
"υ": "upsilon",
"Ü": "Uuml",
"ü": "uuml",
"Ξ": "Xi",
"ξ": "xi",
"Ý": "Yacute",
"ý": "yacute",
"ÿ": "yuml",
"Ÿ": "Yuml",
"Ζ": "Zeta",
"ζ": "zeta",
"": "zwj",
"": "zwnj",
}
// Encode single character
const encodeEntity = (s = "") => {
// If string entity exists, return that with dressing
const ent = HTMLEntities[s]
if (ent) return "&"+ent+";"
// If outside of the ASCII range, use numeric entity
const code = s.charCodeAt(0)
if (code > 127)
return "&#"+code.toString()+";"
// Otherwise, return original character
return s
}
// Encode entire string one character at a time
const encodeEntities = (str = "") => [...str].map(encodeEntity).join('')
return encodeEntities
})()
// Invert { canon: alias[] } to { alias: canon }
const invertAliasIndex = aliasIndex =>
Object
.entries(aliasIndex)
.reduce((acc, [ canon, aliases ]) =>
aliases
.reduce((a, alias) =>
({ ...a, [alias]: canon }), acc),
{})
// Weird object inheritance
const nest_props = (parent, child) =>
// Allow child to inherit from parent with both get & set
new Proxy(parent, {
get (target, prop) {
// Check in child first
if (prop in child)
return child[prop]
// Otherwise, check parent
const got = target[prop]
// Allow methods to keep their scope
if (typeof got === 'function')
return got.bind(target)
return got
},
set (target, prop, val) {
// Check in child first
if (prop in child)
child[prop] = val
else // Otherwise, check parent
target[prop] = val
return true
}
})
const mergeOptions = (def, ovr) => {
// Merge two instance options objects
const ret = {}
// Merge anything that exists in the default
for (const k in def) {
// Allow deletion by setting to null
if (ovr[k] === null) continue
// Merge sub-objects, but not arrays
if (
(typeof def[k] === 'object' && !Array.isArray(def[k])) ||
(typeof ovr[k] === 'object' && !Array.isArray(ovr[k]))
)
ret[k] = mergeOptions(def[k], ovr[k] || {})
// Use value and fall back to default
else ret[k] = ovr[k] || def[k]
}
// Merge anything else that exists in the override
for (const k in ovr) {
// Allow deletion by setting to null
if (ovr[k] === null) continue
// If it's in def it's already been done above
if (k in def) continue
// Clone sub-objects, but not arrays
if (typeof ovr[k] === 'object' && !Array.isArray(ovr[k]))
ret[k] = mergeOptions({}, ovr[k])
// Use value
else ret[k] = ovr[k]
}
return ret
}
// Helper classes for parser
class Executor {
// Containment class for executing arbitrary code in user-defined expressions
// List of allowed keywords that are not interpreted as variable names
#keyword_list = ['true','false','typeof','instanceof','Math','Object','Array','Boolean','String','console','undefined','null','parseFloat','parseInt']
// Keywords in a lookup table for quick access
#keywords = {}
#parser
constructor(parse_js) {
this.#parser = parse_js
this.#keywords = Object.fromEntries(this.#keyword_list.map(kw => [kw,1]))
}
static evaluate_expression = (
exp, internal_props,
// Override globals to disallow access from inside the eval
{ window, globals, global, document } = {}
) => {
// Wrapper for eval that returns the result of the expression
let result
try {
result = Function('internal_props', `return (${exp})`)(internal_props)
} catch (e) {
console.error(e, exp, internal_props)
}
return result
}
rebase_vars (expression, newBase) {
return this.#parser(expression)
}
exec (expression, internal_props) {
// Execute an expression with the given scope variable
return Executor.evaluate_expression(this.rebase_vars(expression, 'internal_props'), internal_props)
}
prep (expression, internal_props) {
// Prepare a function to execute an expression with the given scope variable and any additional arguments
const exp = this.rebase_vars(expression, 'internal_props')
return args => Executor.evaluate_expression(exp, nest_props(internal_props, args))
}
}
class Scope {
#string = ''
#writer = {}
#writer_instance
constructor (string = '', props = {}, writer = {}, parse_js) {
this.#string = string
this.#props = props
this.#executor = new Executor(parse_js)
const dump_fun = method => (...args) => method(this.#writer_instance, ...args)
const mod_fun = method => (...args) => {
const result = method(this.#writer_instance, ...args)
if (typeof result !== 'undefined')
this.#writer_instance = result
}
this.#writer_instance = writer.inst()
this.#writer = Object.fromEntries(
Object.entries(writer)
.map(([ name, method ]) => [
name,
['dump','dumpString'].includes(name)
? dump_fun(method)
: mod_fun(method)
])
)
}
get writer() {
return {...this.#writer}
}
#props = {}
get props() {
return this.#props
}
#executor
exec(expression) {
return this.#executor.exec(expression, this.#props)
}
prep(expression) {
return this.#executor.prep(expression, this.#props)
}
#conditions = {}
condition (indent, exact = false) {
if (exact)
return this.#conditions[indent]
return !Object.entries(this.#conditions)
.some(([i,v]) => parseInt(i) < indent && v === false)
}
setCondition (indent, condition) {
this.#conditions[indent] = condition
}
get conditions() {
return {...this.#conditions}
}
get currentCondition() {
const indent_parent = this.#reading.find(({ data = {} }) => 'indent' in data)
return indent_parent ? this.condition(indent_parent.data.indent) : undefined
}
#reading = []
get reading() {
return [...this.#reading]
}
get currentType() {
return this.#reading[0] && this.#reading[0].type
}
start_reading (type, data = false) {
this.#reading.unshift({ type, ...(data ? {data} : {}) })
}
stop_reading (type, force = false) {
const types = Array.isArray(type) ? type : [type]
const i = this.#reading.findIndex(e => types.includes(e.type))
const typ = this.#reading[i].type
if (i === -1 && !force)
throw new Error(`${typ} cannot be stopped as it is not currently being read.`)
if (i !== 0 && !force)
throw new Error(`${typ} cannot be stopped as it is not the most recent item being read, use force=true if you want this to stop anyway.`)
this.#reading = this.#reading.slice(i+1)
}
is_reading (type, parents = false) {
const types = Array.isArray(type) ? type : [type]
if (parents === true)
return this.#reading.some(e => types.includes(e.type))
if (parents === false)
return this.#reading[0] && types.includes(this.#reading[0].type)
return this.#reading[parents] && types.includes(this.#reading[parents].type)
}
get_all_reading_data(type = false, until = false) {
const types = Array.isArray(type) ? type : [type]
const set = type === false
? this.#reading
: this.#reading.filter(e => types.includes(e.type))
const data = set.map(({ data }) => data || {})
if (until === false)
return data
return array_sliceAt(data, until)
}
get_reading_data(type, check = false) {
const types = Array.isArray(type) ? type : [type]
const e = this.#reading.find(e => types.includes(e.type) && (!check || check(e.data || {})))
return (e && e.data) || {}
}
get reading_data () {
return (this.#reading[0] && this.#reading[0].data) || {}
}
#reserve = ''
set reserve (newReserve) {
this.#reserve = newReserve
}
get reserve () {
return this.#reserve
}
#buffer = ''
get buffer () {
const read = this.#buffer
this.#buffer = ''
return read
}
set buffer(newBuffer){
this.#buffer = newBuffer
}
get data() {
return {
buffer: this.#buffer,
output: (this.#writer.dumpString || this.#writer.dump)(),
syntax: [...this.#reading],
conditions: Object.entries(this.#conditions),
conditional: this.currentCondition,
}
}
#index = -1
get index() {
return this.#index
}
get next() {
this.#index++
return this.currentCharacter
}
get currentCharacter() {
return this.#string[this.#index]
}
get followingCharacter() {
return this.#string[this.#index+1]
}
}
// Custom component registry
const custom_components = {}
const add_component = (...args) => {
// Add a custom component
let name, str, o
// If there's only one argument, assume it's a class
if (args.length === 1){
const obj = args[0]
name = obj.name
str = obj.template
o = obj
} else
// Otherwise, assume it string based
[name, str, o] = args
// Normalise defaults as a class or getter function
let defaults
if (typeof o === 'function')
defaults = o
else
if (typeof o === 'object')
defaults = function () { return {...o} }
else
defaults = function () { return {} }
// Register component
custom_components[name] = {
template: str,
defaults
}
}
// Parser definitions
const parser = (conditions = [], syntax_list = [], token_list = [], writer_interface = {}) => {
// Define a parser for a particular language
// SYNTAX VALUES
// Syntax used by the system
const system_syntax = ['START','END','DEFAULT']
// Check all syntax values for validity
syntax_list.forEach(syn => {
if (system_syntax.includes(syn))
throw new Error(`Invalid parser syntax value: "${syn}". This value is reserved by the system.`)
})
// Create a lookup table for the syntax values
const syntax = Object.fromEntries(
[].concat(
syntax_list.map(syn => [ syn.toUpperCase(), `syntax_${syn.toLowerCase()}` ]),
system_syntax.map(syn => [ syn.toUpperCase(), `syntax_system_${syn.toLowerCase()}` ])
)
)
// TOKEN VALUES
// Tokens used by the system
const system_tokens = ['DEFAULT']
// Check all token values for validity
token_list.forEach(tok => {
if (system_tokens.includes(tok))
throw new Error(`Invalid parser token value: "${tok}". This value is reserved by the system.`)
})
// Create a lookup table for the token values
const tokens = Object.fromEntries(
[].concat(
token_list.map(tok => [ tok.toUpperCase(), `token_${tok.toLowerCase()}` ]),
system_tokens.map(tok => [ tok.toUpperCase(), `token_system_${tok.toLowerCase()}` ]),
)
)
// Fallback action when no condition is met: append current character to buffer
const defaultAction = scope => ({ buffer: scope.currentCharacter })
// Normalise a syntax or token condition into an array
const normalise_condition = (name, cond) => {
const map = name.includes('syntax') ? syntax : tokens
const evalled = (typeof cond === 'function') ? cond(map) : cond
if (!evalled) return {}
const arrayed = Array.isArray(evalled) ? evalled : [evalled]
return {[name]:arrayed.map(v => map[v.toUpperCase()] || v.toLowerCase()).filter(filter_unique)}
}
// Normalise all the conditions to simplify the logic down the line
const normalised_conditions = conditions.map(({ syntax, not_syntax, tokens, not_tokens, action, condition }) => ({
action,
...(condition ? {condition} : {}),
...normalise_condition('syntax', syntax),
...normalise_condition('not_syntax', not_syntax),
...normalise_condition('tokens', tokens),
...normalise_condition('not_tokens', not_tokens),
}))
// Create a lookup table for the conditions as { syntax: { token: condition[] } } for quick access
const quick_conditions =
Object.fromEntries(
Object.values(syntax)
.map(syn => {
const syntax_conditions = normalised_conditions.filter(({ syntax: syntax_matches, not_syntax }) =>
(!syntax_matches || syntax_matches.includes(syn)) &&
(!not_syntax || !not_syntax.includes(syn))
)
return [
syn,
Object.fromEntries(
Object.values(tokens)
.map(token => [
token,
array_sliceAfter(
syntax_conditions.filter(({ tokens: token_matches, not_tokens }) => (
(!token_matches || string_is(token, ...token_matches)) &&
(!not_tokens || !string_is(token, ...not_tokens))
)),
({ condition }) => !condition
)
])
)
]
}))
const getParserStep = (scope, instance, token_lookup, passthrough) => {
// Get a parser step for a particular parser instance
// Condition matcher (this used to be more complex but was made mostly redundant by quick_conditions)
const matchingCondition = ({ condition }) => !condition || condition.call(instance, scope)
const parserStepCall = () => {
// This is called for each character in the string being parsed
// Get the syntax currently being read, fall back to default
const ct = scope.currentType || 'syntax_system_default'
// Classify the currently read character as a token, fall back to default
const cc = tokens[token_lookup[scope.currentCharacter]] || 'token_system_default'
// Find a condition matching the current syntax and token, as well as any other requirements
const foundCondition = quick_conditions[ct][cc].find(matchingCondition)
// Get the action function or fall back to the default action
const action = (foundCondition ? foundCondition.action : false) || defaultAction
// Execute the action
const result = action.call(instance, scope, passthrough)
// Always append to the reserve, for output in case of failure (not yet implemented)
scope.reserve += scope.currentCharacter
// Handle the result if one was returned
if (result) {
// Set buffer value
if (result.setBuffer !== undefined)
scope.buffer = result.setBuffer
// Append to buffer value
if (result.buffer !== undefined)
scope.buffer += result.buffer
}
// Return condition so that its index can be looked up for debug purposes
return foundCondition
}
return parserStepCall
}
const parse = (instance, writers, instance_tokens = {}) => {
// Create a parser instance with a particular config
// Normalise the given tokens by capitalising the keys
const normalised_instance_tokens = Object.fromEntries(
Object.entries(instance_tokens).map(([ tok, vals ]) => [ tok.toUpperCase(), vals ])
)
// Check all the given tokens for validity
Object.keys(tokens).forEach(tok => {
if (system_tokens.includes(tok)) return
const token_list = normalised_instance_tokens[tok]
if (!token_list || !Array.isArray(token_list) || token_list.length === 0)
throw new Error(`Tokens must include "${tok}" as a list of string characters.`)
token_list.forEach(t => {
if (typeof t !== 'string')
throw new Error(`Token must be a string, ${typeof t} given.`)
if (t.length !== 1)
throw new Error(`Token must be a single character, "${t}" is ${t.length} characters.`)
})
})
// Create a lookup table for easy access
const token_lookup = invertAliasIndex(normalised_instance_tokens)
const validate_writer = (name, writer) => {
// Validate a writer object against the given writer interface
if (typeof writer.inst !== 'function')
throw new Error(`The ${name} writer must implement an 'inst' method that creates a new object to write data to.`)
if (typeof writer.dump !== 'function')
throw new Error(`The ${name} writer must implement a 'dump' method that outputs the result after the writing is complete.`)
Object.entries(writer_interface)
.forEach(([ method, reason ]) => {
if (typeof writer[method] !== 'function')
throw new Error(`The ${name} writer must implement a '${method}' method${reason?(' '+reason):''}.`)
})
}
// Check the existing writers implement the required methods
Object.entries(writers)
.forEach(([ name, writer ]) => {
validate_writer(name, writer)
})
const parse_instance = (str = '', args = {}, options = {}) => {
const {
debug: debug_call = false,
writer = writers.default,
outputString = false
} = options
// Check the custom writer implements the required interface
validate_writer('custom', writer)
// Init scope
const scope = new Scope(str, args, writer, instance.parse_js)
// The debug function that reports data on each step
const debug = (index, chosenCondition) =>
debug_call(index, JSON.parse(JSON.stringify(scope.data)), chosenCondition)
// The debug call that will be passed through to writer.nest calls, takes index first to re-base the debug pointer
const subDebugCall = debug_call
? (index) => (ind, dat, ch) => debug_call(index+ind+1, dat, ch, true)
: () => false
// All options passed through to the writer.nest calls
const passthrough = { ...options, debug: subDebugCall }
// The instance that will be passed through to all actions, and can be refered to as `this` inside the actions
const pass_instance = {
isToken(str, ...toks) {
const str_token = token_lookup[str]
const str_token_const = tokens[str_token]
return toks.some(tok =>
tok.toUpperCase() === str_token || tok.toLowerCase() === str_token_const)
},
tokens,
syntax,
...instance
}
// Get a parser instance for this scope
const parserStep = getParserStep(scope, pass_instance, token_lookup, passthrough)
// Zero-th debug step, before any action
if (debug_call && quick_conditions.syntax_system_start.token_system_default.length === 0)
debug(0, -2)
quick_conditions.syntax_system_start.token_system_default
.forEach(condition => {
condition.action.call(pass_instance, scope, passthrough)
if (debug_call)
debug(0, normalised_conditions.indexOf(condition))
})
// Parse every character of the string one by one
while (scope.next) {
const foundCondition = parserStep()
// Record each step of the parsing
if (debug_call)
debug(scope.index+1, normalised_conditions.indexOf(foundCondition))
}
// Final debug step, after all actions
if (debug_call && quick_conditions.syntax_system_end.token_system_default.length === 0)
debug(str.length+1, -3)
quick_conditions.syntax_system_end.token_system_default
.forEach(condition => {
condition.action.call(pass_instance, scope, passthrough)
if (debug_call)
debug(str.length+1, normalised_conditions.indexOf(condition))
})
// Output final result
if (outputString && scope.writer.dumpString)
return scope.writer.dumpString()
return scope.writer.dump()
}
return parse_instance
}
return parse
}
// Language-specific parser for HTMA
const htma_parser = (() => {
// System tags for programatic tags
const tags = {
IF: 'if',
VAR: 'var',
FUNC: 'func',
ARGS: 'args',
ELSE: 'else',
ELSEIF: 'elseif',
FOR: 'for'
}
// System tags grouped by ability
const tag_groups = {
system: [tags.VAR,tags.FOR,tags.IF,tags.ELSE,tags.ELSEIF,tags.ARGS,tags.FUNC],
condition: [tags.IF,tags.ELSE,tags.ELSEIF],
else: [tags.ELSE,tags.ELSEIF],
if: [tags.IF,tags.ELSEIF],
var: [tags.VAR,tags.FUNC],
}
// List of HTML tags that are allowed to be self-closing
const self_closing_tags = {
area: true,
base: true,
br: true,
col: true,
command: true,
embed: true,
hr: true,
img: true,
input: true,
keygen: true,
link: true,
menuitem: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true
}
const attribute_transformer = (attributeTransformations, prop) => {
// Get attribute transformation config for a given attribute name, fill in from & fall back to default
const attr_tr = attributeTransformations[prop]
if (attr_tr)
return { ...attributeTransformations.DEFAULT, ...attr_tr }
return attributeTransformations.DEFAULT
}
const transform_attributes = (attributeTransformations, attrs, orig={}) =>
// Group attribute transformation
Object
.entries(attrs)
.reduce(transform_attribute(attributeTransformations), orig)
const transform_attribute = attributeTransformations => (acc, [ prop, val ]) => {
// Transform a single attribute based on the attribute transformation config
// Get the attribute transformation config
const attr_tr = attribute_transformer(attributeTransformations, prop)
// Check the attribute value is valid first
if (attr_tr.validate && !attr_tr.validate(val))
return acc
// Transform the attribute to others if the value is found in the transformations
if (attr_tr.trans) {
const transed = typeof attr_tr.trans === 'function'
? attr_tr.trans(val)
: attr_tr.trans[val]
// Recursively transform the resulting attributes to ensure they are all resolved
if (transed)
return transform_attributes(attributeTransformations, transed, acc)
// Do nothing if the value is not transformable
return acc
}
// If the atrribute has no transformations, just add it to the attribute object normally
return add_attribute(attributeTransformations, acc, prop, val)
}
const add_attribute = (attributeTransformations, attrs, attr, attrVal) => {
// Add an attribute to the attribute object using the methods in the attribute transformation config
const attr_tr = attribute_transformer(attributeTransformations, attr)
return {
...attrs,
[attr]: attr_tr.add(
attrs[attr],
attr_tr.parse(attrVal)
)
}
}
// Named actions that are taken by the parser, used only in the conditions list
const actions = {
inline_expression(tag) {
return tag.attrs.id+((tag.attrs.class && tag.attrs.class.length) ? ('.'+tag.attrs.class.join('.')) : '')
},
open_tag(scope, tag, passthrough) {
const conditional = scope.currentCondition
if (conditional === false) {
if (string_is(tag.name, tag_groups.var)) {
scope.stop_reading(this.syntax.TAG)
if (tag.indent !== undefined) {
scope.start_reading(this.syntax.INDENT)
return { setBuffer: string_repeat(' ', tag.indent) }
}
}
return { setBuffer: '' }
}
let buff = false
const custom = custom_components[tag.name]
if (custom) {
const contents = custom.template
const defs = new custom.defaults()
Object.assign(defs, tag.attrs)
if (defs.afterConstructed)
defs.afterConstructed()
scope.writer.nest(
contents,
defs,
{ ...passthrough, debug: passthrough.debug(0) })
scope.stop_reading(this.syntax.TAG)
scope.setCondition(tag.indent, tag.eval)
return { setBuffer: '' }
} else
{
if (string_is(tag.name, tag_groups.system)) {
if (string_is(tag.name, tag_groups.else) && scope.condition(tag.indent, true)) {