• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

overlookmotel / livepack / 6897326446

16 Nov 2023 10:36PM UTC coverage: 90.374% (+0.06%) from 90.317%
6897326446

push

github

overlookmotel
TODO

4777 of 5155 branches covered (0.0%)

Branch coverage included in aggregate %.

12901 of 14406 relevant lines covered (89.55%)

13328.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.52
/lib/serialize/parseFunction.js
1
/* --------------------
64✔
2
 * livepack module
64✔
3
 * Parse function code
64✔
4
 * ------------------*/
64✔
5

64✔
6
'use strict';
64✔
7

64✔
8
// Modules
64✔
9
const pathJoin = require('path').join,
64✔
10
        {isString} = require('is-it-type'),
64✔
11
        mapValues = require('lodash/mapValues'),
64✔
12
        t = require('@babel/types');
64✔
13

64✔
14
// Imports
64✔
15
const {isJsIdentifier, isNumberKey, setAddFrom} = require('./utils.js'),
64✔
16
        {
64✔
17
                isReservedVarName, createArrayOrPush, combineArraysWithDedup,
64✔
18
                getProp, getProps, setProp, traverseAll
64✔
19
        } = require('../shared/functions.js'),
64✔
20
        {
64✔
21
                SUPER_CALL, SUPER_EXPRESSION, CONST_VIOLATION_CONST, CONST_VIOLATION_FUNCTION_SILENT
64✔
22
        } = require('../shared/constants.js'),
64✔
23
        assertBug = require('../shared/assertBug.js');
64✔
24

64✔
25
// Constants
64✔
26
const RUNTIME_DIR_PATH = pathJoin(__dirname, '../runtime/');
64✔
27

64✔
28
// Exports
64✔
29

64✔
30
/**
64✔
31
 * Assemble AST for function code, identify Identifier nodes referring to internal/external variables,
64✔
32
 * replace const violations, transpile `super`, get other info about function.
64✔
33
 * Most of this information is pre-prepared by instrumentation, just needs some late processing here.
64✔
34
 *
64✔
35
 * @this {Object} Serializer
64✔
36
 * @param {Function} fn - Function
64✔
37
 * @param {number} fnId - Function ID
64✔
38
 * @param {Function} getFunctionInfo - Function info getter function
64✔
39
 * @param {boolean} isClass - `true` if is a class
64✔
40
 * @param {boolean} isAsync - `true` if is an async function
64✔
41
 * @param {boolean} isGenerator - `true` if is a generator function
64✔
42
 * @param {string} filename - File path
64✔
43
 * @returns {Object} - Function definition object with props:
64✔
44
 *   {Object} .node - AST node for function
64✔
45
 *   {Map} .scopeDefs - Scope definitions map, keyed by block ID
64✔
46
 *   {Object} .externalVars - Object keyed by var name, values are arrays of identifier nodes
64✔
47
 *   {Object} .internalVars - Object keyed by var name, values are arrays of identifier nodes
64✔
48
 *   {Set<string>} .globalVarNames - Set of names of global vars used
64✔
49
 *   {Set<string>} .reservedVarNames - Set of reserved var names
64✔
50
 *     (function names + vars which are frozen due to being accessed from within `with ()`)
64✔
51
 *   {string} .name - `.name` of created function
64✔
52
 *   {number} .numParams - `.length` of created function
64✔
53
 *   {boolean} .isClass - `true` if is class
64✔
54
 *   {boolean} .isAsync - `true` if is async function
64✔
55
 *   {boolean} .isGenerator - `true` if is generator
64✔
56
 *   {boolean} .isArrow - `true` if is arrow function
64✔
57
 *   {boolean} .isMethod - `true` if is a method
64✔
58
 *   {boolean|null} .isStrict - `true` if is strict mode, `false` if sloppy, `null` if indeterminate
64✔
59
 *     (classes and runtime functions are indeterminate)
64✔
60
 *   {boolean} .containsEval - `true` if contains direct `eval()`
64✔
61
 *   {Array<string>|undefined} .argNames - Array of `arguments` var names
64✔
62
 * @throws {Error} - If function contains `import`
64✔
63
 */
