How to fix 'TypeError: process.hrtime is not a function' in nativescript? - nativescript

I am building a nativescript (+Angular) app with aws-amplify. Particular while using the S3 Storage API from aws-amplify, I get following error:
AWSS3Provider - get signed url error TypeError: process.hrtime is not a function. (In 'process.hrtime()', 'process.hrtime' is undefined)
I am using the following polyfills
(window as any).global = window;
(window as any).process = {
env: { DEBUG: undefined },
};
In my code, I check if process is not undefined.
if(typeof process !== 'undefined') {
Storage.get('fileassets/asset.txt')
.then(result => alert(result))
.catch(err => alert(err));
} else {
alert("process is undefined");
}
There is no alert raised, but it seems the native code S3Provider relies on process.hrtime, that can't be resolved in nativescript non{N} environment
I expect that aws-amplify API is successfully executed, as It have no control to hack that to avoid calling process.hrtime.

Related

How can I access `figma.clientStorage` in a Figma Plugin UI?

In my plugin code (code.ts), I am using the ClientStorage Figma Plugin API to store some state.
How can I read data from clientStorage from UI code (ui.html)?
I am not sure that you can access clientStorage directly from the UI, but you can pass the stored value from code.ts to ui.html using figma.ui.postMessage.
Here is an example of code that is retrieving a value from clientStorage, and sending it to the UI:
function retrieveFromStorage() {
(async () => {
try {
var item = await figma.clientStorage.getAsync('item');
figma.ui.postMessage({ type: 'send-item', payload: item);
} catch (err) {
console.log(err);
}
}})();
}
And then you can access it in the UI like so:
if(event.data.pluginMessage.type == 'send-item') {
var item = event.data.pluginMessage.payload
}
In this example I am also using "type" to make sure I am receiving the correct message.

Cypress is ignoring exceptions and stop execution inspite of declairing "Cypress.on("uncaught:exception", (err, runnable) => { return false; });"

I am trying to use Cypress.io for automating salesforce application.
While trying to automate creating some entity in Salesforce my underline application is throwing some error. I want to ignore these uncaught exceptions and continue. I have already added following code in command.js and importing command.js in index.js
Cypress.on("uncaught:exception", (err, runnable) => {
return false;
});
However during execution, Cypress is returning true and doesn't continue with execution.

Is there a way to tell if your app is running in Microsoft Teams

I have a web app that needs to execute specific code if it is running in Microsoft Teams, however I haven't yet figured out if there is any way to tell if your app is running in teams. Any ideas or insight?
edit:
for anyone wondering we ended up using a combination of the two answers below, on app start it will check the url of the app to see if it contains "/teams". The teams app is told specifically to point to {app_name}/teams, if this case is true it will run the following code block:
import * as microsoftTeams from '#microsoft/teams-js';
if (window.location.pathname.includes('teams')) {
microsoftTeams.initialize(() => {
microsoftTeams.getContext(context => {
store.dispatch(teamsDetected(context.hostClientType!));
try {
microsoftTeams.settings.registerOnSaveHandler(saveEvent => {
microsoftTeams.settings.setSettings({
websiteUrl: window.location.href,
contentUrl: `${window.location.href}&teams`,
entityId: context.entityId,
suggestedDisplayName: document.title
});
saveEvent.notifySuccess();
});
microsoftTeams.settings.setValidityState(true);
} catch (err) {
console.error('failed to set teams settings')
}
});
});
}
As you have probably experienced, a call to microsoftTeams.getContext(...) never returns if you are not in Teams.
So I have a flag that I monitor with a setInterval and if this._teamsContext is truthy, and has sane values; and only if if has this._hasAttemptedConnection
It is a bit of a round-a-bout way.
Another mechanism I implemented a little later was passing in a flag with the URL entrypoint (in our case: this is a Teams Tab) https://<oururl>?context=teams and only using the Teams codepath when in Teams.
I have seen requests in the Microsoft Teams .js github to return a failure from the microsoftTeams.getContext(...) refer: is there any API to detect running in Teams or not?
Prior to the flag, I had some Typescript code that looks like
WireTeams(): Promise<boolean> {
this._hasAttemptedConnection = false
return new Promise<boolean>((resolve, reject) => {
microsoftTeams.initialize()
microsoftTeams.getContext((context) => {
if (context === null || context === undefined) {
resolve(false)
}
this._teamsContext = context
})
})
this._hasAttemptedConnection = true
}
As of 2022, Microsoft released version 2.0 of teams-js library. You can check https://www.npmjs.com/package/#microsoft/teams-js. You can now use the app module to check whether it is initialized.
import { app } from '#microsoft/teams-js';
bool initialized = app.isInitialized()

