-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathjsxLoader.js
More file actions
1826 lines (1736 loc) · 91.4 KB
/
jsxLoader.js
File metadata and controls
1826 lines (1736 loc) · 91.4 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
/**
* DataFormsJS jsxLoader and compiler for React/JSX Code
*
* This script runs in a browser and converts JSX inside of <script type="text/babel">
* elements to plain JavaScript. For modern Browsers [Chrome, Firefox, Edge, recent versions
* of Safari, etc] a fast built-in compiler/transpiler is used to quickly convert JSX to JS.
* For older browsers which typically are IE and older versions of Safari/iOS Polyfills are
* and Babel Standalone are downloaded from a CDN and used to convert the JSX code to JS.
*
* The result of this script is that React/JSX can be used directly in production webpages
* without having to use a large build process and dependency download to convert JSX to JS.
*
* Documentation:
* https://github.com/dataformsjs/dataformsjs/blob/master/docs/jsx-loader.md
*
* The starting point and core structure of this compiler is based on (The Super Tiny Compiler)
* [jamiebuilds/the-super-tiny-compiler]:
* https://git.io/compiler
* https://github.com/jamiebuilds/the-super-tiny-compiler
*
* [The Super Tiny Compiler] is a great project to review if you would like to understand
* how compilers work.
*
* Copyright Conrad Sollitt and Authors. For full details of copyright
* and license, view the LICENSE file that is distributed with DataFormsJS.
*
* @link https://www.dataformsjs.com
* @author Conrad Sollitt (https://conradsollitt.com)
* @license MIT
*/
/* Validates with both [jshint] and [eslint] */
/* global Babel, Promise, module */
/* jshint evil:true */
/* jshint strict: true */
/* eslint-env browser */
/* eslint quotes: ["error", "single", { "avoidEscape": true }] */
/* eslint strict: ["error", "function"] */
/* eslint spaced-comment: ["error", "always"] */
/* eslint no-console: ["error", { allow: ["log", "warn", "error"] }] */
/* eslint no-prototype-builtins: "off" */
(function() {
'use strict';
// Enums "JavaScript Objects" for Tokens and AST.
// This makes typing and searching for related code easier.
var tokenTypes = {
js: 0,
e_start: 1,
e_end: 2,
e_prop: 3,
e_value: 4,
e_child_text: 5,
e_child_js: 6,
e_child_whitespace: 7,
e_child_js_start: 8,
e_child_js_end: 9,
};
var astTypes = {
program: 0,
js: 1,
createElement: 2,
};
// Convert enum props to strings so they can be viewed easily from DevTools
var enums = [tokenTypes, astTypes];
for (var n = 0, m = enums.length; n < m; n++) {
var obj = enums[n];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = prop;
}
}
}
/**
* [jsxLoader] Object
*
* If using optional properties or functions then the should be set immediately after this
* script is defined and before the [DOMContentLoaded] event is triggered. Example:
*
* <script src="jsxLoader.js"></script>
* <script>
* jsxLoader.polyfillUrl = '{url}';
* jsxLoader.needsPolyfill = true;
* jsxLoader.babelUrl = '{url}';
* jsxLoader.logCompileTime = true;
* jsxLoader.logCompileDetails = true;
* jsxLoader.evalCode = '{string}';
* jsxLoader.jsUpdates.push({ find:/regex_search/g, replace:'{string}' });
* jsxLoader.usePreact();
* jsxLoader.addBabelPolyfills = function() { '...'; }
* jsxLoader.compiler.pragma = 'Vue.h';
* jsxLoader.compiler.pragmaFrag = 'Vue.Fragment';
* jsxLoader.compiler.addUseStrict = false;
* </script>
*/
var jsxLoader = {
/**
* Polyfill URL that is used for older browsers
*/
polyfillUrl: 'https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0&features=Array.from,Array.isArray,Array.prototype.find,Array.prototype.findIndex,Object.assign,Object.keys,Object.values,URL,fetch,Promise,Promise.prototype.finally,String.prototype.endsWith,String.prototype.startsWith,String.prototype.includes,String.prototype.repeat,WeakSet,Symbol,Number.isInteger,String.prototype.codePointAt,String.fromCodePoint',
/**
* Babel URL and options used for older browsers.
* The version of Babel Standalone used (published Dec 23, 2020) is the most
* recent build that works with IE 11 and older versions of Safari. Versions
* published after this have fatal errors and do not load on older browsers.
*/
babelUrl: 'https://cdn.jsdelivr.net/npm/@babel/[email protected]/babel.js',
babelOptions: {
presets: ['es2015', 'react'],
plugins: ['proposal-object-rest-spread'],
},
/**
* Default options for fetching JSX Templates. To use different options
* set this as soon as the script is loaded and before the document
* 'DOMContentLoaded' event runs. The default options provide for
* flexibility with 'cors', prevention of caching issues with 'no-store',
* and security by using 'same-origin' for `credentials`.
*/
fetchOptions: {
mode: 'cors',
cache: 'no-store',
credentials: 'same-origin',
},
/**
* Print compile start, end, and time taken to console.
*/
logCompileTime: false,
/**
* Print compile tokens and Abstract Syntax Tree (AST) to the console.
* If `true` then `logCompileTime` will also run.
*/
logCompileDetails: false,
/**
* Allow for debugging with Babel Standalone. To use this
* also set `jsxLoader.isSupportedBrowser` to `false`.
*/
sourceMaps: false,
/**
* Code here is evaluated when the [DOMContentLoaded()] event is triggered on
* page load. If the code does not error then the internal compiler will be
* used to convert JSX to JS, however if there is an error then Polyfills
* and Babel will be downloaded and used.
*
* This property can be overwritten before the page finishes loading in case you would
* like to target specific browsers or features. In the first example below Firefox, Edge
* and other supported Browsers will use Babel because Chrome version 79 is being targeted.
*
* window.jsxLoader.evalCode = "if (!navigator.userAgent.includes('Chrome/79')) throw 'Test';";
* window.jsxLoader.evalCode = "throw 'Test';"; // Use Babel for all Browsers
*
*/
evalCode: '"use strict"; class foo {}; const { id, ...other } = { id:123, test:456 };',
/**
* Condition to check for if the browser needs a Polyfill or not
*/
needsPolyfill: (Array.from && typeof window !== 'undefined' && window.Promise && window.fetch && Promise.prototype.finally ? false : true),
/**
* When using the compiler from jsxLoader specific code for ES or node modules should
* be updated or removed. This includes the `import React from 'react'` that used when
* building React Apps from Node. When used in a Browser `React` will already exist as
* a Global and `import` doesn't work with node modules. A calling app can modify this
* list as needed for custom generated code to work.
*
* Additionally this can be used to support React Alternatives such as Preact and Rax.
* See demos and Unit Tests for usage. When calling `jsxLoader.usePreact()` this list
* will be automatically updated for Preact.
*/
jsUpdates: [
{ find: /export function/g, replace: 'function' },
{ find: /export default class/g, replace: 'class' },
{ find: /import React from 'react';/g, replace: '' },
{ find: /import React from"react";/g, replace: '' },
{ find: /=>,/g, replace:'=>' }, // Work-around for edge-case JSX, Issue 21 on GitHub
],
/**
* Used with `jsxLoader.addBabelPolyfills()`. If called this maps
* module names from `require(name)` to a global browser module:
*
* Example:
* require('react') => window.React
* require('react-dom') => window.ReactDOM
*/
globalNamespaces: {
'react': 'React',
'react-dom': 'ReactDom',
},
/**
* This property gets set to either `true` or `false` depending on `evalCode`.
* When `false` it means that Babel was downloaded and used to compile JSX.
* To manually override the default setup set this a value prior to the
* 'DOMContentLoaded' event.
*/
isSupportedBrowser: null,
/**
* Setup the compiler to use Preact instead of React. This function is designed
* for good compatibility between React Components and Preact and it will allow
* React Components to be used for Preact without defining an alias variable.
*
* If you are developing a Preact app that has different needs then this function
* can be copied and easily modified for your app or site.
*
* See Preact demos for usage.
*/
usePreact: function () {
// Set compiler directives
this.compiler.pragma = 'preact.createElement';
this.compiler.pragmaFrag = 'preact.Fragment';
// Replace commonly used React APIs with Preact once code is compiled
this.jsUpdates.push({ find: /ReactDOM\.render/g, replace: 'preact.render' });
this.jsUpdates.push({ find: /React\.Component/g, replace: 'preact.Component' });
this.jsUpdates.push({ find: /React\.Fragment/g, replace: 'preact.Fragment' });
this.jsUpdates.push({ find: /React\.createElement/g, replace: 'preact.createElement' });
this.jsUpdates.push({ find: /React\.cloneElement/g, replace: 'preact.cloneElement' });
this.jsUpdates.push({ find: /React\.createRef/g, replace: 'preact.createRef' });
this.jsUpdates.push({ find: /onChange:/g, replace: 'onInput:' });
this.jsUpdates.push({ find: /import preact from 'preact';/g, replace: '' });
this.jsUpdates.push({ find: /import preact from"preact";/g, replace: '' });
// Update global namespaces to use Preact instead of React for when
// Babel is used (IE 11, old iOS/Safari, etc).
// This also applies to if the app calls `jsxLoader.addBabelPolyfills()`.
this.globalNamespaces.react = 'preact';
this.globalNamespaces['react-dom'] = 'preact';
// Define a `React` global if not defined and `preact` is already loaded.
// This allows DataFormsJS Components (or other components) that use
// <script type="module"> with references to `React.Component` to run
// as long as they are using matching React API.
if (typeof window !== 'undefined' && window.React === undefined && window.preact !== undefined) {
window.React = window.preact;
}
},
/**
* Return `true|false` depending on whether or not all scripts can be loaded.
* This can be used by the calling page to determine if scripts are still being
* compiled. This would not commonly be used and is intended for Unit Testing.
*
* @return {bool}
*/
hasPendingScripts: function () {
var scripts = document.querySelectorAll('script[type="text/babel"]:not([data-added-to-page])');
return (scripts.length > 0);
},
/**
* Setup Event
*
* This gets called automatically when the page is loaded from the
* [DOMContentLoaded] event or it can be called manually if needed.
*
* It will automatically download and load all <script type="text/babel"> scripts
* in the order that they are defined on the page.
*/
setup: function() {
// Get all scripts and if there is only one then load it
var scripts = document.querySelectorAll('script[type="text/babel"]:not([data-added-to-page])');
if (scripts.length === 1) {
jsxLoader.loadScript(scripts[0]);
return;
}
// Private function to Download JSX Source based on <script src="{url}">
// This is based on `loadScript()` however it only downloads and doesn't
// compile or add the script. This allows scripts to be added on the page
// in the expected order based on how they are defined in the HTML.
// Github Issue 22
function downloadJsx(element) {
var result = {
element: element,
text: '',
error: null,
};
return new Promise(function(resolve) {
fetch(element.src, jsxLoader.fetchOptions)
.then(function(res) {
var status = res.status;
if ((status >= 200 && status < 300) || status === 304) {
return res.text();
} else {
throw new Error('Error loading data. Server Response Code: ' + status + ', Response Text: ' + res.statusText);
}
})
.then(function(text) {
result.text = text;
resolve(result);
})
.catch(function(error) {
result.error = error;
resolve(result);
});
});
}
// First asynchronously download all scripts that contain the [src] attribute.
// Scripts that contain embedded content will run after all downloads finish.
// The reason is inline scripts are expected to be dependent on the downloaded scripts.
var promisesSrc = [];
var scriptsNoSrc = [];
Array.prototype.forEach.call(scripts, function(script) {
if (script.src === '') {
scriptsNoSrc.push(script);
} else {
promisesSrc.push(downloadJsx(script));
}
});
// Compile and add scripts to the page once all [src] scripts are downloaded
Promise.all(promisesSrc).then(function (results) {
results.forEach(function(result) {
jsxLoader.loadScript(result.element, result.text, result.error);
});
scriptsNoSrc.forEach(function(script) {
jsxLoader.loadScript(script);
});
});
},
/**
* Load a Babel Script and add it to the page as JavaScript. This function
* gets called by [setup()] for each <script type="text/babel"> on the page.
*
* This function returns a Promise that resolves once the script has been
* added to the page regardless of whether or not it had an error. This
* behavior is used so that `Promise.all(scripts).finally()` logic can be
* used when loading multiple scripts.
*
* Parameters `downloadedSrc` and `downloadError` are intended only
* for internal use.
*
* @param {HTMLScriptElement} element
* @param {string|undefined} downloadedSrc
* @param {mixed|undefined} downloadError
* @return {Promise}
*/
loadScript: function(element, downloadedSrc, downloadError) {
function addToPage(text, callback, src) {
// Status
var startTime = new Date();
if (jsxLoader.logCompileTime || jsxLoader.logCompileDetails) {
console.log('='.repeat(80));
console.log(element.src);
console.log('Start time: ' + startTime.getTime());
}
// If using sourceMaps then set babel options to allow debugging
if (jsxLoader.sourceMaps) {
if (jsxLoader.babelOptions.sourceMaps === undefined) {
jsxLoader.babelOptions.sourceMaps = 'both';
jsxLoader.babelOptions.generatorOpts = { sourceMaps: 'both' };
}
var file = src;
if (file === undefined) {
var selector = 'script[data-compiler="Babel"]:not([data-src])';
var inlineCount = document.querySelectorAll(selector).length;
file = 'Inline Babel script' + (inlineCount === 0 ? '' : ' (' + (inlineCount+1) + ')');
}
jsxLoader.babelOptions.filename = file;
}
// Compile the React/JSX Code to JavaScript
var js, compilerType;
try {
if (jsxLoader.isSupportedBrowser) {
js = jsxLoader.compiler.compile(text);
compilerType = 'jsxLoader';
} else {
js = Babel.transform(text, jsxLoader.babelOptions).code;
compilerType = 'Babel';
}
} catch (e) {
console.log('-'.repeat(80));
console.log('Compile Error:');
console.log(element);
console.error(e);
element.setAttribute('data-error', e.toString());
js = null;
}
// Status
if (jsxLoader.logCompileDetails) {
console.log(js);
}
if (jsxLoader.logCompileTime || jsxLoader.logCompileDetails) {
var endTime = new Date();
console.log('End time: ' + endTime.getTime());
console.log('Time taken (in milliseconds): ' + (endTime.getTime() - startTime.getTime()));
}
// Exit if there was a JavaScript compile error
if (js === null) {
callback();
return;
}
// Find and replace contents in the generated JavaScript. See comments in the [jsUpdates] property
jsxLoader.jsUpdates.forEach(function(item) {
js = js.replace(item.find, item.replace);
});
// Add compiled JS ad a new <script> on the page.
// If the JSX compiles correctly but there is a JavaScript error then
// it will not be caught here and the calling app would have to use
// global error handling `window.onerror` to catch the error. Because
// it is not caught [data-error] will not appear on the <script> element.
var script = document.createElement('script');
if (src) {
script.setAttribute('data-src', src);
}
script.setAttribute('data-compiler', compilerType);
if (element.getAttribute('data-type') === 'module') {
script.type = 'module';
}
script.innerHTML = js;
document.head.appendChild(script);
callback();
}
return new Promise(function(resolve) {
// Inline JSX in the <script> Element
if (element.src === '') {
addToPage(element.innerHTML, resolve);
element.setAttribute('data-added-to-page', '');
return;
}
// Already downloaded from setup
if (typeof downloadedSrc === 'string') {
if (downloadError) {
console.error(downloadError);
element.setAttribute('data-added-to-page', '');
element.setAttribute('data-error', downloadError.toString());
resolve();
} else {
addToPage(downloadedSrc, resolve, element.getAttribute('src'));
element.setAttribute('data-added-to-page', '');
}
return;
}
// Download JSX Source based on <script src="{url}">
fetch(element.src, jsxLoader.fetchOptions)
.then(function(res) {
var status = res.status;
if ((status >= 200 && status < 300) || status === 304) {
return res.text();
} else {
throw new Error('Error loading data. Server Response Code: ' + status + ', Response Text: ' + res.statusText);
}
})
.then(function(text) {
addToPage(text, resolve, element.getAttribute('src'));
element.setAttribute('data-added-to-page', '');
})
.catch(function(error) {
console.error(error);
element.setAttribute('data-added-to-page', '');
element.setAttribute('data-error', error.toString());
resolve();
});
});
},
/**
* Allow [babel-standalone] to use [import and exports] with JSX files.
* This function is called automatically if needed when the page loads
* if Babel is being used and it can be overwritten if needed by the
* calling page before the `DOMContentLoaded` even runs.
*
* For the browser this defines `exports` as the global window object
* and a global `require(module)` function.
*/
addBabelPolyfills: function() {
window.exports = window;
window.require = function(module) {
var obj,
name;
// Map module string name to a specified global namespace object.
// By default two namespaces are handled:
// 'react' => window.React
// 'react-dom' => window.ReactDOM
if (jsxLoader.globalNamespaces[module] !== undefined) {
obj = window[jsxLoader.globalNamespaces[module]];
if (obj !== undefined) {
return obj;
}
}
// Map module to global window object. If not found attempt
// to map it based on common module naming rules.
obj = window[module];
if (obj === undefined) {
// Handle module names that contain a '-' character
if (module.indexOf('-') !== -1) {
// Example: 'prop-types' => 'PropTypes'
name = module.split('-').map(function(s) {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}).join('');
// Example: 'react-transition-group' => 'reactTransitionGroup'
obj = window[name];
if (obj === undefined) {
name = name.substring(0, 1).toLowerCase() + name.substring(1);
obj = window[name];
}
}
}
return obj;
};
},
/**
* Add a <script> element to the page from a URL. This function is used
* internally for loading [polyfillUrl] and [babelUrl]. It only handles regular
* JavaScript and not JSX. For JSX Scripts see the [loadScript()] function.
*
* @param {string} url
* @param {function} callback
*/
downloadScript: function(url, callback) {
var script = document.createElement('script');
script.onload = callback;
script.onerror = function () {
console.error('Error loading Script: ' + url);
callback();
};
script.src = url;
document.head.appendChild(script);
},
/**
* Add additional polyfills needed for Babel that are not included from [polyfill.io].
* This function can be overwritten by the app if needed. As of early 2020 [polyfill.io]
* now includes the new `trimStart()` and `trimEnd()` functions, however Babel 7 uses
* the non-standard `trimLeft()` and `trimRight()`.
*/
addAdditionalPolyfills: function() {
if (String.prototype.trimLeft === undefined) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/, '');
};
}
if (String.prototype.trimStart === undefined) {
String.prototype.trimStart = String.prototype.trimLeft;
}
if (String.prototype.trimRight === undefined) {
String.prototype.trimRight = function() {
return this.replace(/\s+$/, '');
};
}
if (String.prototype.trimEnd === undefined) {
String.prototype.trimEnd = String.prototype.trimRight;
}
},
/**
* Compiler for converting React/JSX Code to JavaScript. See comments
* near the top of this file for info on the compiler.
*/
compiler: {
/**
* Compiler Options
*/
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
maxRecursiveCalls: 1000,
addUseStrict: true,
/**
* Compile JSX to JS
*
* @param {string} input
* @return {string}
*/
compile: function(input) {
// If code appears to be minimized return it without attempting to parse it.
if (this.isMinimized(input)) {
return input;
}
// Compiler Step 1 - Remove Comments from the Code
var newInput = this.removeComments(input);
// Compiler Step 2 (Lexical Analysis) - Convert JSX Code to an array of tokens
var tokens = this.tokenizer(newInput);
if (jsxLoader.logCompileDetails) {
console.log(tokens);
}
// Compiler Step 3 (Syntactic Analysis) - Convert Tokens to an Abstract Syntax Tree (AST)
var ast = this.parser(tokens, input);
if (jsxLoader.logCompileDetails) {
console.log(ast);
}
// Compiler Step 4 (Code Generation) - Convert AST to Code
var output = this.codeGenerator(ast, input);
return output;
},
/**
* Helper function to return line/column numbers when an error occurs
*
* @param {string} input
* @param {int} pos
* @return {string}
*/
getTextPosition: function(input, pos) {
var lines = input.substring(0, pos).split('\n');
var lineCount = lines.length;
var line = lines[lineCount - 1];
return ' at Line #: ' + lineCount + ', Column #: ' + (line.length - 1) + ', Line: ' + line.trim();
},
/**
* Check if the contents of a script appear to be minimized. If so it's likely JavaScript
* and should not be processed by the compiler. This function can be overwritten by a calling
* app if needed in case it has specific logic or comments are embedded in the minimized code.
*
* @param {string} input
* @return {bool}
*/
isMinimized: function(input) {
if (input.indexOf('\n') === -1 && (input.indexOf('if(') !== -1 || input.indexOf('}render(){return') !== -1)) {
return true;
}
return false;
},
/**
* Helper function that gets called when a '<' character is
* found to determine if it's likely an element or not.
*
* @param {string} input
* @param {number} current
* @param {number} length
* @returns {bool}
*/
isExpression: function(input, current, length) {
var pos = current + 2;
var foundName = false;
while (pos < length) {
var nextChar = input[pos];
pos++;
if (/[a-zA-Z0-9_/]/.test(nextChar)) {
if (foundName) {
break;
} else {
continue;
}
} else if (nextChar === '>') {
break;
} else if (nextChar === ' ' || nextChar === '\n' || nextChar === '\t') {
foundName = true;
continue;
} else if (nextChar === ')' || nextChar === '&' || nextChar === '|' || nextChar === '?' || nextChar === ';') {
// This happens if an less than expression uses no spaces and the
// right-hand side value is a variable. Issue #20 on GitHub.
return true;
}
}
return false;
},
/**
* Compiler Step 1 - Remove Comments from the Code
*
* All Code Comments are simply replaced with whitespace. This keeps the
* original structure of the code and allows for error messages to report on
* the correct line/column position of the error. Additionally it simplifies
* lexical analysis because there is no need to tokenize the comments.
*
* Note - this function should handle most but may not handle all comments.
* If new issues parsing are discovered this function needs to be updated to
* better handle them.
*
* @param {string} input
* @return {string}
*/
removeComments: function(input) {
var length = input.length,
newInput = new Array(length),
state = {
inCommentReact: false,
inCommentSingleLine: false,
inCommentMultiLine: false,
inStringSingleQuote: false,
inStringDoubleQuote: false,
inStringMultiLine: false,
elementCount: 0,
jsCount: 0,
},
current = 0,
char,
charNext;
function peekNext() {
return (current < length-1 ? input[current+1] : null);
}
function peekNext2() {
return (current < length-2 ? input[current+1] + input[current+2] : null);
}
while (current < length) {
char = input[current];
if (state.inCommentReact) {
if (char === '*' && peekNext2() === '/}') {
newInput[current] = ' ';
newInput[current + 1] = ' ';
current += 2;
char = ' ';
state.inCommentReact = false;
} else if (char !== '\n') {
char = ' ';
}
} else if (state.inCommentSingleLine) {
if (char === '\n') {
state.inCommentSingleLine = false;
} else {
char = ' ';
}
} else if (state.inCommentMultiLine) {
if (char == '*' && peekNext() === '/') {
newInput[current] = ' ';
current++;
char = ' ';
state.inCommentMultiLine = false;
} else if (char !== '\n') {
char = ' ';
}
} else if (state.inStringDoubleQuote) {
if (char === '"' && input[current-1] !== '\\') {
state.inStringDoubleQuote = false;
}
} else if (state.inStringSingleQuote) {
if (char === "'" && input[current-1] !== '\\') {
state.inStringSingleQuote = false;
}
} else if (state.inStringMultiLine) {
if (char === '`') {
state.inStringMultiLine = false;
}
} else {
switch (char) {
case '{':
if (peekNext2() === '/*') {
newInput[current] = ' ';
newInput[current + 1] = ' ';
current += 2;
char = ' ';
state.inCommentReact = true;
} else if (state.elementCount > 0) {
state.jsCount++;
}
break;
case '}':
if (state.elementCount > 0 && state.jsCount > 0) {
state.jsCount--;
}
break;
case '/':
if (state.elementCount === 0 || state.jsCount > 0) {
var next = peekNext();
state.inCommentSingleLine = (next === '/');
if (!state.inCommentSingleLine) {
state.inCommentMultiLine = (next === '*');
}
if (state.inCommentSingleLine || state.inCommentMultiLine) {
newInput[current] = ' ';
current++;
char = ' ';
}
}
break;
case '"':
state.inStringDoubleQuote = true;
break;
case "'":
state.inStringSingleQuote = true;
break;
case '`':
state.inStringMultiLine = true;
break;
case '<':
charNext = peekNext();
if (/[a-zA-Z>]/.test(charNext) && !this.isExpression(input, current, length)) {
state.elementCount++;
} else if (charNext === '/') {
state.elementCount--;
}
break;
case '>':
if (input[current-1] === '/' && state.elementCount > 0) {
state.elementCount--;
}
break;
}
}
newInput[current] = char;
current++;
}
return newInput.join('');
},
/**
* Compiler Step 2 (Lexical Analysis) - Convert JSX Code to an array of tokens.
*
* Warning, this function is large, contains recursive private functions, and is
* built for speed and features over readability. Using breakpoints with DevTools
* is recommended when making changes and to better understand how the code works.
*
* @param {string} input
* @return {array}
*/
tokenizer: function(input) {
var length = input.length,
current = 0,
tokens = [],
char,
pos,
loopCount = 0,
callCount = 0,
nextChar,
maxRecursiveCalls = this.maxRecursiveCalls;
// Private function to return the next React/JSX Element
function nextElementPos() {
var c = current,
char,
state = {
inStringSingleQuote: false,
inStringDoubleQuote: false,
inStringMultiLine: false,
};
while (c < length - 1) {
char = input[c];
if (state.inStringDoubleQuote) {
if (char === '"' && input[c-1] !== '\\') {
state.inStringDoubleQuote = false;
}
} else if (state.inStringSingleQuote) {
if (char === "'" && input[c-1] !== '\\') {
state.inStringSingleQuote = false;
}
} else if (state.inStringMultiLine) {
if (char === '`') {
state.inStringMultiLine = false;
}
} else {
switch (char) {
case '"':
state.inStringDoubleQuote = true;
break;
case "'":
state.inStringSingleQuote = true;
break;
case '`':
state.inStringMultiLine = true;
break;
case '<':
if (/[a-zA-Z>]/.test(input[c + 1]) && !jsxLoader.compiler.isExpression(input, c, length)) {
return c; // Start of Element found
}
break;
}
}
c++;
}
return null;
}
// Private functions to return the current or next characters without
// incrementing the counter for the current position.
function peekCurrent() {
return (current < length ? input[current] : null);
}
function peekNext() {
return (current < length ? input[current+1] : null);
}
// Safety check to prevent endless loops on unexpected errors.
// The number of loops should always be less that then string length.
function loopCheck() {
loopCount++;
if (loopCount > length) {
throw new Error('Endless loop encountered in tokenizer');
}
}
function tokenizeElement(startPosition, firstNode) {
// Safety check
callCount++;
if (callCount > maxRecursiveCalls) {
throw new Error('Call count exceeded in tokenizer. If you have a large JSX file that is valid you can increase them limit using the property `jsxLoader.compiler.maxRecursiveCalls`.');
}
// Current state of the processed text
var state = {
value: input[pos],
elementStack: 0,
elementState: [],
currentElementState: null,
inElement: true,
hasElementName: false,
elementClosed: false,
closeElement: false,
closingElement: false,
fatalError: false,
errorMessage: null,
addElementEnd: false,
breakLoop: false,
addChild: false,
addChar: true,
hasProp: false,
inValue: false,
inPropString: false,
propStringChar: null,
jsWithElement: false,
};
// Add text up to the matched position as JavaScript
if (current < startPosition && firstNode) {
tokens.push({
type: tokenTypes.js,
value: input.substring(current, startPosition),
pos: current,
});
}
// Tokenize the current React element. This loop inside the recursive function
// provides core logic to process characters one at a time. The loop from the main
// calling function is used to find JSX elements.
current = startPosition + 1;
while (current < length) {
loopCheck();
// Get the character at the current position in the input string
char = input[current];
// Handle character differently depending on if the current
// position is still inside the <element> `state.inElement`
// or if it is in a child/code section <element>{code}</element>
if (state.inElement) {
if (state.hasElementName) {
state.value += char;
current++;
state.breakLoop = false;
state.hasProp = false;
state.inValue = false;
while (current < length) {
loopCheck();
char = input[current];
current++;
if (state.inPropString && char !== state.propStringChar) {
state.value += char;
continue;
}
switch (char) {
case '=':
if (state.currentElementState.inPropJs) {
break;
}
if (state.value.trim() !== '') {
tokens.push({
type: tokenTypes.e_prop,
value: state.value,
pos: current,
});
state.hasProp = true;
state.inValue = true;
}
state.value = '';
nextChar = peekCurrent();
if (nextChar === '"' || nextChar === "'") {
state.inPropString = true;
state.propStringChar = nextChar;
current++;
} else if (nextChar === '{') {
state.currentElementState.inPropJs = true;
state.currentElementState.jsPropBracketCount = 0;
current++;
}
continue;