64✔
64
module.exports = function parseFunction(
64✔
65
        fn, fnId, getFunctionInfo, isClass, isAsync, isGenerator, filename
29,984✔
66
) {
29,984✔
67
        // Get function info and AST from info getter function
29,984✔
68
        const [fnInfoJson, getChildFnInfos, getSources] = getFunctionInfo();
29,984✔
69
        const fnInfo = JSON.parse(fnInfoJson);
29,984✔
70

29,984✔
71
        // Throw error if function contains `import()`
29,984✔
72
        if (fnInfo.containsImport) {
29,984!
73
                const fnName = Object.getOwnPropertyDescriptor(fn, 'name')?.value,
×
74
                        fnDesc = (isString(fnName) && fnName !== '') ? `function '${fnName}'` : 'anonymous function';
×
75
                throw new Error(`Cannot serialize function containing \`import\` (${fnDesc} in '${filename}')`);
×
76
        }
×
77

29,984✔
78
        // Assemble scope definitions
29,984✔
79
        const scopeDefs = new Map(),
29,984✔
80
                externalVars = Object.create(null);
29,984✔
81
        for (const {blockId, blockName, vars} of fnInfo.scopes) {
29,984✔
82
                scopeDefs.set(blockId, {
18,276✔
83
                        blockName,
18,276✔
84
                        vars: mapValues(vars, (varProps, varName) => {
18,276✔
85
                                externalVars[varName] = [];
24,324✔
86
                                return {
24,324✔
87
                                        isReadFrom: !!varProps.isReadFrom,
24,324✔
88
                                        isAssignedTo: !!varProps.isAssignedTo,
24,324✔
89
                                        isFrozenName: !!varProps.isFrozenName
24,324✔
90
                                };
24,324✔
91
                        })
18,276✔
92
                });
18,276✔
93
        }
18,276✔
94

29,984✔
95
        // Add child functions into AST, get external/internal var nodes, and get amendments to be made
29,984✔
96
        // (const violations / incidences of `super` to be transpiled)
29,984✔
97
        const internalVars = Object.create(null),
29,984✔
98
                reservedVarNames = new Set(),
29,984✔
99
                globalVarNames = new Set(),
29,984✔
100
                amendments = [];
29,984✔
101
        resolveFunctionInfo(
29,984✔
102
                fnInfo, getChildFnInfos, false, fnId, scopeDefs,
29,984✔
103
                externalVars, internalVars, globalVarNames, reservedVarNames, amendments
29,984✔
104
        );
29,984✔
105

29,984✔
106
        let node = fnInfo.ast;
29,984✔
107

29,984✔
108
        // If source maps enabled, add source files to `sourceFiles` map and set `loc.filename` for all nodes.
29,984✔
109
        // Create `copyLoc()` function to copy location info for AST nodes befing replaced.
29,984✔
110
        let copyLoc;
29,984✔
111
        if (this.options.sourceMaps) {
29,984✔
112
                const {filesHaveSourcesFor} = this;
29,900✔
113
                if (!filesHaveSourcesFor.has(filename)) {
29,900✔
114
                        Object.assign(this.sourceFiles, JSON.parse(getSources()));
18,982✔
115
                        filesHaveSourcesFor.add(filename);
18,982✔
116
                }
18,982✔
117

29,900✔
118
                traverseAll(node, ({loc}) => {
29,900✔
119
                        if (loc && !loc.filename) loc.filename = filename;
214,176✔
120
                });
29,900✔
121

29,900✔
122
                copyLoc = (destNode, srcNode) => {
29,900✔
123
                        destNode.start = srcNode.start;
8,864✔
124
                        destNode.end = srcNode.end;
8,864✔
125
                        destNode.loc = srcNode.loc;
8,864✔
126
                        return destNode;
8,864✔
127
                };
29,900✔
128
        } else {
29,984✔
129
                copyLoc = destNode => destNode;
84✔
130
        }
84✔
131

29,984✔
132
        // Get whether strict mode and remove use strict directive
29,984✔
133
        let isStrict;
29,984✔
134
        if (!isClass) {
29,984✔
135
                isStrict = !!fnInfo.isStrict;
25,952✔
136
                if (isStrict) {
25,952✔
137
                        removeUseStrictDirective(node);
20,586✔
138
                } else if (filename.startsWith(RUNTIME_DIR_PATH)) {
25,952✔
139
                        // Runtime functions are treated as indeterminate strict/sloppy mode unless explicitly strict
976✔
140
                        isStrict = null;
976✔
141
                }
976✔
142
        }
25,952✔
143

29,984✔
144
        // Create `super` var node if required
29,984✔
145
        let superVarNode;
29,984✔
146
        if (externalVars.super) {
29,984✔
147
                superVarNode = t.identifier('super');
2,848✔
148
                externalVars.super[0] = superVarNode;
2,848✔
149
                globalVarNames.add('Reflect');
2,848✔
150
                globalVarNames.add('Object');
2,848✔
151
        }
2,848✔
152

29,984✔
153
        // Conform function/class, get function name
29,984✔
154
        let isMethod, name, thisVarNode, constructorStatementNodes, firstSuperStatementIndex,
29,984✔
155
                paramNodes = node.params;
29,984✔
156
        const {type} = node,
29,984✔
157
                isArrow = type === 'ArrowFunctionExpression',
29,984✔
158
                containsEval = !!fnInfo.containsEval;
29,984✔
159
        if (isArrow) {
29,984✔
160
                // Arrow function
11,720✔
161
                name = '';
11,720✔
162
                isMethod = false;
11,720✔
163

11,720✔
164
                // If contains `super`, needs `this` too
11,720✔
165
                if (externalVars.super) {
11,720✔
166
                        thisVarNode = t.identifier('this');
384✔
167
                        externalVars.this.push(thisVarNode);
384✔
168
                }
384✔
169
        } else {
29,984✔
170
                // Class, method or function declaration/expression.
18,264✔
171
                // Get function name.
18,264✔
172
                name = (Object.getOwnPropertyDescriptor(fn, 'name') || {}).value;
18,264✔
173
                if (!isString(name)) name = '';
18,264✔
174

18,264✔
175
                // Identify if method and convert class method to object method
18,264✔
176
                if (type === 'ClassMethod') {
18,264✔
177
                        node.type = 'ObjectMethod';
2,256✔
178
                        node.static = undefined;
2,256✔
179
                        isMethod = true;
2,256✔
180
                } else if (type === 'ObjectMethod') {
18,264✔
181
                        isMethod = true;
2,032✔
182
                }
2,032✔
183

18,264✔
184
                if (isMethod) {
18,264✔
185
                        // Class/object method.
4,288✔
186
                        // Convert getter/setter to plain method, and disable computed keys.
4,288✔
187
                        node.kind = 'method';
4,288✔
188
                        node.computed = false;
4,288✔
189

4,288✔
190
                        // Wrap in object.
4,288✔
191
                        // NB: Must be defined as method, to avoid it having prototype.
4,288✔
192
                        let keyNode, accessComputed;
4,288✔
193
                        if (!name) {
4,288!
194
                                name = 'a';
×
195
                                keyNode = t.identifier('a');
×
196
                                accessComputed = false;
×
197
                        } else if (isJsIdentifier(name)) {
4,288✔
198
                                keyNode = t.identifier(name);
3,296✔
199
                                accessComputed = false;
3,296✔
200
                        } else {
4,288✔
201
                                keyNode = isNumberKey(name) ? t.numericLiteral(name * 1) : t.stringLiteral(name);
992✔
202
                                accessComputed = true;
992✔
203
                        }
992✔
204

4,288✔
205
                        node.key = copyLoc(keyNode, node.key || {});
4,288!
206
                        node = t.memberExpression(t.objectExpression([node]), keyNode, accessComputed);
4,288✔
207

4,288✔
208
                        // `this` within method is actual `this`
4,288✔
209
                        thisVarNode = t.thisExpression();
4,288✔
210
                } else {
18,264✔
211
                        // Set function name
13,976✔
212
                        const idNode = node.id;
13,976✔
213
                        if (containsEval) {
13,976✔
214
                                // Function contains `eval()`.
960✔
215
                                // Cannot change name from original as would create a new var in scope of `eval()`.
960✔
216
                                // If is a named function expression, name must be retained, to maintain const violation
960✔
217
                                // error behavior (error in strict mode, silent failure in sloppy mode).
960✔
218
                                // If is a named function declaration, name must be removed to allow read/write access
960✔
219
                                // to external var holding function in upper scope.
960✔
220
                                if (idNode) {
960✔
221
                                        name = idNode.name;
192✔
222
                                        if (externalVars[name]) name = '';
192✔
223
                                } else {
960✔
224
                                        name = '';
768✔
225
                                }
768✔
226
                        } else if (
13,976✔
227
                                name && (!isJsIdentifier(name) || isReservedVarName(name) || globalVarNames.has(name))
13,016✔
228
                        ) {
13,016✔
229
                                // Name cannot be used as is illegal, or would block access to a global var
212✔
230
                                name = '';
212✔
231
                        }
212✔
232

13,976✔
233
                        if (!name) {
13,976✔
234
                                node.id = null;
6,168✔
235
                        } else {
13,976✔
236
                                if (!idNode || idNode.name !== name) {
7,808✔
237
                                        node.id = t.identifier(name);
852✔
238
                                        if (idNode) copyLoc(node.id, idNode);
852✔
239
                                }
852✔
240
                                reservedVarNames.add(name);
7,808✔
241
                        }
7,808✔
242

13,976✔
243
                        if (isClass) {
13,976✔
244
                                // Class
4,032✔
245
                                if (type === 'ClassDeclaration') node.type = 'ClassExpression';
4,032✔
246

4,032✔
247
                                // Classes have indeterminate strict/sloppy status - never require conforming to strict/sloppy
4,032✔
248
                                // as they're automatically strict.
4,032✔
249
                                isStrict = null;
4,032✔
250

4,032✔
251
                                // Remove all members except constructor and prototype properties
4,032✔
252
                                let constructorNode;
4,032✔
253
                                const classBodyNode = node.body;
4,032✔
254
                                const memberNodes = classBodyNode.body = classBodyNode.body.filter((memberNode) => {
4,032✔
255
                                        if (!memberNode) return false;
3,792✔
256
                                        const memberType = memberNode.type;
1,504✔
257
                                        if (memberType === 'ClassMethod') {
1,504✔
258
                                                constructorNode = memberNode;
1,504✔
259
                                                return true;
1,504✔
260
                                        }
1,504✔
261
                                        if (memberType === 'StaticBlock') return false;
×
262
                                        return !memberNode.static;
×
263
                                });
4,032✔
264
                                paramNodes = constructorNode ? constructorNode.params : [];
4,032✔
265

4,032✔
266
                                if (fnInfo.hasSuperClass) {
4,032✔
267
                                        // Remove `extends`
1,440✔
268
                                        node.superClass = null;
1,440✔
269

1,440✔
270
                                        // Add constructor if none present
1,440✔
271
                                        if (!constructorNode) {
1,440✔
272
                                                // `constructor(...args) {
1,056✔
273
                                                //   return Reflect.construct(Object.getPrototypeOf(super$0), args, super$0);
1,056✔
274
                                                // }`
1,056✔
275
                                                const argsVarNode = t.identifier('args');
1,056✔
276
                                                internalVars.args = [argsVarNode];
1,056✔
277
                                                // TODO: Can using `.unshift()` interfere with replacing const violations further on?
1,056✔
278
                                                // Indexes of any class properties will be altered.
1,056✔
279
                                                memberNodes.unshift(t.classMethod(
1,056✔
280
                                                        'constructor',
1,056✔
281
                                                        t.identifier('constructor'),
1,056✔
282
                                                        [t.restElement(argsVarNode)],
1,056✔
283
                                                        t.blockStatement([
1,056✔
284
                                                                t.returnStatement(
1,056✔
285
                                                                        t.callExpression(
1,056✔
286
                                                                                t.memberExpression(t.identifier('Reflect'), t.identifier('construct')),
1,056✔
287
                                                                                [
1,056✔
288
                                                                                        t.callExpression(
1,056✔
289
                                                                                                t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
1,056✔
290
                                                                                                [superVarNode]
1,056✔
291
                                                                                        ),
1,056✔
292
                                                                                        argsVarNode,
1,056✔
293
                                                                                        superVarNode
1,056✔
294
                                                                                ]
1,056✔
295
                                                                        )
1,056✔
296
                                                                )
1,056✔
297
                                                        ])
1,056✔
298
                                                ));
1,056✔
299
                                        } else {
1,440✔
300
                                                // Class has constructor - prepare for transpiling `super()`
384✔
301
                                                const thisInternalVars = internalVars.this;
384✔
302
                                                if (thisInternalVars) {
384✔
303
                                                        // Constructor contains `this` or `super` expression (e.g. `super.foo()`).
288✔
304
                                                        // Var for `this$0` is going to be needed.
288✔
305
                                                        thisVarNode = t.identifier('this');
288✔
306
                                                        thisInternalVars.push(thisVarNode);
288✔
307
                                                }
288✔
308

384✔
309
                                                firstSuperStatementIndex = fnInfo.firstSuperStatementIndex;
384✔
310
                                                constructorStatementNodes = constructorNode.body.body;
384✔
311
                                        }
384✔
312
                                } else {
4,032✔
313
                                        // Class which doesn't extend a super class. `this` within constructor is actual `this`.
2,592✔
314
                                        thisVarNode = t.thisExpression();
2,592✔
315
                                }
2,592✔
316
                        } else {
13,976✔
317
                                // Function declaration/expression. `this` is actual `this`.
9,944✔
318
                                if (type === 'FunctionDeclaration') node.type = 'FunctionExpression';
9,944✔
319
                                thisVarNode = t.thisExpression();
9,944✔
320
                        }
9,944✔
321
                }
13,976✔
322
        }
18,264✔
323

29,984✔
324
        // Replace const violations + `super`.
29,984✔
325
        // Amendments are in reverse order:
29,984✔
326
        // - Nested functions before their parent.
29,984✔
327
        // - Within a function, deeper nested expressions/statements before their parent.
29,984✔
328
        // - Within a function, later statements before earlier statements.
29,984✔
329
        // Reverse order ensures correct handling of nested amendments
29,984✔
330
        // e.g. 2 const violations `c = c2 = 1` or const violation + super `super.foo(c = 1)`.
29,984✔
331
        const superIsProto = isClass || fnInfo.superIsProto || false;
29,984✔
332
        for (const amendment of amendments) {
29,984✔
333
                const {type: amendmentType, trail, trailNodes} = amendment;
2,624✔
334
                if (amendmentType === SUPER_CALL) {
2,624✔
335
                        replaceSuperCall(
448✔
336
                                trail, trailNodes, superVarNode, thisVarNode, firstSuperStatementIndex, copyLoc
448✔
337
                        );
448✔
338
                } else if (amendmentType === SUPER_EXPRESSION) {
2,624✔
339
                        replaceSuperExpression(
1,424✔
340
                                trail, trailNodes, superVarNode, thisVarNode, superIsProto, internalVars, copyLoc
1,424✔
341
                        );
1,424✔
342
                } else if (amendmentType === CONST_VIOLATION_FUNCTION_SILENT) {
2,176✔
343
                        replaceConstViolation(trail, trailNodes, true, internalVars, copyLoc);
16✔
344
                } else {
752✔
345
                        // amendmentType === CONST_VIOLATION_CONST || amendmentType === CONST_VIOLATION_FUNCTION_THROWING
736✔
346
                        replaceConstViolation(trail, trailNodes, false, internalVars, copyLoc);
736✔
347
                }
736✔
348
        }
2,624✔
349

29,984✔
350
        // If is class extending a super class, insert `let this$0;` and `return this$0;` statements
29,984✔
351
        // if required
29,984✔
352
        if (constructorStatementNodes && thisVarNode) {
29,984✔
353
                // Add `let this$0` at start of constructor
288✔
354
                if (firstSuperStatementIndex === undefined) {
288✔
355
                        constructorStatementNodes.unshift(
48✔
356
                                t.variableDeclaration('let', [t.variableDeclarator(thisVarNode, null)])
48✔
357
                        );
48✔
358
                }
48✔
359

288✔
360
                // Add `return this$0` to end of constructor
288✔
361
                if (!fnInfo.returnsSuper) constructorStatementNodes.push(t.returnStatement(thisVarNode));
288✔
362
        }
288✔
363

29,984✔
364
        // Determine what value of `fn.length` will be
29,984✔
365
        let numParams = 0;
29,984✔
366
        for (const {type: paramNodeType} of paramNodes) {
29,984✔
367
                if (paramNodeType === 'RestElement' || paramNodeType === 'AssignmentPattern') break;
5,646✔
368
                numParams++;
5,086✔
369
        }
5,086✔
370

29,984✔
371
        // Return function definition object
29,984✔
372
        return {
29,984✔
373
                node,
29,984✔
374
                scopeDefs,
29,984✔
375
                externalVars,
29,984✔
376
                internalVars,
29,984✔
377
                globalVarNames,
29,984✔
378
                reservedVarNames,
29,984✔
379
                name,
29,984✔
380
                numParams,
29,984✔
381
                isClass,
29,984✔
382
                isAsync,
29,984✔
383
                isGenerator,
29,984✔
384
                isArrow,
29,984✔
385
                isMethod,
29,984✔
386
                isStrict,
29,984✔
387
                containsEval,
29,984✔
388
                argNames: fnInfo.argNames
29,984✔
389
        };
29,984✔
390
};
64✔
391

