Skip to content

Commit 7f19662

Browse files
janvennemannsgtcoolguy
authored andcommitted
feat(node): node 12 compatible util module and improved console
1 parent adb9603 commit 7f19662

File tree

9 files changed

+3700
-426
lines changed

9 files changed

+3700
-426
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import{formatWithOptions}from'../node/internal/util/inspect';
2+
3+
constnativeDebug=console.debug;
4+
constnativeError=console.error;
5+
constnativeInfo=console.info;
6+
constnativeLog=console.log;
7+
constnativeWarn=console.warn;
8+
9+
constkNoColorInspectOptions={};
10+
11+
console.debug=function(...args){
12+
nativeDebug.call(console,formatWithOptions(kNoColorInspectOptions, ...args));
13+
};
14+
15+
console.error=function(...args){
16+
nativeError.call(console,formatWithOptions(kNoColorInspectOptions, ...args));
17+
};
18+
19+
console.info=function(...args){
20+
nativeInfo.call(console,formatWithOptions(kNoColorInspectOptions, ...args));
21+
};
22+
23+
console.log=function(...args){
24+
nativeLog.call(console,formatWithOptions(kNoColorInspectOptions, ...args));
25+
};
26+
27+
console.warn=function(...args){
28+
nativeWarn.call(console,formatWithOptions(kNoColorInspectOptions, ...args));
29+
};
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
// Load all JavaScript extensions/polyfills
2+
import'./console';
23
import'./Error';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import{codes}from'./errors';
2+
3+
leterror;
4+
functionlazyError(){
5+
if(!error){
6+
// @fixme rollup cannot handle lazy loaded modules, maybe move to webpack?
7+
// error = require('./errors').codes.ERR_INTERNAL_ASSERTION;
8+
error=codes.ERR_INTERNAL_ASSERTION;
9+
}
10+
returnerror;
11+
}
12+
functionassert(value,message){
13+
if(!value){
14+
constERR_INTERNAL_ASSERTION=lazyError();
15+
thrownewERR_INTERNAL_ASSERTION(message);
16+
}
17+
}
18+
19+
functionfail(message){
20+
constERR_INTERNAL_ASSERTION=lazyError();
21+
thrownewERR_INTERNAL_ASSERTION(message);
22+
}
23+
24+
assert.fail=fail;
25+
26+
exportdefaultassert;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/**
2+
* Node's internal/errors module modified for Axway Titanium
3+
*
4+
* Only a few selected errors are exported manually here. Most of the functionality
5+
* is still missing and may be added as we move forward with Node compatibility.
6+
*
7+
* @see https://github.com/nodejs/node/blob/master/lib/internal/errors.js
8+
*/
9+
10+
importassertfrom'./assert';
11+
import{format}from'./util/inspect';
12+
13+
constmessages=newMap();
14+
exportconstcodes={};
15+
16+
// @todo implement this once needed
17+
classSystemErrorextendsError{
18+
19+
}
20+
21+
// Utility function for registering the error codes.
22+
functionE(sym,val,def, ...otherClasses){
23+
// Special case for SystemError that formats the error message differently
24+
// The SystemErrors only have SystemError as their base classes.
25+
messages.set(sym,val);
26+
27+
if(def===SystemError){
28+
thrownewError('Node compatible SystemError not yet implemented.');
29+
}else{
30+
def=makeNodeErrorWithCode(def,sym);
31+
}
32+
33+
if(otherClasses.length!==0){
34+
otherClasses.forEach((clazz)=>{
35+
def[clazz.name]=makeNodeErrorWithCode(clazz,sym);
36+
});
37+
}
38+
codes[sym]=def;
39+
}
40+
41+
functionmakeNodeErrorWithCode(Base,key){
42+
returnclassNodeErrorextendsBase{
43+
constructor(...args){
44+
super();
45+
constmessage=getMessage(key,args,this);
46+
Object.defineProperty(this,'message',{
47+
value: message,
48+
enumerable: false,
49+
writable: true,
50+
configurable: true
51+
});
52+
addCodeToName(this,super.name,key);
53+
}
54+
55+
getcode(){
56+
returnkey;
57+
}
58+
59+
setcode(value){
60+
Object.defineProperty(this,'code',{
61+
configurable: true,
62+
enumerable: true,
63+
value,
64+
writable: true
65+
});
66+
}
67+
68+
toString(){
69+
return`${this.name} [${key}]: ${this.message}`;
70+
}
71+
};
72+
}
73+
74+
functiongetMessage(key,args,self){
75+
constmsg=messages.get(key);
76+
77+
/*
78+
// @fixme rollup cannot handle lazy loaded modules, maybe move to webpack?
79+
if (assert === undefined) {
80+
assert = require('./internal/assert');
81+
}
82+
*/
83+
84+
if(typeofmsg==='function'){
85+
assert(
86+
msg.length<=args.length,// Default options do not count.
87+
`Code: ${key}; The provided arguments length (${args.length}) does not `+
88+
`match the required ones (${msg.length}).`
89+
);
90+
returnmsg.apply(self,args);
91+
}
92+
93+
constexpectedLength=(msg.match(/%[dfijoOs]/g)||[]).length;
94+
assert(
95+
expectedLength===args.length,
96+
`Code: ${key}; The provided arguments length (${args.length}) does not `+
97+
`match the required ones (${expectedLength}).`
98+
);
99+
if(args.length===0){
100+
returnmsg;
101+
}
102+
103+
args.unshift(msg);
104+
returnformat.apply(null,args);
105+
// @fixme rollup cannot handle lazy loaded modules, maybe move to webpack?
106+
// return lazyInternalUtilInspect().format.apply(null, args);
107+
}
108+
109+
functionaddCodeToName(err,name,code){
110+
// Add the error code to the name to include it in the stack trace.
111+
err.name=`${name} [${code}]`;
112+
// Access the stack to generate the error message including the error code
113+
// from the name.
114+
// @fixme: This only works on V8/Android, iOS/JSC has a different Error structure.
115+
// should we try to make errors behave the same across platforms?
116+
err.stack;
117+
// Reset the name to the actual name.
118+
if(name==='SystemError'){
119+
Object.defineProperty(err,'name',{
120+
value: name,
121+
enumerable: false,
122+
writable: true,
123+
configurable: true
124+
});
125+
}else{
126+
deleteerr.name;
127+
}
128+
}
129+
130+
E('ERR_INTERNAL_ASSERTION',(message)=>{
131+
constsuffix='This is caused by either a bug in Titanium '+
132+
'or incorrect usage of Titanium internals.\n'+
133+
'Please open an issue with this stack trace at '+
134+
'https://jira.appcelerator.org\n';
135+
returnmessage===undefined ? suffix : `${message}\n${suffix}`;
136+
},Error);
137+
E('ERR_INVALID_ARG_TYPE',(name,expected,actual)=>{
138+
assert(typeofname==='string','\'name\' must be a string');
139+
140+
// determiner: 'must be' or 'must not be'
141+
letdeterminer;
142+
if(typeofexpected==='string'&&expected.startsWith('not ')){
143+
determiner='must not be';
144+
expected=expected.replace(/^not/,'');
145+
}else{
146+
determiner='must be';
147+
}
148+
149+
letmsg;
150+
if(name.endsWith(' argument')){
151+
// For cases like 'first argument'
152+
msg=`The ${name}${determiner}${oneOf(expected,'type')}`;
153+
}else{
154+
consttype=name.includes('.') ? 'property' : 'argument';
155+
msg=`The "${name}" ${type}${determiner}${oneOf(expected,'type')}`;
156+
}
157+
158+
// TODO(BridgeAR): Improve the output by showing `null` and similar.
159+
msg+=`. Received type ${typeofactual}`;
160+
returnmsg;
161+
},TypeError);
162+
163+
letmaxStack_ErrorName;
164+
letmaxStack_ErrorMessage;
165+
/**
166+
* Returns true if `err.name` and `err.message` are equal to engine-specific
167+
* values indicating max call stack size has been exceeded.
168+
* "Maximum call stack size exceeded" in V8.
169+
*
170+
* @param {Error} err
171+
* @returns {boolean}
172+
*/
173+
exportfunctionisStackOverflowError(err){
174+
if(maxStack_ErrorMessage===undefined){
175+
try{
176+
functionoverflowStack(){
177+
overflowStack();
178+
}
179+
overflowStack();
180+
}catch(e){
181+
maxStack_ErrorMessage=e.message;
182+
maxStack_ErrorName=e.name;
183+
}
184+
}
185+
186+
returnerr.name===maxStack_ErrorName&&err.message===maxStack_ErrorMessage;
187+
}
188+
189+
functiononeOf(expected,thing){
190+
assert(typeofthing==='string','`thing` has to be of type string');
191+
if(Array.isArray(expected)){
192+
constlen=expected.length;
193+
assert(len>0,'At least one expected value needs to be specified');
194+
expected=expected.map((i)=>String(i));
195+
if(len>2){
196+
return`one of ${thing}${expected.slice(0,len-1).join(', ')}, or `+expected[len-1];
197+
}elseif(len===2){
198+
return`one of ${thing}${expected[0]} or ${expected[1]}`;
199+
}else{
200+
return`of ${thing}${expected[0]}`;
201+
}
202+
}else{
203+
return`of ${thing}${String(expected)}`;
204+
}
205+
}

