How to detect brave using navigator - user-agent

I am trying to detect brave using navigator. I referred to this post, https://stackoverflow.com/a/60954062/14443512
I tried this condition,
(navigator.brave && await navigator.brave.isBrave() || false)
But I get error, Property 'brave' does not exist on type 'Navigator'.
Am I missing any configuration here?
My code block,
export const errorMessage = (networkError: netError): string | undefined => {
const {statusCode, message} = networkError;
if (statusCode === undefined) {
return message;
}
if (statusCode < 400) {
return undefined;
}
switch (statusCode) {
case 401:
return 'authn error';
case 403:
if(navigator.brave && await navigator.brave.isBrave() || false)
return 'browser not supported';
else
return 'authz error';
case 500:
if (message.includes("invalid value")) {
return invalidString;
}
break;
}
if (statusCode < 500) {
return 'error';
}
return 'serverError';
};

I think that the declaration should be something like this:
export {}; // there must be at least one export in this file
declare global {
interface Navigator {
brave: {
isBrave(): boolean;
};
}
interface Global {
document: Document;
window: Window;
navigator: Navigator,
}
}

Related

issue when cypress executes code asynchronously

i have this method that returns an object. if i run the code below i find that the second console.log() hits first and the object returns undefined
private routeAndPassengerDataObject: undefined | RouteAndPassenger;
public getDataFromRouteAndPassengerObject(fileName?: string): RouteAndPassenger {
if (this.routeAndPassengerDataObject) {
return this.routeAndPassengerDataObject;
}
if (typeof fileName !== 'string') {
throw new Error(`${fileName} has to be a string`);
}
cy.fixture(fileName).then((data: unknown) => {
if (!isValidRouteAndPassengerObject(data)) {
throw new Error(`${data} is not valid`);
}
console.log(`this is first`);
this.routeAndPassengerDataObject = data;
});
console.log(`this is second`);
return this.routeAndPassengerDataObject!;
}
}
const routeAndPassengerData = getDataFromRouteAndPassengerObject()
console.log(routeAndPassengerData);
result-
this is second
this is first
undefined
would like to know how to handle this please.
returing the object as cypress.chainable like below has worked for me-
public getDataFromRouteAndPassengerObject(fileName?: string): Cypress.Chainable<RouteAndPassenger> {
if (this.routeAndPassengerDataObject) {
return cy.wrap(this.routeAndPassengerDataObject);
}
if (typeof fileName !== 'string') {
throw new Error(`${fileName} has to be a string`);
}
return cy.fixture(fileName).then((data: unknown) => {
if (!isValidRouteAndPassengerObject(data)) {
throw new Error(`${data} is not valid`);
}
console.log(`this is first`);
this.routeAndPassengerDataObject = data;
return cy.wrap(this._routeAndPassengerDataObject);
});
}
and then calling the object like so-
const routeAndPassengerData = getDataFromRouteAndPassengerObject().then((routeAndPassenger)=>{
console.log(routeAndPassenger)
})

Is there a method to remove circular references in Ace

I'm wrapping AceEditor page in web view and returning the event results to the container and it is hanging on objects that contain circular references.
Is there a method in ace to remove circular references in the objects dispatched in the events of Ace Editor?
I didn't find one so I wrote one myself. It seems to work so far:
"use strict";
// returns an object that removes circular references
document.removeReferences = function (object, maxDepth, depth, objects, clone, debug) {
if (objects==null) { objects = []; }
if (clone==true) { clone = {}; }
maxDepth = maxDepth==null ? 10 : maxDepth;
depth = depth==null ? 0 : depth;
var padding = "";
var value;
if (debug) { for (var i=0;i<depth;i++) { padding += " "; } };
if (debug && typeof object != 'function') {
console.log(padding + "\nDepth:" + depth + " max depth:" + maxDepth);
}
if (typeof object == 'object') {
if (object!=null && objects.indexOf(object)==-1) {
if (debug) console.log(padding+"caching object:"+object);
objects.push(object);
}
else {
if (debug) console.log(padding+"object found. skipping");
return clone;
}
for (var key in object) {
value = object[key];
if (debug && typeof value!="function") {
console.log(padding+""+key + ":" + typeof value);
}
if (object.hasOwnProperty(key) && (typeof value == 'object')) {
// remove circular references
if (objects.indexOf(value)!=-1) {
if (debug) console.log(padding+"recursive object found. deleting:"+key);
if (clone==null) {
delete object[key];
}
else {
delete clone[key];
}
continue;
}
if (depth>=maxDepth) {
//object[key] = null;
if (clone==null) {
if (debug) console.log(padding+"max object limit - deleting:"+key);
delete object[key];
}
else {
if (typeof value=="array") {
clone[key] = null;
}
else {
clone[key] = null;
}
delete clone[key];
if (debug) console.log(padding+"max object limit - not adding:"+key);
}
}
else {
if (clone==null) {
if (value!=null) {
if (debug) console.log(padding+"diving into:"+key);
document.removeReferences(value, maxDepth, depth+1, objects, null, debug);
}
}
else {
if (typeof value=="array") {
clone[key] = value.slice();
}
else {
clone[key] = value!=null ? {} : null;
}
if (value!=null) {
if (debug) console.log(padding+"diving into:"+key);
document.removeReferences(value, maxDepth, depth+1, objects, clone[key], debug);
}
}
}
}
else if (typeof value == 'function') {
//object[key] = null;
if (clone==null) {
delete object[key];
}
else {
}
}
else {
if (clone!=null) {
if (debug) console.log(padding+" cloning key :"+key);
if (typeof value=="array") {
clone[key] = value.slice();
}
else {
clone[key] = value!=null ? value : null;
}
}
}
}
}
if (clone!=null) {
if (debug) console.log(padding+"return clone");
return clone;
}
if (debug) console.log(padding+"return object");
return object;
}
You then use something like this:
// inside an ace editor event:
var debug = true;
var clonedEvent = document.removeReferences(event, 0, null, null, true, debug);