64✔
392
/**
64✔
393
 * Remove 'use strict' directive from function.
64✔
394
 * @param {Object} fnNode - Function AST node
64✔
395
 * @returns {undefined}
64✔
396
 */
64✔
397
function removeUseStrictDirective(fnNode) {
20,586✔
398
        const bodyNode = fnNode.body;
20,586✔
399
        if (bodyNode.type !== 'BlockStatement') return;
20,586✔
400
        const directiveNodes = bodyNode.directives;
14,440✔
401
        if (directiveNodes.length === 0) return;
18,972✔
402
        const index = directiveNodes.findIndex(directiveNode => directiveNode.value.value === 'use strict');
962✔
403
        if (index === -1) return;
1,728✔
404

802✔
405
        // Relocate any comments attached to directive
802✔
406
        const directiveNode = directiveNodes[index];
802✔
407
        const commentNodes = [
802✔
408
                ...(directiveNode.leadingComments || []),
20,586✔
409
                ...(directiveNode.trailingComments || [])
20,586✔
410
        ];
20,586✔
411
        if (commentNodes.length !== 0) {
20,586✔
412
                const statementNodes = bodyNode.body;
16✔
413
                if (index !== 0) {
16!
414
                        directiveNodes[index - 1].trailingComments = combineArraysWithDedup(
×
415
                                directiveNodes[index - 1].trailingComments, commentNodes
×
416
                        );
×
417
                } else if (index !== directiveNodes.length - 1) {
16!
418
                        directiveNodes[index + 1].leadingComments = combineArraysWithDedup(
×
419
                                commentNodes, directiveNodes[index + 1].leadingComments
×
420
                        );
×
421
                } else if (statementNodes.length !== 0) {
16✔
422
                        statementNodes[0].leadingComments = combineArraysWithDedup(
16✔
423
                                commentNodes, statementNodes[0].leadingComments
16✔
424
                        );
16✔
425
                } else {
16!
426
                        bodyNode.innerComments = combineArraysWithDedup(bodyNode.innerComments, commentNodes);
×
427
                }
×
428
        }
16✔
429

802✔
430
        // Remove directive
802✔
431
        directiveNodes.splice(index, 1);
802✔
432
}
20,586✔
433

