forked from reactjs/React.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactEnvironment.cs
532 lines (497 loc) · 16.2 KB
/
ReactEnvironment.cs
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
/*
* Copyright (c) 2014-Present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using JavaScriptEngineSwitcher.Core;
using JSPool;
using React.Exceptions;
using React.TinyIoC;
namespace React
{
/// <summary>
/// Request-specific ReactJS.NET environment. This is unique to the individual request and is
/// not shared.
/// </summary>
public class ReactEnvironment : IReactEnvironment, IDisposable
{
/// <summary>
/// JavaScript variable set when user-provided scripts have been loaded
/// </summary>
protected const string USER_SCRIPTS_LOADED_KEY = "_ReactNET_UserScripts_Loaded";
/// <summary>
/// Stack size to use for JSXTransformer if the default stack is insufficient
/// </summary>
protected const int LARGE_STACK_SIZE = 2 * 1024 * 1024;
/// <summary>
/// Factory to create JavaScript engines
/// </summary>
protected readonly IJavaScriptEngineFactory _engineFactory;
/// <summary>
/// Site-wide configuration
/// </summary>
protected readonly IReactSiteConfiguration _config;
/// <summary>
/// Cache used for storing compiled JSX
/// </summary>
protected readonly ICache _cache;
/// <summary>
/// File system wrapper
/// </summary>
protected readonly IFileSystem _fileSystem;
/// <summary>
/// Hash algorithm for file-based cache
/// </summary>
protected readonly IFileCacheHash _fileCacheHash;
/// <summary>
/// React Id generator
/// </summary>
private readonly IReactIdGenerator _reactIdGenerator;
/// <summary>
/// JSX Transformer instance for this environment
/// </summary>
protected readonly Lazy<IBabel> _babelTransformer;
/// <summary>
/// Version number of ReactJS.NET
/// </summary>
protected readonly Lazy<string> _version = new Lazy<string>(GetVersion);
/// <summary>
/// Contains an engine acquired from a pool of engines. Only used if
/// <see cref="IReactSiteConfiguration.ReuseJavaScriptEngines"/> is enabled.
/// </summary>
protected Lazy<PooledJsEngine> _engineFromPool;
/// <summary>
/// List of all components instantiated in this environment
/// </summary>
protected readonly IList<IReactComponent> _components = new List<IReactComponent>();
/// <summary>
/// Gets the <see cref="IReactEnvironment"/> for the current request. If no environment
/// has been created for the current request, creates a new one.
/// </summary>
public static IReactEnvironment Current
{
get { return AssemblyRegistration.Container.Resolve<IReactEnvironment>(); }
}
/// <summary>
/// Gets the <see cref="IReactEnvironment"/> for the current request. If no environment
/// has been created for the current request, creates a new one.
/// Also provides more specific error information in the event that ReactJS.NET is misconfigured.
/// </summary>
public static IReactEnvironment GetCurrentOrThrow
{
get
{
try
{
return Current;
}
catch (TinyIoCResolutionException ex)
{
throw new ReactNotInitialisedException(
#if NET451
"ReactJS.NET has not been initialised correctly.",
#else
"ReactJS.NET has not been initialised correctly. Please ensure you have " +
"called services.AddReact() and app.UseReact() in your Startup.cs file.",
#endif
ex
);
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactEnvironment"/> class.
/// </summary>
/// <param name="engineFactory">The JavaScript engine factory</param>
/// <param name="config">The site-wide configuration</param>
/// <param name="cache">The cache to use for JSX compilation</param>
/// <param name="fileSystem">File system wrapper</param>
/// <param name="fileCacheHash">Hash algorithm for file-based cache</param>
/// <param name="reactIdGenerator">React ID generator</param>
public ReactEnvironment(
IJavaScriptEngineFactory engineFactory,
IReactSiteConfiguration config,
ICache cache,
IFileSystem fileSystem,
IFileCacheHash fileCacheHash,
IReactIdGenerator reactIdGenerator
)
{
_engineFactory = engineFactory;
_config = config;
_cache = cache;
_fileSystem = fileSystem;
_fileCacheHash = fileCacheHash;
_reactIdGenerator = reactIdGenerator;
_babelTransformer = new Lazy<IBabel>(() =>
new Babel(this, _cache, _fileSystem, _fileCacheHash, _config)
);
_engineFromPool = new Lazy<PooledJsEngine>(() => _engineFactory.GetEngine());
}
/// <summary>
/// Gets the JavaScript engine to use for this environment.
/// </summary>
protected virtual IJsEngine Engine
{
get
{
return _config.ReuseJavaScriptEngines
? _engineFromPool.Value
: _engineFactory.GetEngineForCurrentThread();
}
}
/// <summary>
/// Gets the Babel transformer for this environment.
/// </summary>
public virtual IBabel Babel
{
get { return _babelTransformer.Value; }
}
/// <summary>
/// Gets the version of the JavaScript engine in use by ReactJS.NET
/// </summary>
public virtual string EngineVersion
{
get { return Engine.Name + " " + Engine.Version; }
}
/// <summary>
/// Gets the version number of ReactJS.NET
/// </summary>
public virtual string Version
{
get { return _version.Value; }
}
/// <summary>
/// Ensures any user-provided scripts have been loaded. This only loads JSX files; files
/// that need no transformation are loaded in JavaScriptEngineFactory.
/// </summary>
protected virtual void EnsureUserScriptsLoaded()
{
// Scripts already loaded into this environment, don't load them again
if (Engine.HasVariable(USER_SCRIPTS_LOADED_KEY) || _config == null)
{
return;
}
foreach (var file in _config.Scripts)
{
var contents = Babel.TransformFile(file);
try
{
Execute(contents);
}
catch (JsRuntimeException ex)
{
throw new ReactScriptLoadException(string.Format(
"Error while loading \"{0}\": {1}",
file,
ex.Message
));
}
}
Engine.SetVariableValue(USER_SCRIPTS_LOADED_KEY, true);
}
/// <summary>
/// Executes the provided JavaScript code.
/// </summary>
/// <param name="code">JavaScript to execute</param>
public virtual void Execute(string code)
{
try
{
Engine.Execute(code);
}
catch (JsRuntimeException ex)
{
throw WrapJavaScriptRuntimeException(ex);
}
}
/// <summary>
/// Executes the provided JavaScript code, returning a result of the specified type.
/// </summary>
/// <typeparam name="T">Type to return</typeparam>
/// <param name="code">Code to execute</param>
/// <returns>Result of the JavaScript code</returns>
public virtual T Execute<T>(string code)
{
try
{
return Engine.Evaluate<T>(code);
}
catch (JsRuntimeException ex)
{
throw WrapJavaScriptRuntimeException(ex);
}
}
/// <summary>
/// Executes the provided JavaScript function, returning a result of the specified type.
/// </summary>
/// <typeparam name="T">Type to return</typeparam>
/// <param name="function">JavaScript function to execute</param>
/// <param name="args">Arguments to pass to function</param>
/// <returns>Result of the JavaScript code</returns>
public virtual T Execute<T>(string function, params object[] args)
{
try
{
return Engine.CallFunctionReturningJson<T>(function, args);
}
catch (JsRuntimeException ex)
{
throw WrapJavaScriptRuntimeException(ex);
}
}
/// <summary>
/// Determines if the specified variable exists in the JavaScript engine
/// </summary>
/// <param name="name">Name of the variable</param>
/// <returns><c>true</c> if the variable exists; <c>false</c> otherwise</returns>
public virtual bool HasVariable(string name)
{
try
{
return Engine.HasVariable(name);
}
catch (JsRuntimeException ex)
{
throw WrapJavaScriptRuntimeException(ex);
}
}
/// <summary>
/// Creates an instance of the specified React JavaScript component.
/// </summary>
/// <typeparam name="T">Type of the props</typeparam>
/// <param name="componentName">Name of the component</param>
/// <param name="props">Props to use</param>
/// <param name="containerId">ID to use for the container HTML tag. Defaults to an auto-generated ID</param>
/// <param name="clientOnly">True if server-side rendering will be bypassed. Defaults to false.</param>
/// <param name="serverOnly">True if this component only should be rendered server-side. Defaults to false.</param>
/// <returns>The component</returns>
public virtual IReactComponent CreateComponent<T>(string componentName, T props, string containerId = null, bool clientOnly = false, bool serverOnly = false)
{
if (!clientOnly)
{
EnsureUserScriptsLoaded();
}
var component = new ReactComponent(this, _config, _reactIdGenerator, componentName, containerId)
{
Props = props,
ServerOnly = serverOnly
};
_components.Add(component);
return component;
}
/// <summary>
/// Adds the provided <see cref="IReactComponent"/> to the list of components to render client side.
/// </summary>
/// <param name="component">Component to add to client side render list</param>
/// <param name="clientOnly">True if server-side rendering will be bypassed. Defaults to false.</param>
/// <returns>The component</returns>
public virtual IReactComponent CreateComponent(IReactComponent component, bool clientOnly = false)
{
if (!clientOnly)
{
EnsureUserScriptsLoaded();
}
_components.Add(component);
return component;
}
/// <summary>
/// Renders the JavaScript required to initialise all components client-side. This will
/// attach event handlers to the server-rendered HTML.
/// </summary>
/// <param name="clientOnly">True if server-side rendering will be bypassed. Defaults to false.</param>
/// <returns>JavaScript for all components</returns>
public virtual string GetInitJavaScript(bool clientOnly = false)
{
using (var writer = new StringWriter())
{
GetInitJavaScript(writer, clientOnly);
return writer.ToString();
}
}
/// <summary>
/// Renders the JavaScript required to initialise all components client-side. This will
/// attach event handlers to the server-rendered HTML.
/// </summary>
/// <param name="writer">The <see cref="T:System.IO.TextWriter" /> to which the content is written</param>
/// <param name="clientOnly">True if server-side rendering will be bypassed. Defaults to false.</param>
/// <returns>JavaScript for all components</returns>
public virtual void GetInitJavaScript(TextWriter writer, bool clientOnly = false)
{
// Propagate any server-side console.log calls to corresponding client-side calls.
if (!clientOnly)
{
var consoleCalls = Execute<string>("console.getCalls()");
writer.Write(consoleCalls);
}
foreach (var component in _components)
{
if (!component.ServerOnly)
{
component.RenderJavaScript(writer);
writer.WriteLine(';');
}
}
}
/// <summary>
/// Attempts to execute the provided JavaScript code using a non-pooled JavaScript engine (ie.
/// creates a new JS engine per-thread). This is because Babel uses a LOT of memory, so we
/// should completely dispose any engines that have loaded Babel in order to conserve memory.
///
/// If an exception is thrown, retries the execution using a new thread (and hence a new engine)
/// with a larger maximum stack size.
/// This is required because JSXTransformer uses a huge stack which ends up being larger
/// than what ASP.NET allows by default (256 KB).
/// </summary>
/// <typeparam name="T">Type to return from JavaScript call</typeparam>
/// <param name="function">JavaScript function to execute</param>
/// <param name="args">Arguments to pass to function</param>
/// <returns>Result returned from JavaScript code</returns>
public virtual T ExecuteWithBabel<T>(string function, params object[] args)
{
var engine = _engineFactory.GetEngineForCurrentThread();
EnsureBabelLoaded(engine);
#if NET40
try
{
return engine.CallFunctionReturningJson<T>(function, args);
}
catch (Exception)
{
// Assume the exception MAY be an "out of stack space" error. Try running the code
// in a different thread with larger stack. If the same exception occurs, we know
// it wasn't a stack space issue.
T result = default(T);
Exception innerEx = null;
var thread = new Thread(() =>
{
// New engine will be created here (as this is a new thread)
var threadEngine = _engineFactory.GetEngineForCurrentThread();
EnsureBabelLoaded(threadEngine);
try
{
result = threadEngine.CallFunctionReturningJson<T>(function, args);
}
catch (Exception threadEx)
{
// Unhandled exceptions in threads kill the whole process.
// Pass the exception back to the parent thread to rethrow.
innerEx = threadEx;
}
finally
{
_engineFactory.DisposeEngineForCurrentThread();
}
}, LARGE_STACK_SIZE);
thread.Start();
thread.Join();
// Rethrow any exceptions that occured in the thread
if (innerEx != null)
{
throw innerEx;
}
return result;
}
#else
return engine.CallFunctionReturningJson<T>(function, args);
#endif
}
/// <summary>
/// Gets the ReactJS.NET version number. Use <see cref="Version" /> instead.
/// </summary>
private static string GetVersion()
{
#if NET40
var assembly = Assembly.GetExecutingAssembly();
var rawVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
#else
var assembly = typeof(ReactEnvironment).GetTypeInfo().Assembly;
var rawVersion = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
#endif
var lastDot = rawVersion.LastIndexOf('.');
var version = rawVersion.Substring(0, lastDot);
var build = rawVersion.Substring(lastDot + 1);
return string.Format("{0} (build {1})", version, build);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
_engineFactory.DisposeEngineForCurrentThread();
ReturnEngineToPool();
}
/// <summary>
/// Returns the currently held JS engine to the pool. (no-op if engine pooling is disabled)
/// </summary>
public void ReturnEngineToPool()
{
if (_engineFromPool.IsValueCreated)
{
_engineFromPool.Value.Dispose();
_engineFromPool = new Lazy<PooledJsEngine>(() => _engineFactory.GetEngine());
}
}
/// <summary>
/// Updates the Message of a <see cref="JsRuntimeException"/> to be more useful, containing
/// the line and column numbers.
/// </summary>
/// <param name="ex">Original exception</param>
/// <returns>New exception</returns>
protected virtual JsRuntimeException WrapJavaScriptRuntimeException(JsRuntimeException ex)
{
return new JsRuntimeException(string.Format(
"{0}\r\nLine: {1}\r\nColumn:{2}",
ex.Message,
ex.LineNumber,
ex.ColumnNumber
), ex.EngineName, ex.EngineVersion)
{
ErrorCode = ex.ErrorCode,
Category = ex.Category,
LineNumber = ex.LineNumber,
ColumnNumber = ex.ColumnNumber,
SourceFragment = ex.SourceFragment,
Source = ex.Source,
};
}
/// <summary>
/// Gets the site-wide configuration.
/// </summary>
public virtual IReactSiteConfiguration Configuration
{
get { return _config; }
}
/// <summary>
/// Ensures that Babel has been loaded into the JavaScript engine.
/// </summary>
private void EnsureBabelLoaded(IJsEngine engine)
{
// If Babel is disabled in the config, don't even try loading it
if (!_config.LoadBabel)
{
throw new BabelNotLoadedException();
}
var babelLoaded = engine.Evaluate<bool>("typeof ReactNET_transform !== 'undefined'");
if (!babelLoaded)
{
#if NET40
var assembly = typeof(ReactEnvironment).Assembly;
#else
var assembly = typeof(ReactEnvironment).GetTypeInfo().Assembly;
#endif
engine.ExecuteResource("React.Core.Resources.babel.generated.min.js", assembly);
}
}
}
}