@squiz/render-runtime-lib 1.2.1-alpha.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +11 -0
  2. package/lib/component-runner/component-runner.spec.d.ts +1 -0
  3. package/lib/component-runner/index.d.ts +19 -0
  4. package/lib/component-runner/worker/WorkerPool.d.ts +50 -0
  5. package/lib/component-runner/worker/getRuntimeModules.d.ts +1 -0
  6. package/lib/component-runner/worker/worker-root.d.ts +1 -0
  7. package/lib/index.d.ts +9 -0
  8. package/lib/index.js +63783 -0
  9. package/lib/index.js.map +7 -0
  10. package/lib/render-runtime-lib.spec.d.ts +1 -0
  11. package/lib/test/helpers/fixtures.d.ts +6 -0
  12. package/lib/test/helpers/stack.d.ts +2 -0
  13. package/lib/utils/convertFunctionStaticFilesToFqdn.d.ts +1 -0
  14. package/lib/utils/log.d.ts +3 -0
  15. package/lib/webserver/app.d.ts +2 -0
  16. package/lib/webserver/controllers/core.d.ts +3 -0
  17. package/lib/webserver/controllers/definition.d.ts +3 -0
  18. package/lib/webserver/controllers/definition.spec.d.ts +1 -0
  19. package/lib/webserver/controllers/index.d.ts +4 -0
  20. package/lib/webserver/controllers/render.d.ts +3 -0
  21. package/lib/webserver/controllers/render.spec.d.ts +1 -0
  22. package/lib/webserver/controllers/static.d.ts +3 -0
  23. package/lib/webserver/controllers/static.spec.d.ts +1 -0
  24. package/lib/webserver/index.d.ts +15 -0
  25. package/lib/worker/bridge.js +1000 -0
  26. package/lib/worker/compiler.js +87 -0
  27. package/lib/worker/events.js +977 -0
  28. package/lib/worker/nodevm.js +503 -0
  29. package/lib/worker/resolver-compat.js +342 -0
  30. package/lib/worker/resolver.js +882 -0
  31. package/lib/worker/script.js +388 -0
  32. package/lib/worker/setup-node-sandbox.js +464 -0
  33. package/lib/worker/setup-sandbox.js +453 -0
  34. package/lib/worker/transformer.js +176 -0
  35. package/lib/worker/vm.js +539 -0
  36. package/lib/worker/worker-root.js +40146 -0
  37. package/lib/worker/worker-root.js.map +7 -0
  38. package/package.json +55 -0