64✔
434
/**
64✔
435
 * Replace const violation expression with expression which throws.
64✔
436
 * e.g. `c = f()` -> `f(), (() => {const c = 0; c = 0;})()`
64✔
437
 * If is silent violation (function expression name assigned to in sloppy mode),
64✔
438
 * just remove the assignment.
64✔
439
 * e.g. `c += f()` -> `c + f()`
64✔
440
 *
64✔
441
 * @param {Array<string|number>} trail - Keys trail
64✔
442
 * @param {Array<Object>} trailNodes - Trail nodes
64✔
443
 * @param {boolean} isSilent - `true` if is a silent violation (i.e. doesn't throw)
64✔
444
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
445
 * @param {Function} copyLoc - Function to copy location from old to new AST node
64✔
446
 * @returns {undefined}
64✔
447
 */
64✔
448
function replaceConstViolation(trail, trailNodes, isSilent, internalVars, copyLoc) {
752✔
449
        const trailLen = trail.length,
752✔
450
                node = trailNodes[trailLen],
752✔
451
                parentNode = trailNodes[trailLen - 1];
752✔
452
        function replaceParent(replacementNode) {
752✔
453
                trailNodes[trailLen - 2][trail[trailLen - 2]] = copyLoc(replacementNode, parentNode);
576✔
454
        }
576✔
455

752✔
456
        const {type} = parentNode;
752✔
457
        if (type === 'AssignmentExpression') {
752✔
458
                const {operator} = parentNode;
480✔
459
                if (operator === '=') {
480✔
460
                        // `c = x` -> `x, throw()`
416✔
461
                        replaceParent(
416✔
462
                                createConstViolationThrowNode(parentNode.right, node.name, isSilent, internalVars)
416✔
463
                        );
416✔
464
                } else if (['&&=', '||=', '??='].includes(operator)) {
480✔
465
                        // `c &&= x` -> `c && (x, throw())`
32✔
466
                        replaceParent(
32✔
467
                                t.logicalExpression(
32✔
468
                                        operator.slice(0, -1),
32✔
469
                                        node,
32✔
470
                                        createConstViolationThrowNode(parentNode.right, node.name, isSilent, internalVars)
32✔
471
                                )
32✔
472
                        );
32✔
473
                } else {
32✔
474
                        // Other assignment operator e.g. `+=`, `-=`, `>>>=`
32✔
475
                        // `c += x` -> `c + x, throw()`
32✔
476
                        replaceParent(
32✔
477
                                createConstViolationThrowNode(
32✔
478
                                        t.binaryExpression(operator.slice(0, -1), node, parentNode.right),
32✔
479
                                        node.name, isSilent, internalVars
32✔
480
                                )
32✔
481
                        );
32✔
482
                }
32✔
483
        } else if (type === 'UpdateExpression') {
752✔
484
                // `c++` -> `(n => n++)(c), throw()`
32✔
485
                // `--c` -> `(n => --n)(c), throw()`
32✔
486
                // See https://github.com/overlookmotel/livepack/issues/528#issuecomment-1773242897
32✔
487
                const varNode = createTempVarNode(node.name, internalVars),
32✔
488
                        replacementNode = t.callExpression(
32✔
489
                                t.arrowFunctionExpression(
32✔
490
                                        [varNode], t.updateExpression(parentNode.operator, varNode, parentNode.prefix)
32✔
491
                                ),
32✔
492
                                [node]
32✔
493
                        );
32✔
494
                replaceParent(createConstViolationThrowNode(replacementNode, node.name, isSilent, internalVars));
32✔
495
        } else if (type === 'AssignmentPattern') {
272✔
496
                // `[c = x] = []`
64✔
497
                // -> `[(e => ({set a(v) {v === void 0 && e(); const c = 0; c = 0;}}))(() => x).a] = []`
64✔
498
                // `{c = x} = {}`
64✔
499
                // -> `{c: (e => ({set a(v) {v === void 0 && e(); const c = 0; c = 0;}}))(() => x).a} = {}`
64✔
500
                replaceParent(
64✔
501
                        createConstViolationThrowPatternNode(node.name, parentNode.right, isSilent, internalVars)
64✔
502
                );
64✔
503
        } else if (
240✔
504
                type === 'ForOfStatement' || type === 'ForInStatement'
176✔
505
                || type === 'ObjectProperty' || type === 'RestElement'
176✔
506
                || trailNodes[trailLen - 2].type === 'ArrayPattern'
176✔
507
        ) {
176✔
508
                // `for (c of [1]) { foo(); }`
176✔
509
                // -> `for ({ set a(v) { const c = 0; c = 0; } }.a of [1]) { foo(); }`
176✔
510
                // `{x: c} = {}` -> `{x: {set a(v) { const c = 0; c = 0; }}.a} = {}`
176✔
511
                // `[...c] = []` -> `[...{set a(v) { const c = 0; c = 0; }}.a] = []`
176✔
512
                // `{...c} = {}` -> `{...{set a(v) { const c = 0; c = 0; }}.a} = {}`
176✔
513
                // `[c] = [1]` -> `[{set a(v) { const c = 0; c = 0; }}.a] = [1]`
176✔
514
                parentNode[trail[trailLen - 1]] = copyLoc(
176✔
515
                        createConstViolationThrowAssignNode(node.name, isSilent, internalVars), node
176✔
516
                );
176✔
517
        } else {
176!
518
                assertBug(false, `Unexpected const violation node type ${type}`);
×
519
        }
×
520
}
752✔
521