Not all code paths return a value in Typescript Promise

I have a method that returns a Typescript promise. I am tightening up my code by enabling TSLint and it says that "Not all code paths return a value" for this method.
Please critique my code - I cannot work out what path it is referring to:
public getExtendedProfile(): Promise<any> {
//only do this if they are authenticated
if (this.authenticated()) {
if (typeof this.userProfile.user_id !== 'undefined') {
if (typeof this.user == 'undefined') {
this.profileService.getExtendedUserProfile(this.userProfile.user_id)
.then(data => {
return Promise.resolve(data);
})
.catch((error: any) => {
return Promise.reject(error)
});
}
else {
return Promise.resolve(this.user);
}
}
else {
return Promise.reject("No user stored");
}
}
else {
return Promise.reject("Not Authenticated");
}
}
// una alternativa podria ser
:Promise<any>
// cambiar a
:Promise<any|void>
docs typescript funciones: https://www.typescriptlang.org/docs/handbook/functions.html

How can I override jasmine's buildExpectationResult in order to modify message() function?

I am using protractor for my e2e tests and jasmine2 as framework. I am using a plugin for html reporter with screenshots ( html-report for protractor ).
In these reports there will be shown a list of all failed/passed expects. When the expect fails I get a descriptive message of the expectation. However when the expect passes I only see the word: Passed. The reason behind that is that jasmine overrides the message when the expect passes.
That is done in the following file:
node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
getJasmineRequireObj().buildExpectationResult = function () {
function buildExpectationResult(options) {
var messageFormatter = options.messageFormatter || function () {
},
stackFormatter = options.stackFormatter || function () {
};
var result = {
matcherName: options.matcherName,
message: message(),
stack: stack(),
passed: options.passed
};
if (!result.passed) {
result.expected = options.expected;
result.actual = options.actual;
}
return result;
function message() {
if (options.passed) {
// Here is the message overriden
return 'Passed.';
} else if (options.message) {
return options.message;
} else if (options.error) {
return messageFormatter(options.error);
}
return '';
}
function stack() {
if (options.passed) {
return '';
}
var error = options.error;
if (!error) {
try {
throw new Error(message());
} catch (e) {
error = e;
}
}
return stackFormatter(error);
}
}
return buildExpectationResult;
};
What I wanted is to override this function in my protractor protractor.conf.js file. And replace it with one with the desired behaviour.
I've tried to do so unsuccessfully doing the following:
onPrepare: function () {
jasmine.buildExpectationResult = function () {
function buildExpectationResult(options) {
var messageFormatter = options.messageFormatter || function () {
},
stackFormatter = options.stackFormatter || function () {
};
return {
matcherName: options.matcherName,
expected: options.expected,
actual: options.actual,
message: message(),
stack: stack(),
passed: options.passed
};
function message() {
if (options.message) {
return options.message;
} else if (options.error) {
return messageFormatter(options.error);
}
return "";
}
function stack() {
if (options.passed) {
return "";
}
var error = options.error;
if (!error) {
try {
throw new Error(message());
} catch (e) {
error = e;
}
}
return stackFormatter(error);
}
}
return buildExpectationResult;
};
}
Then my questions is: What is the right way to override a jasmine method?
Since we use gulp task to run protractor tests, we override the lib (like jasmine lib) as one of the gulp task with custom copy. We do that as part of installation or every test execution.
I didn't find any good way to override it unless we create another npm module.
I had the same issue, I'm not sure if my solution
onPrepare: function () {
// ...
jasmine.Spec.prototype.addExpectationResult = function(passed, data, isError) {
var buildExpectationResult = function(options) {
var messageFormatter = options.messageFormatter || function() {},
stackFormatter = options.stackFormatter || function() {};
var result = {
matcherName: options.matcherName,
message: message(),
stack: stack(),
passed: options.passed
};
if(!result.passed) {
result.expected = options.expected;
result.actual = options.actual;
}
return result;
function message() {
if (options.passed) {
return options.message ? options.message : 'Passed';
} else if (options.message) {
return options.message;
} else if (options.error) {
return messageFormatter(options.error);
}
return '';
}
function stack() {
if (options.passed) {
return '';
}
var error = options.error;
if (!error) {
try {
throw new Error(message());
} catch (e) {
error = e;
}
}
return stackFormatter(error);
}
}
var exceptionFormatter = jasmine.ExceptionFormatter;
var expectationResultFactory = function(attrs) {
attrs.messageFormatter = exceptionFormatter.message;
attrs.stackFormatter = exceptionFormatter.stack;
return buildExpectationResult(attrs);
}
var expectationResult = expectationResultFactory(data);
if (passed) {
this.result.passedExpectations.push(expectationResult);
} else {
this.result.failedExpectations.push(expectationResult);
if (this.throwOnExpectationFailure && !isError) {
throw new j$.errors.ExpectationFailed();
}
}
};
// ...
}

