-
Notifications
You must be signed in to change notification settings - Fork 3
/
process.js
791 lines (726 loc) · 29.5 KB
/
process.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
/*
* Copyright 2013 Amadeus s.a.s.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = function (UglifyJS) {
var throwError = function (msg, code) {
var e = new Error(msg + " (" + code + ")");
e.code = code;
throw e;
};
var reportError = function (errorMsg, item) {
throw new Error([errorMsg, " in ", item.start.file, ' (line ', item.start.line, ')\n ', item.print_to_string()].join(''));
};
var acceptedAriaMethods = {
// Don't transform resource definitions for now (as the new syntax is not supported for them):
// 'resourcesDefinition' : 1,
'classDefinition' : 1,
'interfaceDefinition' : 1,
'beanDefinitions' : 1,
'tplScriptDefinition' : 1
};
var checkAriaDefinition = function (node) {
// check that the walker is positioned in the argument of
// an Aria.classDefinition, Aria.interfaceDefinition, Aria.tplScriptDefinition or Aria.beanDefinitions
if (node instanceof UglifyJS.AST_Call) {
var expr = node.expression;
if (expr instanceof UglifyJS.AST_Dot) {
var aria = expr.expression;
if (aria instanceof UglifyJS.AST_SymbolRef && aria.name === "Aria"
&& acceptedAriaMethods.hasOwnProperty(expr.property)) {
return expr.property;
}
}
}
// To check what is happening:
// reportError('Not taking the property into account.', walker.self())
return false;
};
var isUndeclaredSymbolRef = function (node, walker) {
if (!(node instanceof UglifyJS.AST_SymbolRef && node.thedef.undeclared)) {
return false;
}
if (node.name == "arguments" && walker.find_parent(UglifyJS.AST_Lambda)) {
return false;
}
return true;
};
var Transformation = function (ast, sourceText, options) {
this.ast = ast;
if (sourceText) {
// makes sure sourceText is exactly the same as the text Uglify uses
// when tokenizing, so that changes using positions in the string,
// as performed by insertNodeInString, are accurate
sourceText = UglifyJS.tokenizer(sourceText).context().text;
this.sourceText = sourceText;
}
this.options = options || {};
};
Transformation.prototype.findAriaDefAndGlobals = function () {
var ast = this.ast;
ast.figure_out_scope();
var ariaDefinition = null;
var ariaDefinitionType = null;
var globals = {};
walker = new UglifyJS.TreeWalker(function (node) {
var ariaDefType = checkAriaDefinition(node);
if (ariaDefType) {
if (ariaDefinition) {
reportError("Found multiple Aria definitions", node);
} else {
ariaDefinition = {
node : node,
parent : walker.parent()
};
ariaDefinitionType = ariaDefType;
}
} else if (isUndeclaredSymbolRef(node, walker)) {
var stack = walker.stack;
var i = stack.length - 1;
do {
var curNode = stack[i];
var propertyName = curNode.print_to_string();
if (!globals.hasOwnProperty(propertyName)) {
globals[propertyName] = [];
}
globals[propertyName].push({
node : curNode,
parent : stack[i - 1]
});
i--;
} while (i >= 0 && stack[i] instanceof UglifyJS.AST_Dot);
}
});
ast.walk(walker);
if (globals["module"] || globals["require"]) {
throwError("This file already uses 'module' or 'require'. It cannot be converted automatically. Perhaps it was already converted.", "alreadyConverted");
}
if (!ariaDefinition) {
throwError("Could not find any Aria definition in this file.", "noAria");
}
this.ariaDefinition = ariaDefinition;
this.ariaDefinitionType = ariaDefinitionType;
this.globals = globals;
};
Transformation.prototype.findBootstrapDependencies = function () {
var bootstrap = require("./at-bootstrap");
var globals = this.globals;
bootstrap.forEach(function (bootstrapGlobalName) {
if (globals.hasOwnProperty(bootstrapGlobalName) && bootstrapGlobalName != this.classpath) {
this.addDependency(bootstrapGlobalName, "JS");
}
}, this);
};
Transformation.prototype.findDependencies = function () {
this.dependencies = {};
var ariaDefParameter = this.ariaDefinition.node.args[0];
if (!(ariaDefParameter instanceof UglifyJS.AST_Object)) {
return reportError("Expected an object literal for the Aria definition", ariaDefParameter);
}
this.addDependency("Aria", "JS", "ariatemplates/Aria", "Aria"); // a very special dependency
ariaDefParameter.properties.forEach(function (property) {
var fnName = "findDependenciesIn" + property.key;
var fnRef = this[fnName];
if (fnRef) {
fnRef.call(this, property, ariaDefParameter);
}
}, this);
if (this.parentClasspath) {
this.parentType = this.parentType || "JS";
if (!extensions.hasOwnProperty(this.parentType)) {
return reportError("Incorrect value in $extendsType", value);
}
this.addDependencyFromNodeWithReplacement(this.parentType, this.parentClasspath.parent, this.parentClasspath.node);
}
this.findBootstrapDependencies();
};
var getBaseLogicalPath = function (classpath) {
var array = classpath.split(".");
if (array[0] === "aria") {
array[0] = "ariatemplates";
}
return array.join("/");
};
var extensions = {
JS : "",
TPL : ".tpl",
CSS : ".tpl.css",
TML : ".tml",
CML : ".cml",
TXT : ".tpl.txt"
};
var createRequireNode = function (path) {
return new UglifyJS.AST_Call({
expression : new UglifyJS.AST_SymbolRef({
name : "require"
}),
args : [new UglifyJS.AST_String({
value : path
})]
});
};
var createRequireResourceNode = function (curDep, requesterBaseLogicalPath, forceAbsolutePaths) {
var serverResource = /([^\/]*)\/Res$/.exec(curDep.baseLogicalPath);
var path = computeRelativePath(requesterBaseLogicalPath, "ariatemplates/$resources", forceAbsolutePaths);
var requireNode = createRequireNode(path);
var args = [new UglifyJS.AST_String({
value : curDep.baseRelativePath
})];
if (/^(.|..)\//.test(curDep.baseRelativePath)) {
// relative path, include __dirname:
args.unshift(new UglifyJS.AST_SymbolRef({
name : "__dirname"
}));
}
if (serverResource) {
args.unshift(new UglifyJS.AST_String({
value : serverResource[1]
}));
}
return new UglifyJS.AST_Call({
expression : new UglifyJS.AST_Dot({
expression : requireNode,
property : serverResource ? "module" : "file"
}),
args : args
});
};
var createRequireResourceProviderNode = function (curDep, requesterBaseLogicalPath, requesterClasspath, forceAbsolutePaths) {
var path = computeRelativePath(requesterBaseLogicalPath, "ariatemplates/$resourcesProviders", forceAbsolutePaths);
var requireNode = createRequireNode(path);
var args = [new UglifyJS.AST_String({
value : curDep.baseRelativePath
})];
if (/^(.|..)\//.test(curDep.baseRelativePath)) {
// relative path, include __dirname:
args.unshift(new UglifyJS.AST_SymbolRef({
name : "__dirname"
}));
} else {
args.unshift(new UglifyJS.AST_String({
value : ""
}));
}
args.push(new UglifyJS.AST_String({
value : requesterClasspath
}));
var params = curDep.params;
args.push(new UglifyJS.AST_String({
value : params.onLoad
}));
args.push(new UglifyJS.AST_String({
value : params.handler
}));
params.resources.forEach(function (curRes){
args.push(new UglifyJS.AST_String({
value : curRes
}));
});
return new UglifyJS.AST_Call({
expression : new UglifyJS.AST_Dot({
expression : requireNode,
property : "fetch"
}),
args : args
});
};
Transformation.prototype.addDependency = function (globalName, type, baseLogicalPath, varName) {
var res = this.dependencies[globalName];
if (!res) {
var baseLogicalPath = baseLogicalPath || getBaseLogicalPath(globalName);
this.dependencies[globalName] = res = {
varName : varName,
globalName : globalName,
type : type,
baseLogicalPath : baseLogicalPath,
usages : []
};
var classpathGlobalUsages = this.globals[globalName];
if (classpathGlobalUsages) {
res.usages.push.apply(res.usages, classpathGlobalUsages);
}
}
return res;
};
Transformation.prototype.addDependencyFromNode = function (type, parent, node) {
if (!(node instanceof UglifyJS.AST_String)) {
return reportError("Expected a string literal", node);
}
return this.addDependency(node.value, type);
};
Transformation.prototype.addDependencyFromNodeWithReplacement = function (type, parent, node) {
var dependency = this.addDependencyFromNode(type, parent, node);
dependency.usages.push({
parent : parent,
node : node
});
};
var findDepsInArray = function (type, doReplacements) {
return function (node, parent) {
var value = node.value;
if (!(value instanceof UglifyJS.AST_Array)) {
return reportError("Expected an array literal in " + node.key, node.value);
}
var fnToCall = doReplacements ? this.addDependencyFromNodeWithReplacement : this.addDependencyFromNode;
value.elements.forEach(fnToCall.bind(this, type, value));
if (!doReplacements) {
// we remove the node later because we are in a forEach loop on the array which we need to change
this.removeNodeLater({
node : node,
parent : parent
});
}
};
};
var findDepsInMap = function (type) {
return function (node) {
var value = node.value;
if (!(value instanceof UglifyJS.AST_Object)) {
return reportError("Expected an object literal in " + node.key, node.value);
}
value.properties.forEach(function (property) {
this.addDependencyFromNodeWithReplacement(type, property, property.value);
}, this);
};
};
Transformation.prototype.findDependenciesIn$classpath = function (property) {
if (this.ariaDefinitionType === "beanDefinitions") {
return;
}
var value = property.value
if (!(value instanceof UglifyJS.AST_String)) {
return reportError("Expected an string literal in $classpath", value);
}
this.classpath = value.value;
this.baseLogicalPath = getBaseLogicalPath(this.classpath);
};
Transformation.prototype.findDependenciesIn$package = function (property) {
if (this.ariaDefinitionType !== "beanDefinitions") {
return;
}
var value = property.value
if (!(value instanceof UglifyJS.AST_String)) {
return reportError("Expected an string literal in $package", value);
}
this.classpath = value.value;
this.baseLogicalPath = getBaseLogicalPath(this.classpath);
};
Transformation.prototype.findDependenciesIn$extends = function (property) {
this.parentClasspath = {
parent : property,
node : property.value
};
};
Transformation.prototype.findDependenciesIn$extendsType = function (property, parent) {
var value = property.value
if (!(value instanceof UglifyJS.AST_String)) {
return reportError("Expected a string in $extendsType", value);
}
this.parentType = value.value;
this.removeNodeLater({
node : property,
parent : parent
});
};
Transformation.prototype.findDependenciesIn$implements = findDepsInArray("JS", true);
Transformation.prototype.findDependenciesIn$dependencies = findDepsInArray("JS", false);
Transformation.prototype.findDependenciesIn$resources = function (node) {
if (this.ariaDefinitionType === "resourcesDefinition") {
// in a file with Aria.resourcesDefinition, $resources does not contain dependencies like in other file
// types
return;
}
var value = node.value;
if (!(value instanceof UglifyJS.AST_Object)) {
return reportError("Expected an object literal in $resources", node.value);
}
value.properties.forEach(function (property) {
//console.log("props", property.value.properties[2].value);
var astObject;
if (property.value instanceof UglifyJS.AST_String) {
this.addDependencyFromNodeWithReplacement("RES", property, property.value);
} else if (property.value instanceof UglifyJS.AST_Object && (astObject = getMapFromASTObject(property.value)).provider) {
this.addResourceProviderDependency(astObject, property);
} else {
return reportError("Expected either a string literal or an object literal containing a \"provider\" property in $resources", property);
}
}, this);
};
var providersCounters = 0;
Transformation.prototype.addResourceProviderDependency = function (providerCfg, property) {
var provider = providerCfg.provider;
if (!(provider instanceof UglifyJS.AST_String)) {
return reportError("Expected a string literal as resources provider", provider);
}
var providerValue = provider.value;
var providerBaseLogicalPath = getBaseLogicalPath(providerValue);
var globalName = providerValue + providersCounters;
providersCounters++;
var onLoad = providerCfg.onLoad;
var onLoadValue = "";
if (onLoad) {
if (onLoad instanceof UglifyJS.AST_String) {
onLoadValue = onLoad.value;
} else {
return reportError("Expected a string literal as resources provider's onLoad", onLoad);
}
}
var handler = providerCfg.handler;
var handlerValue = "";
if (handler) {
if (handler instanceof UglifyJS.AST_String) {
handlerValue = handler.value;
} else {
return reportError("Expected a string literal as resources provider's handler", handler);
}
}
var resources = providerCfg.resources;
var resourcesValue = [];
if (resources) {
if (resources instanceof UglifyJS.AST_Array) {
var elements = resources.elements;
for (var i = 0, len = elements.length; i < len; i++) {
if (elements[i] instanceof UglifyJS.AST_String) {
resourcesValue.push(elements[i].value);
} else {
return reportError("Expected a string literal as resources provider's resource", elements[i]);
}
}
} else {
return reportError("Expected array as resources provider's resources", resources);
}
}
this.dependencies[globalName] = {
globalName : globalName,
type : "RES_PROVIDER",
baseLogicalPath : providerBaseLogicalPath,
usages : [{
parent : property,
node : property.value
}],
params : {
onLoad : onLoadValue,
handler : handlerValue,
resources : resourcesValue
}
};
};
var getMapFromASTObject = function (astObject) {
var map = {};
astObject.properties.forEach(function (property) {
map[property.key] = property.value;
});
return map;
};
Transformation.prototype.findDependenciesIn$templates = findDepsInArray("TPL", false);
Transformation.prototype.findDependenciesIn$css = findDepsInArray("CSS", true);
Transformation.prototype.findDependenciesIn$macrolibs = findDepsInArray("TML", false);
Transformation.prototype.findDependenciesIn$csslibs = findDepsInArray("CML", false);
Transformation.prototype.findDependenciesIn$texts = findDepsInMap("TXT");
Transformation.prototype.findDependenciesIn$namespaces = findDepsInMap("JS");
Transformation.prototype.createVarName = function (dependency) {
return dependency.globalName.replace(/[^a-zA-Z0-9]+/g, "_").split("_").map(function (part, index) {
if (index == 0) {
return part.charAt(0).toLowerCase() + part.substring(1);
} else {
return part.charAt(0).toUpperCase() + part.substring(1);
}
}).join("");
};
var createModuleDotExports = function () {
return new UglifyJS.AST_Dot({
expression : new UglifyJS.AST_SymbolRef({
name : "module"
}),
property : "exports"
});
};
var computeRelativePath = function (refPath, logicalPath, forceAbsolute) {
if (forceAbsolute) {
return logicalPath;
}
var refParts = refPath.split("/");
var targetParts = logicalPath.split("/");
var maxCommon = Math.min(refParts.length, targetParts.length) - 1;
var commonItems = 0;
while (commonItems < maxCommon && refParts[commonItems] == targetParts[commonItems]) {
commonItems++;
}
if (commonItems == 0) {
return logicalPath;
}
targetParts.splice(0, commonItems);
var parentsCount = refParts.length - 1 - commonItems;
if (parentsCount == 0) {
targetParts.unshift(".");
} else {
for (var i = 0; i < parentsCount; i++) {
targetParts.unshift("..");
}
}
return targetParts.join("/");
};
Transformation.prototype.insertRequires = function () {
this.replaceNodeLater(this.ariaDefinition, new UglifyJS.AST_Assign({
left : createModuleDotExports(),
operator : "=",
right : this.ariaDefinition.node
}), this.insertModuleExportsInString);
var simplifySingleUsage = this.options.simplifySingleUsage;
var dependencies = this.dependencies;
var forceAbsolutePaths = this.options.forceAbsolutePaths;
for (var depName in dependencies) {
var curDep = dependencies[depName];
var requireNode;
curDep.baseRelativePath = computeRelativePath(this.baseLogicalPath, curDep.baseLogicalPath, forceAbsolutePaths);
if (curDep.type == "RES") {
requireNode = createRequireResourceNode(curDep, this.baseLogicalPath, forceAbsolutePaths);
} else if (curDep.type == "RES_PROVIDER") {
requireNode = createRequireResourceProviderNode(curDep, this.baseLogicalPath, this.classpath, forceAbsolutePaths);
} else {
requireNode = createRequireNode(curDep.baseRelativePath + extensions[curDep.type]);
}
var nbUsages = curDep.usages.length;
if (simplifySingleUsage && nbUsages === 1 && !curDep.varName) {
this.replaceNodeLater(curDep.usages[0], requireNode);
} else if (curDep.varName || nbUsages > 0) {
var varName = curDep.varName || this.createVarName(curDep);
this.insertNodeLater(new UglifyJS.AST_Var({
definitions : [new UglifyJS.AST_VarDef({
name : new UglifyJS.AST_SymbolVar({
name : varName
}),
value : requireNode
})]
}));
curDep.usages.forEach(function (usageNode) {
this.replaceNodeLater(usageNode, new UglifyJS.AST_SymbolRef({
name : varName
}));
}, this);
} else {
this.insertNodeLater(new UglifyJS.AST_SimpleStatement({
body : requireNode
}));
}
}
if (this.globals.hasOwnProperty(this.classpath) && this.options.replaceOwnClasspath) {
this.globals[this.classpath].forEach(function (usageNode) {
this.replaceNodeLater(usageNode, createModuleDotExports());
}, this);
}
this.doLaterOperations();
};
var replaceNodeInArray = function (array, oldNode, newNode) {
for (var i = 0, l = array.length; i < l; i++) {
if (array[i] === oldNode) {
if (newNode) {
array[i] = newNode;
} else {
array.splice(i, 1);
}
return {
array : array,
index : i
};
}
}
return false;
};
var replaceNodeInProperties = function (parent, oldNode, newNode) {
var properties = parent.CTOR.PROPS;
for (var i = 0, l = properties.length; i < l; i++) {
var curProperty = properties[i];
var curValue = parent[curProperty];
if (curValue === oldNode) {
if (newNode) {
parent[curProperty] = newNode;
} else {
delete parent[curProperty];
}
return {
property : curProperty
};
} else if (Array.isArray(curValue)) {
var res = replaceNodeInArray(curValue, oldNode, newNode)
if (res) {
return res;
}
}
}
return false;
};
var methodsOrder = {
"insertNode" : -1,
"replaceNode" : 1
};
var sortOperations = function (op1, op2) {
if (op1.position != op2.position) {
return op1.position - op2.position;
} else if (op1.method != op2.method) {
// for the same position, insertNode is before replaceNode
return methodsOrder[op1.method] - methodsOrder[op2.method];
} else {
return op1.order - op2.order;
}
};
Transformation.prototype.doLaterOperations = function () {
if (!this.laterOperations) {
return;
}
this.laterOperations.sort(sortOperations);
while (this.laterOperations.length > 0) {
var operation = this.laterOperations.pop();
this[operation.method].apply(this, operation.arguments);
}
};
Transformation.prototype.insertNodeLater = function () {
if (!this.laterOperations) {
this.laterOperations = [];
}
this.laterOperations.push({
order : this.laterOperations.length,
position : this.findInsertPosition(),
method : "insertNode",
arguments : arguments
});
};
Transformation.prototype.replaceNodeLater = function (nodeAndParent, newNode) {
if (!this.laterOperations) {
this.laterOperations = [];
}
this.laterOperations.push({
order : this.laterOperations.length,
position : nodeAndParent.node.start.pos,
method : "replaceNode",
arguments : arguments
});
};
Transformation.prototype.removeNodeLater = function (nodeAndParent) {
this.replaceNodeLater(nodeAndParent);
};
Transformation.prototype.replaceNodeInString = function (nodeAndParent, newNode, changeInfo) {
var node = nodeAndParent.node;
var sourceText = this.sourceText;
var newNodeText = "";
var start = node.start.pos;
var end = node.end.endpos;
if (newNode) {
newNodeText = newNode.print_to_string({
beautify : true
});
if (!(newNode instanceof UglifyJS.AST_Statement || newNode instanceof UglifyJS.AST_SymbolRef)) {
newNodeText = "(" + newNodeText + ")";
}
} else {
// removing a node is a bit more complex, as there can be an extra comma
var array = changeInfo.array;
if (array) {
var index = changeInfo.index;
if (index > 0) {
// also remove the preceding comma if any
start = array[index - 1].end.endpos;
} else if (array.length > 0) {
// also remove the next comma if any
end = array[index].start.pos;
}
}
}
this.sourceText = sourceText.substr(0, start) + newNodeText + sourceText.substr(end);
};
Transformation.prototype.insertModuleExportsInString = function (nodeAndParent, newNode) {
var node = nodeAndParent.node;
var pos = node.start.pos;
var sourceText = this.sourceText;
this.sourceText = sourceText.substr(0, pos) + "module.exports = " + sourceText.substr(pos);
};
Transformation.prototype.replaceNode = function (nodeAndParent, newNode, stringOperation) {
var parent = nodeAndParent.parent;
var node = nodeAndParent.node
if (newNode && !newNode.start) {
// this is needed because of a bug in uglify-js if start is not defined on some specific nodes
newNode.start = {
comments_before : []
};
}
var res = replaceNodeInProperties(parent, node, newNode);
if (res) {
if (this.sourceText) {
stringOperation = stringOperation || this.replaceNodeInString;
stringOperation.call(this, nodeAndParent, newNode, res);
}
return;
}
reportError("Internal error: unable to find the node to replace", node);
};
Transformation.prototype.removeNode = function (nodeAndParent) {
this.replaceNode(nodeAndParent, null);
};
var isGlobalComment = function (comment) {
return /copyright|license|jshint/i.test(comment);
};
var filterStart = function (start) {
if (!start) {
return;
}
var firstComments = [];
var laterComments = start.comments_before;
while (laterComments.length > 0 && isGlobalComment(laterComments[0].value)) {
firstComments.push(laterComments.shift())
}
return {
nlb : true,
comments_before : firstComments
};
};
Transformation.prototype.findInsertPosition = function () {
if (this._insertPosition == null) {
var start = this.ast.start = filterStart(this.ast.start);
if (start && start.comments_before.length > 0) {
var lastComment = start.comments_before[start.comments_before.length - 1];
this._insertPosition = lastComment.endpos;
} else {
this._insertPosition = 0;
}
}
return this._insertPosition;
};
Transformation.prototype.insertNodeInString = function (node) {
var sourceText = this.sourceText;
var newNodeText = node.print_to_string({
beautify : true
});
var pos = this.findInsertPosition();
if (this._alreadyInsertedNode) {
pos += 1;
newNodeText += "\n";
} else {
newNodeText = "\n" + newNodeText + "\n";
this._alreadyInsertedNode = true;
}
this.sourceText = sourceText.substr(0, pos) + newNodeText + sourceText.substr(pos);
};
Transformation.prototype.insertNode = function (node) {
if (this.sourceText) {
this.insertNodeInString(node);
}
this.ast.body.splice(0, 0, node);
};
return function (ast, sourceText, options) {
var scope = new Transformation(ast, sourceText, options);
scope.findAriaDefAndGlobals();
scope.findDependencies();
scope.insertRequires();
return scope.sourceText;
};
};