64✔
522
/**
64✔
523
 * Create expression node which throws 'Assignment to constant variable' TypeError.
64✔
524
 * @param {Object} node - AST node to wrap
64✔
525
 * @param {string} name - Var name
64✔
526
 * @param {boolean} isSilent - `true` if violation does not throw
64✔
527
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
528
 * @returns {Object} - AST Node object
64✔
529
 */
64✔
530
function createConstViolationThrowNode(node, name, isSilent, internalVars) {
512✔
531
        // If silent failure, return node unchanged
512✔
532
        if (isSilent) return node;
512✔
533

496✔
534
        // `(x, (() => { const c = 0; c = 0; })())`
496✔
535
        return t.sequenceExpression([
496✔
536
                node,
496✔
537
                t.callExpression(
496✔
538
                        t.arrowFunctionExpression([], createConstViolationThrowBlockNode(name, internalVars)), []
496✔
539
                )
496✔
540
        ]);
496✔
541
}
512✔
542

64✔
543
/**
64✔
544
 * Create expression node which throws when assigned to.
64✔
545
 * @param {string} name - Var name
64✔
546
 * @param {boolean} isSilent - `true` if violation does not throw
64✔
547
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
548
 * @returns {Object} - AST Node object
64✔
549
 */
64✔
550
function createConstViolationThrowAssignNode(name, isSilent, internalVars) {
176✔
551
        // If silent failure, return expression which assignment to is a no-op
176✔
552
        if (isSilent) {
176!
553
                // `{}.a`
×
554
                return t.memberExpression(t.objectExpression([]), t.identifier('a'));
×
555
        }
×
556

176✔
557
        // `{ set a(v) { const c = 0; c = 0; } }.a`
176✔
558
        return t.memberExpression(
176✔
559
                t.objectExpression([
176✔
560
                        t.objectMethod(
176✔
561
                                'set',
176✔
562
                                t.identifier('a'),
176✔
563
                                [createTempVarNode(name === 'v' ? '_v' : 'v', internalVars)],
176!
564
                                createConstViolationThrowBlockNode(name, internalVars)
176✔
565
                        )
176✔
566
                ]),
176✔
567
                t.identifier('a')
176✔
568
        );
176✔
569
}
176✔
570

64✔
571
/**
64✔
572
 * Create expression node to replace an assignment pattern which:
64✔
573
 * 1. Evaluates right hand side of pattern expression only if incoming assignment value is `undefined`
64✔
574
 * 2. Throws when assigned to
64✔
575
 *
64✔
576
 * @param {string} name - Var name
64✔
577
 * @param {Object} rightNode - AST Node for right-hand side of assignment pattern
64✔
578
 * @param {boolean} isSilent - `true` if violation does not throw
64✔
579
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
580
 * @returns {Object} - AST Node object
64✔
581
 */
64✔
582
function createConstViolationThrowPatternNode(name, rightNode, isSilent, internalVars) {
64✔
583
        const valueVarNode = createTempVarNode(name === 'v' ? '_v' : 'v', internalVars),
64!
584
                rightGetterVarNode = createTempVarNode(name === 'e' ? '_e' : 'e', internalVars);
64!
585

64✔
586
        // `v === void 0 && e()`
64✔
587
        const statementNodes = [t.expressionStatement(t.logicalExpression(
64✔
588
                '&&',
64✔
589
                t.binaryExpression('===', valueVarNode, t.unaryExpression('void', t.numericLiteral(0))),
64✔
590
                t.callExpression(rightGetterVarNode, [])
64✔
591
        ))];
64✔
592

64✔
593
        if (!isSilent) statementNodes.push(...createConstViolationThrowStatementNodes(name, internalVars));
64✔
594

64✔
595
        // `(e => ({ set a(v) { v === void 0 && e(); const c = 0; c = 0; }}))(() => x).a`
64✔
596
        return t.memberExpression(
64✔
597
                t.callExpression(
64✔
598
                        t.arrowFunctionExpression(
64✔
599
                                [rightGetterVarNode],
64✔
600
                                t.objectExpression([
64✔
601
                                        t.objectMethod('set', t.identifier('a'), [valueVarNode], t.blockStatement(statementNodes))
64✔
602
                                ])
64✔
603
                        ),
64✔
604
                        [t.arrowFunctionExpression([], rightNode)]
64✔
605
                ),
64✔
606
                t.identifier('a')
64✔
607
        );
64✔
608
}
64✔
609