@@ -0,0 +1,453 @@
1
+ /* global host, bridge, data, context */
2
+
3
+ 'use strict';
4
+
5
+ const {
6
+ Object: localObject,
7
+ Array: localArray,
8
+ Error: LocalError,
9
+ Reflect: localReflect,
10
+ Proxy: LocalProxy,
11
+ WeakMap: LocalWeakMap,
12
+ Function: localFunction,
13
+ Promise: localPromise,
14
+ eval: localEval
15
+ } = global;
16
+
17
+ const {
18
+ freeze: localObjectFreeze
19
+ } = localObject;
20
+
21
+ const {
22
+ getPrototypeOf: localReflectGetPrototypeOf,
23
+ apply: localReflectApply,
24
+ deleteProperty: localReflectDeleteProperty,
25
+ has: localReflectHas,
26
+ defineProperty: localReflectDefineProperty,
27
+ setPrototypeOf: localReflectSetPrototypeOf,
28
+ getOwnPropertyDescriptor: localReflectGetOwnPropertyDescriptor
29
+ } = localReflect;
30
+
31
+ const {
32
+ isArray: localArrayIsArray
33
+ } = localArray;
34
+
35
+ const {
36
+ ensureThis,
37
+ ReadOnlyHandler,
38
+ from,
39
+ fromWithFactory,
40
+ readonlyFactory,
41
+ connect,
42
+ addProtoMapping,
43
+ VMError,
44
+ ReadOnlyMockHandler
45
+ } = bridge;
46
+
47
+ const {
48
+ allowAsync,
49
+ GeneratorFunction,
50
+ AsyncFunction,
51
+ AsyncGeneratorFunction
52
+ } = data;
53
+
54
+ const localWeakMapGet = LocalWeakMap.prototype.get;
55
+
56
+ function localUnexpected() {
57
+ return new VMError('Should not happen');
58
+ }
59
+
60
+ // global is originally prototype of host.Object so it can be used to climb up from the sandbox.
61
+ if (!localReflectSetPrototypeOf(context, localObject.prototype)) throw localUnexpected();
62
+
63
+ Object.defineProperties(global, {
64
+ global: {value: global, writable: true, configurable: true, enumerable: true},
65
+ globalThis: {value: global, writable: true, configurable: true},
66
+ GLOBAL: {value: global, writable: true, configurable: true},
67
+ root: {value: global, writable: true, configurable: true}
68
+ });
69
+
70
+ if (!localReflectDefineProperty(global, 'VMError', {
71
+ __proto__: null,
72
+ value: VMError,
73
+ writable: true,
74
+ enumerable: false,
75
+ configurable: true
76
+ })) throw localUnexpected();
77
+
78
+ // Fixes buffer unsafe allocation
79
+ /* eslint-disable no-use-before-define */
80
+ class BufferHandler extends ReadOnlyHandler {
81
+
82
+ apply(target, thiz, args) {
83
+ if (args.length > 0 && typeof args[0] === 'number') {
84
+ return LocalBuffer.alloc(args[0]);
85
+ }
86
+ return localReflectApply(LocalBuffer.from, LocalBuffer, args);
87
+ }
88
+
89
+ construct(target, args, newTarget) {
90
+ if (args.length > 0 && typeof args[0] === 'number') {
91
+ return LocalBuffer.alloc(args[0]);
92
+ }
93
+ return localReflectApply(LocalBuffer.from, LocalBuffer, args);
94
+ }
95
+
96
+ }
97
+ /* eslint-enable no-use-before-define */
98
+
99
+ const LocalBuffer = fromWithFactory(obj => new BufferHandler(obj), host.Buffer);
100
+
101
+
102
+ if (!localReflectDefineProperty(global, 'Buffer', {
103
+ __proto__: null,
104
+ value: LocalBuffer,
105
+ writable: true,
106
+ enumerable: false,
107
+ configurable: true
108
+ })) throw localUnexpected();
109
+
110
+ addProtoMapping(LocalBuffer.prototype, host.Buffer.prototype, 'Uint8Array');
111
+
112
+ /**
113
+ *
114
+ * @param {*} size Size of new buffer
115
+ * @this LocalBuffer
116
+ * @return {LocalBuffer}
117
+ */
118
+ function allocUnsafe(size) {
119
+ return LocalBuffer.alloc(size);
120
+ }
121
+
122
+ connect(allocUnsafe, host.Buffer.allocUnsafe);
123
+
124
+ /**
125
+ *
126
+ * @param {*} size Size of new buffer
127
+ * @this LocalBuffer
128
+ * @return {LocalBuffer}
129
+ */
130
+ function allocUnsafeSlow(size) {
131
+ return LocalBuffer.alloc(size);
132
+ }
133
+
134
+ connect(allocUnsafeSlow, host.Buffer.allocUnsafeSlow);
135
+
136
+ /**
137
+ * Replacement for Buffer inspect
138
+ *
139
+ * @param {*} recurseTimes
140
+ * @param {*} ctx
141
+ * @this LocalBuffer
142
+ * @return {string}
143
+ */
144
+ function inspect(recurseTimes, ctx) {
145
+ // Mimic old behavior, could throw but didn't pass a test.
146
+ const max = host.INSPECT_MAX_BYTES;
147
+ const actualMax = Math.min(max, this.length);
148
+ const remaining = this.length - max;
149
+ let str = this.hexSlice(0, actualMax).replace(/(.{2})/g, '$1 ').trim();
150
+ if (remaining > 0) str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`;
151
+ return `<${this.constructor.name} ${str}>`;
152
+ }
153
+
154
+ connect(inspect, host.Buffer.prototype.inspect);
155
+
156
+ connect(localFunction.prototype.bind, host.Function.prototype.bind);
157
+
158
+ connect(localObject.prototype.__defineGetter__, host.Object.prototype.__defineGetter__);
159
+ connect(localObject.prototype.__defineSetter__, host.Object.prototype.__defineSetter__);
160
+ connect(localObject.prototype.__lookupGetter__, host.Object.prototype.__lookupGetter__);
161
+ connect(localObject.prototype.__lookupSetter__, host.Object.prototype.__lookupSetter__);
162
+
163
+ /*
164
+ * PrepareStackTrace sanitization
165
+ */
166
+
167
+ const oldPrepareStackTraceDesc = localReflectGetOwnPropertyDescriptor(LocalError, 'prepareStackTrace');
168
+
169
+ let currentPrepareStackTrace = LocalError.prepareStackTrace;
170
+ const wrappedPrepareStackTrace = new LocalWeakMap();
171
+ if (typeof currentPrepareStackTrace === 'function') {
172
+ wrappedPrepareStackTrace.set(currentPrepareStackTrace, currentPrepareStackTrace);
173
+ }
174
+
175
+ let OriginalCallSite;
176
+ LocalError.prepareStackTrace = (e, sst) => {
177
+ OriginalCallSite = sst[0].constructor;
178
+ };
179
+ new LocalError().stack;
180
+ if (typeof OriginalCallSite === 'function') {
181
+ LocalError.prepareStackTrace = undefined;
182
+
183
+ function makeCallSiteGetters(list) {
184
+ const callSiteGetters = [];
185
+ for (let i=0; i<list.length; i++) {
186
+ const name = list[i];
187
+ const func = OriginalCallSite.prototype[name];
188
+ callSiteGetters[i] = {__proto__: null,
189
+ name,
190
+ propName: '_' + name,
191
+ func: (thiz) => {
192
+ return localReflectApply(func, thiz, []);
193
+ }
194
+ };
195
+ }
196
+ return callSiteGetters;
197
+ }
198
+
199
+ function applyCallSiteGetters(thiz, callSite, getters) {
200
+ for (let i=0; i<getters.length; i++) {
201
+ const getter = getters[i];
202
+ localReflectDefineProperty(thiz, getter.propName, {
203
+ __proto__: null,
204
+ value: getter.func(callSite)
205
+ });
206
+ }
207
+ }
208
+
209
+ const callSiteGetters = makeCallSiteGetters([
210
+ 'getTypeName',
211
+ 'getFunctionName',
212
+ 'getMethodName',
213
+ 'getFileName',
214
+ 'getLineNumber',
215
+ 'getColumnNumber',
216
+ 'getEvalOrigin',
217
+ 'isToplevel',
218
+ 'isEval',
219
+ 'isNative',
220
+ 'isConstructor',
221
+ 'isAsync',
222
+ 'isPromiseAll',
223
+ 'getPromiseIndex'
224
+ ]);
225
+
226
+ class CallSite {
227
+ constructor(callSite) {
228
+ applyCallSiteGetters(this, callSite, callSiteGetters);
229
+ }
230
+ getThis() {
231
+ return undefined;
232
+ }
233
+ getFunction() {
234
+ return undefined;
235
+ }
236
+ toString() {
237
+ return 'CallSite {}';
238
+ }
239
+ }
240
+
241
+
242
+ for (let i=0; i<callSiteGetters.length; i++) {
243
+ const name = callSiteGetters[i].name;
244
+ const funcProp = localReflectGetOwnPropertyDescriptor(OriginalCallSite.prototype, name);
245
+ if (!funcProp) continue;
246
+ const propertyName = callSiteGetters[i].propName;
247
+ const func = {func() {
248
+ return this[propertyName];
249
+ }}.func;
250
+ const nameProp = localReflectGetOwnPropertyDescriptor(func, 'name');
251
+ if (!nameProp) throw localUnexpected();
252
+ nameProp.value = name;
253
+ if (!localReflectDefineProperty(func, 'name', nameProp)) throw localUnexpected();
254
+ funcProp.value = func;
255
+ if (!localReflectDefineProperty(CallSite.prototype, name, funcProp)) throw localUnexpected();
256
+ }
257
+
258
+ if (!localReflectDefineProperty(LocalError, 'prepareStackTrace', {
259
+ configurable: false,
260
+ enumerable: false,
261
+ get() {
262
+ return currentPrepareStackTrace;
263
+ },
264
+ set(value) {
265
+ if (typeof(value) !== 'function') {
266
+ currentPrepareStackTrace = value;
267
+ return;
268
+ }
269
+ const wrapped = localReflectApply(localWeakMapGet, wrappedPrepareStackTrace, [value]);
270
+ if (wrapped) {
271
+ currentPrepareStackTrace = wrapped;
272
+ return;
273
+ }
274
+ const newWrapped = (error, sst) => {
275
+ if (localArrayIsArray(sst)) {
276
+ for (let i=0; i < sst.length; i++) {
277
+ const cs = sst[i];
278
+ if (typeof cs === 'object' && localReflectGetPrototypeOf(cs) === OriginalCallSite.prototype) {
279
+ sst[i] = new CallSite(cs);
280
+ }
281
+ }
282
+ }
283
+ return value(error, sst);
284
+ };
285
+ wrappedPrepareStackTrace.set(value, newWrapped);
286
+ wrappedPrepareStackTrace.set(newWrapped, newWrapped);
287
+ currentPrepareStackTrace = newWrapped;
288
+ }
289
+ })) throw localUnexpected();
290
+ } else if (oldPrepareStackTraceDesc) {
291
+ localReflectDefineProperty(LocalError, 'prepareStackTrace', oldPrepareStackTraceDesc);
292
+ } else {
293
+ localReflectDeleteProperty(LocalError, 'prepareStackTrace');
294
+ }
295
+
296
+ /*
297
+ * Exception sanitization
298
+ */
299
+
300
+ const withProxy = localObjectFreeze({
301
+ __proto__: null,
302
+ has(target, key) {
303
+ if (key === host.INTERNAL_STATE_NAME) return false;
304
+ return localReflectHas(target, key);
305
+ }
306
+ });
307
+
308
+ const interanState = localObjectFreeze({
309
+ __proto__: null,
310
+ wrapWith(x) {
311
+ if (x === null || x === undefined) return x;
312
+ return new LocalProxy(localObject(x), withProxy);
313
+ },
314
+ handleException: ensureThis,
315
+ import(what) {
316
+ throw new VMError('Dynamic Import not supported');
317
+ }
318
+ });
319
+
320
+ if (!localReflectDefineProperty(global, host.INTERNAL_STATE_NAME, {
321
+ __proto__: null,
322
+ configurable: false,
323
+ enumerable: false,
324
+ writable: false,
325
+ value: interanState
326
+ })) throw localUnexpected();
327
+
328
+ /*
329
+ * Eval sanitization
330
+ */
331
+
332
+ function throwAsync() {
333
+ return new VMError('Async not available');
334
+ }
335
+
336
+ function makeFunction(inputArgs, isAsync, isGenerator) {
337
+ const lastArgs = inputArgs.length - 1;
338
+ let code = lastArgs >= 0 ? `${inputArgs[lastArgs]}` : '';
339
+ let args = lastArgs > 0 ? `${inputArgs[0]}` : '';
340
+ for (let i = 1; i < lastArgs; i++) {
341
+ args += `,${inputArgs[i]}`;
342
+ }
343
+ try {
344
+ code = host.transformAndCheck(args, code, isAsync, isGenerator, allowAsync);
345
+ } catch (e) {
346
+ throw bridge.from(e);
347
+ }
348
+ return localEval(code);
349
+ }
350
+
351
+ const FunctionHandler = {
352
+ __proto__: null,
353
+ apply(target, thiz, args) {
354
+ return makeFunction(args, this.isAsync, this.isGenerator);
355
+ },
356
+ construct(target, args, newTarget) {
357
+ return makeFunction(args, this.isAsync, this.isGenerator);
358
+ }
359
+ };
360
+
361
+ const EvalHandler = {
362
+ __proto__: null,
363
+ apply(target, thiz, args) {
364
+ if (args.length === 0) return undefined;
365
+ let code = `${args[0]}`;
366
+ try {
367
+ code = host.transformAndCheck(null, code, false, false, allowAsync);
368
+ } catch (e) {
369
+ throw bridge.from(e);
370
+ }
371
+ return localEval(code);
372
+ }
373
+ };
374
+
375
+ const AsyncErrorHandler = {
376
+ __proto__: null,
377
+ apply(target, thiz, args) {
378
+ throw throwAsync();
379
+ },
380
+ construct(target, args, newTarget) {
381
+ throw throwAsync();
382
+ }
383
+ };
384
+
385
+ function makeCheckFunction(isAsync, isGenerator) {
386
+ if (isAsync && !allowAsync) return AsyncErrorHandler;
387
+ return {
388
+ __proto__: FunctionHandler,
389
+ isAsync,
390
+ isGenerator
391
+ };
392
+ }
393
+
394
+ function overrideWithProxy(obj, prop, value, handler) {
395
+ const proxy = new LocalProxy(value, handler);
396
+ if (!localReflectDefineProperty(obj, prop, {__proto__: null, value: proxy})) throw localUnexpected();
397
+ return proxy;
398
+ }
399
+
400
+ const proxiedFunction = overrideWithProxy(localFunction.prototype, 'constructor', localFunction, makeCheckFunction(false, false));
401
+ if (GeneratorFunction) {
402
+ if (!localReflectSetPrototypeOf(GeneratorFunction, proxiedFunction)) throw localUnexpected();
403
+ overrideWithProxy(GeneratorFunction.prototype, 'constructor', GeneratorFunction, makeCheckFunction(false, true));
404
+ }
405
+ if (AsyncFunction) {
406
+ if (!localReflectSetPrototypeOf(AsyncFunction, proxiedFunction)) throw localUnexpected();
407
+ overrideWithProxy(AsyncFunction.prototype, 'constructor', AsyncFunction, makeCheckFunction(true, false));
408
+ }
409
+ if (AsyncGeneratorFunction) {
410
+ if (!localReflectSetPrototypeOf(AsyncGeneratorFunction, proxiedFunction)) throw localUnexpected();
411
+ overrideWithProxy(AsyncGeneratorFunction.prototype, 'constructor', AsyncGeneratorFunction, makeCheckFunction(true, true));
412
+ }
413
+
414
+ global.Function = proxiedFunction;
415
+ global.eval = new LocalProxy(localEval, EvalHandler);
416
+
417
+ /*
418
+ * Promise sanitization
419
+ */
420
+
421
+ if (localPromise && !allowAsync) {
422
+
423
+ const PromisePrototype = localPromise.prototype;
424
+
425
+ overrideWithProxy(PromisePrototype, 'then', PromisePrototype.then, AsyncErrorHandler);
426
+ // This seems not to work, and will produce
427
+ // UnhandledPromiseRejectionWarning: TypeError: Method Promise.prototype.then called on incompatible receiver [object Object].
428
+ // This is likely caused since the host.Promise.prototype.then cannot use the VM Proxy object.
429
+ // Contextify.connect(host.Promise.prototype.then, Promise.prototype.then);
430
+
431
+ if (PromisePrototype.finally) {
432
+ overrideWithProxy(PromisePrototype, 'finally', PromisePrototype.finally, AsyncErrorHandler);
433
+ // Contextify.connect(host.Promise.prototype.finally, Promise.prototype.finally);
434
+ }
435
+ if (Promise.prototype.catch) {
436
+ overrideWithProxy(PromisePrototype, 'catch', PromisePrototype.catch, AsyncErrorHandler);
437
+ // Contextify.connect(host.Promise.prototype.catch, Promise.prototype.catch);
438
+ }
439
+
440
+ }
441
+
442
+ function readonly(other, mock) {
443
+ // Note: other@other(unsafe) mock@other(unsafe) returns@this(unsafe) throws@this(unsafe)
444
+ if (!mock) return fromWithFactory(readonlyFactory, other);
445
+ const tmock = from(mock);
446
+ return fromWithFactory(obj=>new ReadOnlyMockHandler(obj, tmock), other);
447
+ }
448
+
449
+ return {
450
+ __proto__: null,
451
+ readonly,
452
+ global
453
+ };
@@ -0,0 +1,176 @@
1
+
2
+ const {Parser: AcornParser, isNewLine: acornIsNewLine, getLineInfo: acornGetLineInfo} = require('acorn');
3
+ const {full: acornWalkFull} = require('acorn-walk');
4
+
5
+ const INTERNAL_STATE_NAME = 'VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL';
6
+
7
+ function assertType(node, type) {
8
+ if (!node) throw new Error(`None existent node expected '${type}'`);
9
+ if (node.type !== type) throw new Error(`Invalid node type '${node.type}' expected '${type}'`);
10
+ return node;
11
+ }
12
+
13
+ function makeNiceSyntaxError(message, code, filename, location, tokenizer) {
14
+ const loc = acornGetLineInfo(code, location);
15
+ let end = location;
16
+ while (end < code.length && !acornIsNewLine(code.charCodeAt(end))) {
17
+ end++;
18
+ }
19
+ let markerEnd = tokenizer.start === location ? tokenizer.end : location + 1;
20
+ if (!markerEnd || markerEnd > end) markerEnd = end;
21
+ let markerLen = markerEnd - location;
22
+ if (markerLen <= 0) markerLen = 1;
23
+ if (message === 'Unexpected token') {
24
+ const type = tokenizer.type;
25
+ if (type.label === 'name' || type.label === 'privateId') {
26
+ message = 'Unexpected identifier';
27
+ } else if (type.label === 'eof') {
28
+ message = 'Unexpected end of input';
29
+ } else if (type.label === 'num') {
30
+ message = 'Unexpected number';
31
+ } else if (type.label === 'string') {
32
+ message = 'Unexpected string';
33
+ } else if (type.label === 'regexp') {
34
+ message = 'Unexpected token \'/\'';
35
+ markerLen = 1;
36
+ } else {
37
+ const token = tokenizer.value || type.label;
38
+ message = `Unexpected token '${token}'`;
39
+ }
40
+ }
41
+ const error = new SyntaxError(message);
42
+ if (!filename) return error;
43
+ const line = code.slice(location - loc.column, end);
44
+ const marker = line.slice(0, loc.column).replace(/\S/g, ' ') + '^'.repeat(markerLen);
45
+ error.stack = `${filename}:${loc.line}\n${line}\n${marker}\n\n${error.stack}`;
46
+ return error;
47
+ }
48
+
49
+ function transformer(args, body, isAsync, isGenerator, filename) {
50
+ let code;
51
+ let argsOffset;
52
+ if (args === null) {
53
+ code = body;
54
+ } else {
55
+ code = isAsync ? '(async function' : '(function';
56
+ if (isGenerator) code += '*';
57
+ code += ' anonymous(';
58
+ code += args;
59
+ argsOffset = code.length;
60
+ code += '\n) {\n';
61
+ code += body;
62
+ code += '\n})';
63
+ }
64
+
65
+ const parser = new AcornParser({
66
+ __proto__: null,
67
+ ecmaVersion: 2022,
68
+ allowAwaitOutsideFunction: args === null && isAsync,
69
+ allowReturnOutsideFunction: args === null
70
+ }, code);
71
+ let ast;
72
+ try {
73
+ ast = parser.parse();
74
+ } catch (e) {
75
+ // Try to generate a nicer error message.
76
+ if (e instanceof SyntaxError && e.pos !== undefined) {
77
+ let message = e.message;
78
+ const match = message.match(/^(.*) \(\d+:\d+\)$/);
79
+ if (match) message = match[1];
80
+ e = makeNiceSyntaxError(message, code, filename, e.pos, parser);
81
+ }
82
+ throw e;
83
+ }
84
+
85
+ if (args !== null) {
86
+ const pBody = assertType(ast, 'Program').body;
87
+ if (pBody.length !== 1) throw new SyntaxError('Single function literal required');
88
+ const expr = pBody[0];
89
+ if (expr.type !== 'ExpressionStatement') throw new SyntaxError('Single function literal required');
90
+ const func = expr.expression;
91
+ if (func.type !== 'FunctionExpression') throw new SyntaxError('Single function literal required');
92
+ if (func.body.start !== argsOffset + 3) throw new SyntaxError('Unexpected end of arg string');
93
+ }
94
+
95
+ const insertions = [];
96
+ let hasAsync = false;
97
+
98
+ const TO_LEFT = -100;
99
+ const TO_RIGHT = 100;
100
+
101
+ let internStateValiable = undefined;
102
+
103
+ acornWalkFull(ast, (node, state, type) => {
104
+ if (type === 'Function') {
105
+ if (node.async) hasAsync = true;
106
+ }
107
+ const nodeType = node.type;
108
+ if (nodeType === 'CatchClause') {
109
+ const param = node.param;
110
+ if (param) {
111
+ const name = assertType(param, 'Identifier').name;
112
+ const cBody = assertType(node.body, 'BlockStatement');
113
+ if (cBody.body.length > 0) {
114
+ insertions.push({
115
+ __proto__: null,
116
+ pos: cBody.body[0].start,
117
+ order: TO_LEFT,
118
+ code: `${name}=${INTERNAL_STATE_NAME}.handleException(${name});`
119
+ });
120
+ }
121
+ }
122
+ } else if (nodeType === 'WithStatement') {
123
+ insertions.push({
124
+ __proto__: null,
125
+ pos: node.object.start,
126
+ order: TO_LEFT,
127
+ code: INTERNAL_STATE_NAME + '.wrapWith('
128
+ });
129
+ insertions.push({
130
+ __proto__: null,
131
+ pos: node.object.end,
132
+ order: TO_RIGHT,
133
+ code: ')'
134
+ });
135
+ } else if (nodeType === 'Identifier') {
136
+ if (node.name === INTERNAL_STATE_NAME) {
137
+ if (internStateValiable === undefined || internStateValiable.start > node.start) {
138
+ internStateValiable = node;
139
+ }
140
+ }
141
+ } else if (nodeType === 'ImportExpression') {
142
+ insertions.push({
143
+ __proto__: null,
144
+ pos: node.start,
145
+ order: TO_RIGHT,
146
+ code: INTERNAL_STATE_NAME + '.'
147
+ });
148
+ }
149
+ });
150
+
151
+ if (internStateValiable) {
152
+ throw makeNiceSyntaxError('Use of internal vm2 state variable', code, filename, internStateValiable.start, {
153
+ __proto__: null,
154
+ start: internStateValiable.start,
155
+ end: internStateValiable.end
156
+ });
157
+ }
158
+
159
+ if (insertions.length === 0) return {__proto__: null, code, hasAsync};
160
+
161
+ insertions.sort((a, b) => (a.pos == b.pos ? a.order - b.order : a.pos - b.pos));
162
+
163
+ let ncode = '';
164
+ let curr = 0;
165
+ for (let i = 0; i < insertions.length; i++) {
166
+ const change = insertions[i];
167
+ ncode += code.substring(curr, change.pos) + change.code;
168
+ curr = change.pos;
169
+ }
170
+ ncode += code.substring(curr);
171
+
172
+ return {__proto__: null, code: ncode, hasAsync};
173
+ }
174
+
175
+ exports.INTERNAL_STATE_NAME = INTERNAL_STATE_NAME;
176
+ exports.transformer = transformer;