common/Resources/ti.internal/extensions/node/internal/util.js

+37
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
1+
import{isNativeError}from'./util/types';
2+
13
constkNodeModulesRE=/^(.*)[\\/]node_modules[\\/]/;
24

5+
exportconstcustomInspectSymbol=Symbol.for('nodejs.util.inspect.custom');
6+
7+
constcolorRegExp=/\u001b\[\d\d?m/g;// eslint-disable-line no-control-regex
8+
9+
exportfunctionremoveColors(str){
10+
returnstr.replace(colorRegExp,'');
11+
}
12+
13+
exportfunctionisError(e){
14+
// An error could be an instance of Error while not being a native error
15+
// or could be from a different realm and not be instance of Error but still
16+
// be a native error.
17+
returnisNativeError(e)||einstanceofError;
18+
}
19+
320
letgetStructuredStack;
421
classStackTraceErrorextendsError{}
522
StackTraceError.prepareStackTrace=(err,trace)=>trace;
@@ -42,3 +59,23 @@ export function isInsideNodeModules() {
4259

4360
returnfalse;
4461
}
62+
63+
exportfunctionjoin(output,separator){
64+
letstr='';
65+
if(output.length!==0){
66+
constlastIndex=output.length-1;
67+
for(leti=0;i<lastIndex;i++){
68+
// It is faster not to use a template string here
69+
str+=output[i];
70+
str+=separator;
71+
}
72+
str+=output[lastIndex];
73+
}
74+
returnstr;
75+
}
76+
77+
exportfunctionuncurryThis(f){
78+
returnfunction(){
79+
returnf.call.apply(f,arguments);
80+
};
81+
}

0 commit comments

Comments
 (0)
close