64✔
610
/**
64✔
611
 * Create block statement which throws 'Assignment to constant variable' TypeError.
64✔
612
 * @param {string} name - Var name
64✔
613
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
614
 * @returns {Object} - AST Node object
64✔
615
 */
64✔
616
function createConstViolationThrowBlockNode(name, internalVars) {
672✔
617
        // `{ const c = 0; c = 0; }`
672✔
618
        return t.blockStatement(createConstViolationThrowStatementNodes(name, internalVars));
672✔
619
}
672✔
620

64✔
621
/**
64✔
622
 * Create statements which throw 'Assignment to constant variable' TypeError.
64✔
623
 * @param {string} name - Var name
64✔
624
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
625
 * @returns {Array<Object>} - Array of AST Node objects
64✔
626
 */
64✔
627
function createConstViolationThrowStatementNodes(name, internalVars) {
736✔
628
        // `const c = 0; c = 0;`
736✔
629
        const varNode = createTempVarNode(name, internalVars);
736✔
630
        return [
736✔
631
                t.variableDeclaration('const', [t.variableDeclarator(varNode, t.numericLiteral(0))]),
736✔
632
                t.expressionStatement(t.assignmentExpression('=', varNode, t.numericLiteral(0)))
736✔
633
        ];
736✔
634
}
736✔
635

64✔
636
/**
64✔
637
 * Replace `super()` call with transpiled version.
64✔
638
 * @param {Array<string|number>} trail - Keys trail
64✔
639
 * @param {Array<Object>} trailNodes - Trail nodes
64✔
640
 * @param {Object} superVarNode - Var node for home object for `super`
64✔
641
 * @param {Object} [thisVarNode] - Var node for `this` (Identifier)
64✔
642
 * @param {number} [firstSuperStatementIndex] - Index of first top-level `super()` statement
64✔
643
 * @param {Function} copyLoc - Function to copy location from old to new AST node
64✔
644
 * @returns {undefined}
64✔
645
 */
64✔
646
function replaceSuperCall(
448✔
647
        trail, trailNodes, superVarNode, thisVarNode, firstSuperStatementIndex, copyLoc
448✔
648
) {
448✔
649
        const trailLen = trail.length,
448✔
650
                callNode = trailNodes[trailLen - 1];
448✔
651

448✔
652
        // Convert to `super(x, y)` -> `Reflect.construct(Object.getPrototypeOf(super$0), [x, y], super$0)`.
448✔
653
        // NB: Cannot optimize `super(...x)` to `Reflect.construct(Object.getPrototypeOf(super$0), x, super$0)`
448✔
654
        // in case `x` is an iterator not an array.
448✔
655
        const argumentsNodes = callNode.arguments;
448✔
656
        callNode.callee = copyLoc(
448✔
657
                t.memberExpression(t.identifier('Reflect'), t.identifier('construct')),
448✔
658
                callNode.callee
448✔
659
        );
448✔
660
        callNode.arguments = [
448✔
661
                t.callExpression(
448✔
662
                        t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
448✔
663
                        [superVarNode]
448✔
664
                ),
448✔
665
                t.arrayExpression(argumentsNodes),
448✔
666
                superVarNode
448✔
667
        ];
448✔
668

448✔
669
        // If is `return super()`, just substitute transpiled super
448✔
670
        // `return super(x)` -> `return Reflect.construct(Object.getPrototypeOf(super$0), [x], super$0)`
448✔
671
        const grandParentNode = trailNodes[trailLen - 2],
448✔
672
                grandParentType = grandParentNode.type;
448✔
673
        if (grandParentType === 'ReturnStatement') {
448✔
674
                if (thisVarNode) {
16!
675
                        grandParentNode[trail[trailLen - 2]] = copyLoc(
×
676
                                t.assignmentExpression('=', thisVarNode, callNode),
×
677
                                callNode
×
678
                        );
×
679
                }
×
680
                return;
16✔
681
        }
16✔
682

432✔
683
        // If is a top-level statement in constructor
432✔
684
        // (i.e. is statement which is purely `super()`, directly in constructor body block):
432✔
685
        // - Last statement: `return Reflect.construct(...)`
432✔
686
        //   or if `this` used in constructor: `return this$0 = Reflect.construct(...)`
432✔
687
        // - First statement: `const this$0 = Reflect.construct(...)`
432✔
688
        // - Any other statement: `this$0 = Reflect.construct(...)`
432✔
689
        if (grandParentType === 'ExpressionStatement') {
432✔
690
                const fnType = trailNodes[0].type;
416✔
691
                if ((fnType === 'ClassDeclaration' || fnType === 'ClassExpression') && trail.length === 8) {
416✔
692
                        // Top-level statement in constructor
368✔
693
                        const statementNodes = trailNodes[5],
368✔
694
                                statementIndex = trail[5];
368✔
695
                        if (statementIndex === statementNodes.length - 1) {
368✔
696
                                // Last statement in constructor
96✔
697
                                // `return Reflect.construct(...);` or `return this$0 = Reflect.construct(...);`
96✔
698
                                statementNodes[statementIndex] = copyLoc(
96✔
699
                                        t.returnStatement(thisVarNode ? t.assignmentExpression('=', thisVarNode, callNode) : callNode),
96✔
700
                                        callNode
96✔
701
                                );
96✔
702
                                return;
96✔
703
                        }
96✔
704

272✔
705
                        if (statementIndex === firstSuperStatementIndex) {
352✔
706
                                // First `super()` statement - replace with `const this$0 = Reflect.construct(...);`
240✔
707
                                statementNodes[statementIndex] = copyLoc(
240✔
708
                                        t.variableDeclaration('const', [t.variableDeclarator(thisVarNode, callNode)]),
240✔
709
                                        grandParentNode
240✔
710
                                );
240✔
711
                                return;
240✔
712
                        }
240✔
713
                }
368✔
714
        }
416✔
715

96✔
716
        // Replace with `this$0 = Reflect.construct(...)`
96✔
717
        grandParentNode[trail[trailLen - 2]] = copyLoc(
96✔
718
                t.assignmentExpression('=', thisVarNode, callNode), callNode
96✔
719
        );
96✔
720
}
448✔
721