Site is not-secured in cypress window

Our site is secured & chrome also show "Secured" lock icon. But when I ran cypress automation test, cypress window shows "Not secured". So I got below error on console and page is not loaded.
SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS
error image
How to fix this issue
Note:We have sockJs client. So sockjs-client throws this error.
sockjs-client/lib/main.js:79
if (loc.protocol === 'https:' && !secure) {
throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
}
If you want to just hack around this error (as opposed to e.g. not throwing the error on localhost in the first place), you can mute it like this.
I've taken into account what you wrote in comments, and while I don't know the cause, let's bring out the big guns. If this doesn't work, then I don't know.
This assumes you're using cy.visit to load your page. Also, this won't work for non-page tests (e.g. when you don't load a page at all).
// cypress/support/index.js
Cypress.Commands.overwrite( 'visit', (origFn, url, opts = {}) => {
// normalize arguments
// -------------------------------------------------------------------------
if ( typeof url == 'string' ) {
opts.url = url;
} else {
opts = url;
}
// overwrite onBeforeLoad
// -------------------------------------------------------------------------
const _onBeforeLoad = opts.onBeforeLoad;
opts.onBeforeLoad = function ( win ) {
// monkey-patch `window.onerror` callback which Cypress uses for error
// handling. When cypress starts to use `addEventListener`, then we're
// in trouble.
// Note: By this time, Cypress should have added the callback. If this
// wasn't the case, we'd have to add a setter on `window.onerror` and
// ensure we wrap the callback, there.
const _onerror = win.onerror;
win.onerror = function ( err ) {
if (
typeof err === 'string' &&
err.includes('SecurityError: An insecure SockJS')
) return;
_onerror.call(win, ...arguments);
}
// add a regular listener in order to prevent logging to devTools console
win.addEventListener('error', ev => {
if (
ev && typeof ev.message === 'string' &&
ev.message.includes('SecurityError: An insecure SockJS')
) {
ev.preventDefault();
ev.stopImmediatePropagation();
}
});
// call user-supplied `onBeforeLoad` callback, if supplied
if ( _onBeforeLoad ) _onBeforeLoad(win);
}
// -------------------------------------------------------------------------
return origFn(opts);
});
Also see turning off all uncaught exception handling

After updating nativescript folder and files are not creating in my android phone

I'm able to create a folder if it not exists and save a newly written file in that folder previously. but after updating to latest nativescript the same code was not working and not give error properly.
and also I'm getting an error
Error: android.util.AndroidRuntimeException: Calling startActivity() from >outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. >Is this really what you want?
const fileSystemModule = require("tns-core-modules/file-system");
const documents = fileSystemModule.knownFolders.documents();
documents._path = "/storage/emulated/0/";
const folder = documents.getFolder('Reports/sample/');
const file = folder.getFile('fileName.xlsx');
file.writeText(viewModel.get("fileTextContent") || html_content)
.then((result) => {
return file.readText()
.then((res) => {
var toast = Toast.makeText("Exported to Excel Succesfully");
toast.show();
return res;
});
}).then((result) => {
console.log("---result---");
console.log(result); // im getting result, a html string
var intent = new android.content.Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(android.net.Uri.fromFile(new java.io.File(file._path)), "application/vnd.ms-excel");
application.android.context.startActivity(android.content.Intent.createChooser(intent, "Open Excel..."));
}).catch((err) => {
console.log(err);
});
before updating it was working fine. but now I don't know what happened to this.
It's a new requirement from Android itself. You must add FLAG_ACTIVITY_NEW_TASK flag to your intent.
With Android 9, you cannot start an activity from a non-activity context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you attempt to start an activity without passing this flag, the activity does not start, and the system prints a message to the log.
intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

Resources