Future functions in DART working with ORACLE DART pub

I'm using oracledart pub, and need to get the results returned as Map to the main function, I know it is a FUTURE function, and read about FUTURE, but looks still not clear for me, or I'm doing something wrong in my code, my function is as below:
void main() {
var ORAresults = <Map>[];
ORA()
.then((results) => ORAresults = results)
.catchError((e) => 'Sorry, something wrong!');
}
ORA() {
var results = <Map>[];
connect(
"SYSTEM","pswd",
"(DESCRIPTION="
"(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))"
"(CONNECT_DATA=(SERVICE_NAME=XE)(SERVER=DEDICATED)))")
.then(
(oracleConnection) {
var resultset = oracleConnection.select("select * from vendors");
while(resultset.next()) {
results.add({"code":"vCode 1","name": "${resultset.getStringByName('NAME')}"});
}
print('the results inside $results'); // this works very well
return results;
},
onError: (error) {
print("Failed to connect: $error");
});
}
When I run the above, I get this error:
Breaking on exception: object of type NoSuchMethodError
the file dart:core-patch_object_patch.dart is opening, and pointing to:
noSuchMethod(Invocation invocation) {
=> return _noSuchMethod(invocation.isMethod, // this line is being highlighted!
internal.Symbol.getName(invocation.memberName),
invocation._type,
invocation.positionalArguments,
_symbolMapToStringMap(invocation.namedArguments));
}
I thing the error is due to something wrong here, because if I removed these lines, the error disappear.:
ORA()
.then((results) => ORAresults = results)
.catchError((e) => 'Sorry, something wrong!');
any help pls.
Your ORA() function does not return the Future it uses. Change the connect( line to return connect(, and it should work.
When you do ORA().then(...), you're using ORA()'s return value as a Future, but your ORA() function returns null (it has no return statement, so it returns null by default). What you really want to do is return the Future you're building on with the connect().
Thanks #Tonio and #Robert, I think now I understood the meaning of the FUTURE better :)
I was able to solve the issue, based on your hints and explanations, as below:
in the server.dart
void handlePost(HttpRequest req) {
HttpResponse res = req.response;
switch (req.uri.path) {
...
case '/getVendors':
getVendors(req);
break;
default:
break;
}
}
void getVendors(HttpRequest req) {
HttpResponse res = req.response;
addCorsHeaders(res);
print('${req.method}: ${req.uri.path}');
var vendors = <Map>[];
connect(
"SYSTEM",
"pswrd",
"(DESCRIPTION="
"(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))"
"(CONNECT_DATA=(SERVICE_NAME=XE)(SERVER=DEDICATED)))")
.then(
(oracleConnection) {
var resultset = oracleConnection.select("select * from vendors");
while(resultset.next()) {
vendors.add({"code":"${resultset.getStringByName('CODE')}","name": "${resultset.getStringByName('NAME')}"});
}
res.write(JSON.encode(vendors));
res.close();
},
onError: (error) {
print("Failed to connect: $error");
});
}
and in the client.dart
main(){
HttpRequest request;
String serverResponse = '';
...
}
void submit(){
request = new HttpRequest();
request.onReadyStateChange.listen(onData_getvendors);
var url = 'http://127.0.0.1:8004/getVendors';
request.open('POST', url);
request.send('');
}
onData_getvendors(_){
if (request.readyState == HttpRequest.DONE && request.status == 200) { // Data saved OK.
for(Map vendor in JSON.decode(request.responseText)){
vendor..children.add(new OptionElement(value: vendor['code'], data: vendor['name']));
}
else if (request.readyState == HttpRequest.DONE &&
request.status == 0) { // Status is 0...most likely the server isn't running.
serverResponse=request.responseText;
}
}

Resources