64✔
722
/**
64✔
723
 * Replace `super` expression with transpiled version.
64✔
724
 * `super.prop` / `super[prop]` / `super.prop(...)` / `super[prop](...)` /
64✔
725
 * `super.prop = ...` / `super[prop] = ...`
64✔
726
 *
64✔
727
 * @param {Array<string|number>} trail - Keys trail
64✔
728
 * @param {Array<Object>} trailNodes - Trail nodes
64✔
729
 * @param {Object} superVarNode - Var node for home object for `super`
64✔
730
 * @param {Object} [thisVarNode] - Var node for `this` (may be Identifier or ThisExpression)
64✔
731
 * @param {boolean} superIsProto - `true` if `super` is within context of class prototype method
64✔
732
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
733
 * @param {Function} copyLoc - Function to copy location from old to new AST node
64✔
734
 * @returns {undefined}
64✔
735
 */
64✔
736
function replaceSuperExpression(
1,424✔
737
        trail, trailNodes, superVarNode, thisVarNode, superIsProto, internalVars, copyLoc
1,424✔
738
) {
1,424✔
739
        const trailLen = trail.length,
1,424✔
740
                expressionNode = trailNodes[trailLen - 1];
1,424✔
741

1,424✔
742
        // `super.prop` -> `Reflect.get(Object.getPrototypeOf(super$0.prototype), 'prop', this$0)`
1,424✔
743
        // or in static class method `Reflect.get(Object.getPrototypeOf(super$0), 'prop', this$0)`
1,424✔
744
        let propNode = expressionNode.property;
1,424✔
745
        if (!expressionNode.computed) propNode = copyLoc(t.stringLiteral(propNode.name), propNode);
1,424✔
746

1,424✔
747
        let replacementNode = t.callExpression(
1,424✔
748
                t.memberExpression(t.identifier('Reflect'), t.identifier('get')),
1,424✔
749
                [
1,424✔
750
                        t.callExpression(
1,424✔
751
                                t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
1,424✔
752
                                [
1,424✔
753
                                        superIsProto
1,424✔
754
                                                ? t.memberExpression(superVarNode, t.identifier('prototype'))
1,424✔
755
                                                : superVarNode
1,424✔
756
                                ]
1,424✔
757
                        ),
1,424✔
758
                        propNode,
1,424✔
759
                        thisVarNode
1,424✔
760
                ]
1,424✔
761
        );
1,424✔
762

1,424✔
763
        // `super.prop = ...` -> `Reflect.set(Object.getPrototypeOf(super$0.prototype), 'prop', value, this$0)`
1,424✔
764
        const parentNode = trailNodes[trailLen - 2],
1,424✔
765
                parentKey = trail[trailLen - 2],
1,424✔
766
                parentType = parentNode.type;
1,424✔
767
        if (parentType === 'AssignmentExpression' && parentKey === 'left') {
1,424✔
768
                // Convert `Reflect.get(...)` to `Reflect.set(...)`
224✔
769
                replacementNode.callee.property.name = 'set';
224✔
770

224✔
771
                const valueNode = parentNode.right,
224✔
772
                        grandParentNode = trailNodes[trailLen - 3];
224✔
773
                if (grandParentNode.type === 'ExpressionStatement') {
224✔
774
                        // Standalone expression - add value to `Reflect.set()` arguments
208✔
775
                        replacementNode.arguments.splice(2, 0, valueNode);
208✔
776
                } else {
208✔
777
                        // Not standalone expression - wrap in function which return values.
16✔
778
                        // This avoids evaluating the value expression twice.
16✔
779
                        // `x = super.foo = y();` =>
16✔
780
                        // `x = ((key, value) => (Reflect.set(..., key, value, this$0), value))('foo', y());`
16✔
781
                        // NB: Key is passed to function as argument too as it could be a complex expression
16✔
782
                        // referencing many vars. Evaluating it outside the temp closure ensures no var name clashes.
16✔
783
                        const keyVarNode = createTempVarNode('key', internalVars),
16✔
784
                                valueVarNode = createTempVarNode('value', internalVars);
16✔
785
                        replacementNode.arguments[1] = keyVarNode;
16✔
786
                        replacementNode.arguments.splice(2, 0, valueVarNode);
16✔
787
                        replacementNode = t.callExpression(
16✔
788
                                t.arrowFunctionExpression(
16✔
789
                                        [keyVarNode, valueVarNode],
16✔
790
                                        t.sequenceExpression([replacementNode, valueVarNode])
16✔
791
                                ),
16✔
792
                                [propNode, valueNode]
16✔
793
                        );
16✔
794
                }
16✔
795

224✔
796
                grandParentNode[trail[trailLen - 3]] = copyLoc(replacementNode, parentNode);
224✔
797
                return;
224✔
798
        }
224✔
799

1,200✔
800
        // `super.prop(x, y)` -> `Reflect.get(...).call(this$0, x, y)`
1,200✔
801
        if (parentType === 'CallExpression') {
1,424✔
802
                replacementNode = t.memberExpression(replacementNode, t.identifier('call'));
912✔
803
                parentNode.arguments.unshift(thisVarNode);
912✔
804
        }
912✔
805
        copyLoc(replacementNode, expressionNode);
1,200✔
806

1,200✔
807
        parentNode[parentKey] = replacementNode;
1,200✔
808
}
1,424✔
809

64✔
810
/**
64✔
811
 * Create temp var node and add to internal vars.
64✔
812
 * @param {string} name - Var name
64✔
813
 * @param {Object} internalVars - Map of internal vars, keyed by var name
64✔
814
 * @returns {Object} - Identifier AST node
64✔
815
 */
64✔
816
function createTempVarNode(name, internalVars) {
1,104✔
817
        const node = t.identifier(name);
1,104✔
818
        createArrayOrPush(internalVars, name, node);
1,104✔
819
        return node;
1,104✔
820
}
1,104✔
821

64✔
822
/**
64✔
823
 * Add ASTs of nested functions to AST.
64✔
824
 * A function which has other functions nested within it will have left those nodes defined as `null`
64✔
825
 * in JSON-serialized AST. Get those child functions' ASTs from their own `getFnInfo()` functions
64✔
826
 * and insert them into the parent AST.
64✔
827
 * @param {Object} fnInfo - Function info object which was encoded as JSON to fn info getter function
64✔
828
 * @param {Array<Function>} getInfos - Function info getter functions for child functions
64✔
829
 * @param {boolean} isNestedFunction - `true` if is nested function
64✔
830
 * @param {number} fnId - Block ID of function being serialized
64✔
831
 * @param {Map} scopeDefs - Scope definitions map, keyed by block ID
64✔
832
 * @param {Object} externalVars - Map of var name to array of var nodes
64✔
833
 * @param {Object} internalVars - Map of var name to array of var nodes
64✔
834
 * @param {Set<string>} globalVarNames - Set of global var names
64✔
835
 * @param {Set<string>} reservedVarNames - Set of internal var names which are used
64✔
836
 * @param {Array<Object>} amendments - Array of amendments (const violations or `super`)
64✔
837
 * @returns {undefined}
64✔
838
 */
64✔
839
function resolveFunctionInfo(
35,316✔
840
        fnInfo, getInfos, isNestedFunction, fnId, scopeDefs,
35,316✔
841
        externalVars, internalVars, globalVarNames, reservedVarNames, amendments
35,316✔
842
) {
35,316✔
843
        // Init internal vars.
35,316✔
844
        // Converting trails to nodes needs to be done after child functions added into AST
35,316✔
845
        // because some vars recorded as internal to this function may be within the ASTs of child functions.
35,316✔
846
        // These are class `extends` clauses and computed method keys.
35,316✔
847
        // Initializing properties of `internalVars` needs to happen before processing child functions,
35,316✔
848
        // as external vars in child functions can become internal vars in this function.
35,316✔
849
        const internalVarTrails = [];
35,316✔
850
        for (const [varName, trails] of Object.entries(fnInfo.internalVars)) {
35,316✔
851
                if (!internalVars[varName]) internalVars[varName] = [];
10,626✔
852
                internalVarTrails.push({varName, trails});
10,626✔
853
        }
10,626✔
854

35,316✔
855
        // Process child functions
35,316✔
856
        const fnNode = fnInfo.ast;
35,316✔
857
        fnInfo.childFns.forEach((trail, index) => {
35,316✔
858
                const [childJson, childGetInfos] = getInfos[index](),
5,332✔
859
                        childInfo = JSON.parse(childJson);
5,332✔
860
                resolveFunctionInfo(
5,332✔
861
                        childInfo, childGetInfos, true, fnId, scopeDefs,
5,332✔
862
                        externalVars, internalVars, globalVarNames, reservedVarNames, amendments
5,332✔
863
                );
5,332✔
864

5,332✔
865
                // Insert child function's AST into this function's AST
5,332✔
866
                setProp(fnNode, trail, childInfo.ast);
5,332✔
867
        });
35,316✔
868

35,316✔
869
        // Record function name
35,316✔
870
        if (isNestedFunction) {
35,316✔
871
                const idNode = fnNode.id;
5,332✔
872
                if (idNode) reservedVarNames.add(idNode.name);
5,332✔
873
        }
5,332✔
874

35,316✔
875
        // Get external var nodes
35,316✔
876
        for (const scope of fnInfo.scopes) {
35,316✔
877
                const {blockId} = scope;
22,982✔
878
                if (blockId < fnId) {
22,982✔
879
                        // External var
19,940✔
880
                        for (
19,940✔
881
                                const [varName, {isReadFrom, isAssignedTo, isFrozenName, trails}]
19,940✔
882
                                of Object.entries(scope.vars)
19,940✔
883
                        ) {
19,940✔
884
                                if (isNestedFunction) {
27,748✔
885
                                        const scopeDefVar = scopeDefs.get(blockId).vars[varName];
3,424✔
886
                                        if (isReadFrom) scopeDefVar.isReadFrom = true;
3,424✔
887
                                        if (isAssignedTo) scopeDefVar.isAssignedTo = true;
3,424✔
888
                                        // TODO: I think next line isn't required, as it'll already be set on the parent anyway
3,424✔
889
                                        if (isFrozenName) scopeDefVar.isFrozenName = true;
3,424!
890
                                }
3,424✔
891

27,748✔
892
                                externalVars[varName].push(...trailsToNodes(fnNode, trails, varName));
27,748✔
893
                        }
27,748✔
894
                } else {
22,982✔
895
                        // Var which is external to current function, but internal to function being serialized
3,042✔
896
                        for (const [varName, {isFrozenInternalName, trails}] of Object.entries(scope.vars)) {
3,042✔
897
                                if (!isFrozenInternalName) {
3,364✔
898
                                        internalVars[varName]?.push(...trailsToNodes(fnNode, trails, varName));
3,252✔
899
                                }
3,252✔
900
                        }
3,364✔
901
                }
3,042✔
902
        }
22,982✔
903

35,316✔
904
        // Get internal var nodes
35,316✔
905
        for (const {varName, trails} of internalVarTrails) {
35,316✔
906
                internalVars[varName].push(...trailsToNodes(fnNode, trails, varName));
10,626✔
907
        }
10,626✔
908

35,316✔
909
        // Get reserved internal var names + global var names
35,316✔
910
        if (fnInfo.reservedVarNames) setAddFrom(reservedVarNames, fnInfo.reservedVarNames);
35,316!
911
        if (fnInfo.globalVarNames) setAddFrom(globalVarNames, fnInfo.globalVarNames);
35,316✔
912

35,316✔
913
        // Get amendments (const violations and `super`).
35,316✔
914
        // Ignore amendments which refer to internal vars.
35,316✔
915
        const thisAmendments = fnInfo.amendments;
35,316✔
916
        if (thisAmendments) {
35,316✔
917
                for (const [type, blockId, ...trail] of thisAmendments) {
2,592✔
918
                        if (blockId < fnId) {
2,800✔
919
                                amendments.push({type, trail, trailNodes: getProps(fnNode, trail)});
2,624✔
920
                        } else if (type === CONST_VIOLATION_CONST) {
2,800✔
921
                                // Const violation where var is internal to function. Add to internal vars instead.
32✔
922
                                // Ignore CONST_VIOLATION_FUNCTION_THROWING and CONST_VIOLATION_FUNCTION_SILENT violation types
32✔
923
                                // because they refer to function names, which are not treated as internal vars.
32✔
924
                                const node = getProp(fnNode, trail);
32✔
925
                                internalVars[node.name].push(node);
32✔
926
                        }
32✔
927
                }
2,800✔
928
        }
2,592✔
929
}
35,316✔
930

64✔
931
/**
64✔
932
 * Get nodes for trails.
64✔
933
 * Convert `ThisExpression`s to `Identifier`s.
64✔
934
 * @param {Object} fnNode - AST node for function
64✔
935
 * @param {Array<Array>} trails - Trails
64✔
936
 * @param {string} varName - Var name
64✔
937
 * @returns {Array<Object>} - AST nodes specified by trails
64✔
938
 */
64✔
939
function trailsToNodes(fnNode, trails, varName) {
40,058✔
940
        return varName === 'this'
40,058✔
941
                ? trails.map((trail) => {
40,058✔
942
                        const node = getProp(fnNode, trail);
512✔
943
                        node.type = 'Identifier';
512✔
944
                        node.name = 'this';
512✔
945
                        return node;
512✔
946
                })
1,344✔
947
                : trails.map(trail => getProp(fnNode, trail));
40,058✔
948
}
40,058✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc