NEAR protocol ReferenceError: Buffer is not defined - nearprotocol

I'm getting ReferenceError: Buffer is not defined when trying to use near-api-js.
The relevant lines of code are:
export const near = new Near({
networkId,
keyStore: new keyStores.BrowserLocalStorageKeyStore(),
nodeUrl,
walletUrl,
headers: null,
});
export const walletConnection = new WalletConnection(near, appKeyPrefix);
walletConnection.requestSignIn({ // This line causes the problem
contractId,
methodNames: [],
});
My project is a fresh installation of Gatsby.
Any ideas what I'm missing?

I ran yarn add buffer.
Then I prepended my file with these lines:
import * as buffer from 'buffer';
(window as any).Buffer = buffer.Buffer; // https://github.com/isaacs/core-util-is/issues/27#issuecomment-878969583
See https://github.com/isaacs/core-util-is/issues/27#issuecomment-878969583
Then it seemed to work.
But this feels like a weird hack, and I didn't expect to need to do something like this. But I couldn't find any better way in any NEAR docs. I'm curious what other people will suggest here.

This is pending issue in near-api-js, check here for more details, https://github.com/near/near-api-js/issues/757.
Might be resolve soon.

Related

How do you effectively solve node module issues when google isn't providing many answers?

I received this issue and google isn't providing many case-specific examples to work from. Can anyone decode this? I am not really sure what the main issue is.
I have followed the file path of the first issue to cjs.js file but there isn't much there
"use strict";
const loader = require("./index");
module.exports = loader.default;
And the file path of the second issue leads me to this
var correctedContent = params.removeCR && (os.EOL !== '\\r') ?
sourceContent.replace(ORPHAN_CR_REGEX, ' $1') :
sourceContent;
Github link for context.

Tips on solving 'DevTools was disconnected from the page' and Electron Helper dies

I've a problem with Electron where the app goes blank. i.e. It becomes a white screen. If I open the dev tools it displays the following message.
In ActivityMonitor I can see the number of Electron Helper processes drops from 3 to 2 when this happens. Plus it seems I'm not the only person to come across it. e.g.
Facing "Devtools was disconnected from the page. Once page is reloaded, Devtools will automatically reconnect."
Electron dying without any information, what now?
But I've yet to find an answer that helps. In scenarios where Electron crashes are there any good approaches to identifying the problem?
For context I'm loading an sdk into Electron. Originally I was using browserify to package it which worked fine. But I want to move to the SDKs npm release. This version seems to have introduced the problem (though the code should be the same).
A good bit of time has passed since I originally posted this question. I'll answer it myself in case my mistake can assist anyone.
I never got a "solution" to the original problem. At a much later date I switched across to the npm release of the sdk and it worked.
But before that time I'd hit this issue again. Luckily, by then, I'd added a logger that also wrote console to file. With it I noticed that a JavaScript syntax error caused the crash. e.g. Missing closing bracket, etc.
I suspect that's what caused my original problem. But the Chrome dev tools do the worst thing by blanking the console rather than preserve it when the tools crash.
Code I used to setup a logger
/*global window */
const winston = require('winston');
const prettyMs = require('pretty-ms');
/**
* Proxy the standard 'console' object and redirect it toward a logger.
*/
class Logger {
constructor() {
// Retain a reference to the original console
this.originalConsole = window.console;
this.timers = new Map([]);
// Configure a logger
this.logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new winston.transports.File(
{
filename: `${require('electron').remote.app.getPath('userData')}/logs/downloader.log`, // Note: require('electron').remote is undefined when I include it in the normal imports
handleExceptions: true, // Log unhandled exceptions
maxsize: 1048576, // 10 MB
maxFiles: 10
}
)
]
});
const _this = this;
// Switch out the console with a proxied version
window.console = new Proxy(this.originalConsole, {
// Override the console functions
get(target, property) {
// Leverage the identical logger functions
if (['debug', 'info', 'warn', 'error'].includes(property)) return (...parameters) => {
_this.logger[property](parameters);
// Simple approach to logging to console. Initially considered
// using a custom logger. But this is much easier to implement.
// Downside is that the format differs but I can live with that
_this.originalConsole[property](...parameters);
}
// The log function differs in logger so map it to info
if ('log' === property) return (...parameters) => {
_this.logger.info(parameters);
_this.originalConsole.info(...parameters);
}
// Re-implement the time and timeEnd functions
if ('time' === property) return (label) => _this.timers.set(label, window.performance.now());
if ('timeEnd' === property) return (label) => {
const now = window.performance.now();
if (!_this.timers.has(label)) {
_this.logger.warn(`console.timeEnd('${label}') called without preceding console.time('${label}')! Or console.timeEnd('${label}') has been called more than once.`)
}
const timeTaken = prettyMs(now - _this.timers.get(label));
_this.timers.delete(label);
const message = `${label} ${timeTaken}`;
_this.logger.info(message);
_this.originalConsole.info(message);
}
// Any non-overriden functions are passed to console
return target[property];
}
});
}
}
/**
* Calling this function switches the window.console for a proxied version.
* The proxy allows us to redirect the call to a logger.
*/
function switchConsoleToLogger() { new Logger(); } // eslint-disable-line no-unused-vars
Then in index.html I load this script first
<script src="js/logger.js"></script>
<script>switchConsoleToLogger()</script>
I had installed Google Chrome version 79.0.3945.130 (64 bit). My app was going to crash every time when I was in debug mode. I try all the solutions I found on the web but no one was useful. I downgrade to all the previous version:
78.x Crashed
77.x Crashed
75.x Not Crashed
I had to re-install the version 75.0.3770.80 (64 bit). Problem has been solved. It can be a new versions of Chrome problem. I sent feedback to Chrome assistence.
My problem was that I was not loading a page such as index.html. Once I loaded problem went away.
parentWindow = new BrowserWindow({
title: 'parent'
});
parentWindow.loadURL(`file://${__dirname}/index.html`);
parentWindow.webContents.openDevTools();
The trick to debugging a crash like this, is to enable logging, which is apparently disabled by default. This is done by setting the environment variable ELECTRON_ENABLE_LOGGING=1, as mentioned in this GitHub issue.
With that enabled, you should see something along the lines of this in the console:
You can download Google Chrome Canary. I was facing this problem on Google Chrome where DevTools was crashing every time on the same spot. On Chrome Canary the debugger doesn't crash.
I also faced the exact same problem
I was trying to require sqlite3 module from renderer side
which was causing a problem but once i removed the request it was working just fine
const {app , BrowserWindow , ipcMain, ipcRenderer } = require('electron')
const { event } = require('jquery')
const sqlite3 = require('sqlite3').verbose(); // <<== problem
I think the best way to solve this (if your code is really really small) just try to remove functions and run it over and over again eventually you can narrow it down to the core problem
It is a really tedious , dumb and not a smart way of doing it , but hey it worked
I encountered this issue, and couldn't figure out why the the DevTool was constantly disconnecting. So on a whim I launched Firefox Developer edition and identified the cause as an undefined variable with a string length property.
if ( args.length > 1 ) {
$( this ).find( "option" ).each(function () {
$( $( this ).attr( "s-group" ) ).hide();
});
$( args ).show();
}
TL;DR Firefox Developer edition can identify these kinds of problems when Chrome's DevTool fails.
After reading the comments above it is clear to me that there is a problem at least in Chrome that consists of not showing any indication of what the fault comes from. In Firefox, the program works but with a long delay.
But, as Shane Gannon said, the origin of the problem is certainly not in a browser but it is in the code: in my case, I had opened a while loop without adding the corresponding incremental, which made the loop infinite. As in the example below:
var a = 0;
while (a < 10) {
...
a ++ // this is the part I was missing;
}
Once this was corrected, the problem disappeared.
I found that upgrading to
react 17.0.2
react-dom 17.0.2
react-scripts 4.0.3
but also as react-scripts start is being used to run electron maybe its just react scripts that needs updating.
Well I nearly went crazy but with electron the main problem I realized I commented out the code to fetch (index.html)
// and load the index.html of the app.
mainWindow.loadFile('index.html');
check this side and make sure you have included it. without this the page will go black or wont load. so check your index.js to see if there's something to load your index.html file :) feel free to mail : profnird#gmail.com if you need additional help
Downgrade from Electron 11 to Electron 8.2 worked for me in Angular 11 - Electron - Typeorm -sqlite3 app.
It is not a solution as such, but it is an assumption of why the problem.
In the angular 'ngOnInit' lifecycle I put too many 'for' and 'while' loops, one inside the other, after cleaning the code and making it more compact, the problem disappeared, I think maybe because it didn't finish the processes within a time limit I hope someone finds this comment helpful. :)
I have stumbled upon the similar problem, My approach is comment out some line that I just added to see if it works. And if that is the case, those problem is at those lines of code.
for(var i = 0;i<objLen; i+3 ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
The console works fine after i change the code to like this.
for(var i = 0;i<objLen; i=i+space ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
Open your google dev console (Ctrl + shift + i). Then press (fn + F1) or just F1, then scroll down and click on the Restore defaults and reload.

Laravel Webpack - Unwanted minification of top level variable

I have a variable in my main javascript file e.g. var example = {};.
After webpack has finished its job, I find that example is now referenced as t. This presents me a problem as I am using the variable across the web project. I bind functions onto objects for example:
var example = {};
example.initialise = function () {};
Finally at the bottom of a page I may invoke this section of script e.g:
<script>example.initialise()</script>
This way of writing javascript functions is not unusual...
This is obviously a huge pain in the ass as I have no control over the minification. Moreover, it appears that webpack doesn't figure out that example.initialise = function () {}; relates to its newly minified var example (becoming)--> var t. I.e. it doesn't become t.initialise = function {}; either.
What am I supposed to do here?
I've tried using rollup as well. The same kind of variable minification happens.
The thing is, this kind of minification/obfuscation is great, particularly on the inner workings of functions where there's little cause for concern over the parameter names. But not on the top level. I do not understand why this is happening, or how to prevent it.
Any ideas?
I assume that there are ways to set the configuration of webpack. E.g. inside webpack.config.js, but my perusing of the webpack docs gives me no easy understanding of what options I can use to resolve this, like preventing property minification in some way.
In laravel-elixir-webpack-official code you can see minify() is being applied here, minify() uses UglifyJS2 and mangling is on by default.
Mangling is an optimisation that reduces names of local variables and functions usually to single-letters (this explains your example object being renamed to t). See the doc here.
I don't see any way you can customize minify() behaviour in laravel-elixir-webpack, so for now you might have to monkey patch WebpackTask.prototype.gulpTask method before using the module (not an ideal solution). See the lines I am commenting out.
const WebpackTask = require('laravel-elixir-webpack-official/dist/WebpackTask').default;
WebpackTask.prototype.gulpTask = function () {
return (
gulp
.src(this.src.path)
.pipe(this.webpack())
.on('error', this.onError())
// .pipe(jsFiles)
// .pipe(this.minify())
// .on('error', this.onError())
// .pipe(jsFiles.restore)
.pipe(this.saveAs(gulp))
.pipe(this.onSuccess())
);
};
Turns out I have been silly. I've discovered that you can prevent top level properties from being minified by binding it to window... which in hindsight is something I've always known and was stupid not to have realised sooner. D'oh!
So all that needed to be done was to change all top-level properties like var example = {}; to something like window.app.example = {}; in which app is helping to namespace and prevent and override anything set by the language itself.

cfajaxproxy is sending invalid parameters?

For some reason that I don't understand, on my development machine can't call to function of a cfc component from a cfajaxproxy.
In my cfm document:
<cfajaxproxy cfc="#Application.CfcPath#.empleado"
jsclassname="ccEmpleado">
This works, and also I can instantiate an object to get all the functions of that cfc component:
var cfcEmpleado = new ccEmpleado();
But, when I try to call a function of that object:
var nb_Empleado = cfcEmpleado.RSEmpeladoNombreBIND(1,1);
Debug complains:
Error: The ID_EMPRESA parameter to the RSEmpeladoNombreBIND function is required but was not passed in.
I got this from Network tab on Chrome and figured out that something is generating an invalid parameter:
http://127.0.0.1/vpa/componentes/empleado.cfc?method=RSEmpeladoNombreBIND&_cf_ajaxproxytoken=[object%20Object]&returnFormat=json&_cf_nodebug=true&_cf_nocache=true&_cf_clientid=41C92098C98042112AE2B3AAF523F289&_cf_rc=0
As you can see, there's a parameter [object%20Object], that is messing around my request, and that's why it fails. I don't why is happening this. Other people has tested this, and it works, but in mine doesn't.
I have Coldfusion 9, Apache, Windows 8. Is is some configuration issue on Coldfusion, or a bug?
I can't tell if this is your error or not, but it might be. This was a problem that we had for awhile. You should consider using explicit names to avoid any confusion. Add the "js" in there.
<cfajaxproxy cfc="cfcEmpleado" jsclassname="proxyEmpleado">
var jsEmpleado = new proxyEmpleado();
I will try to find a link to an article about this very thing.

Swift Error : Use of module 'CMSampleBuffer' as a type

I saw below question to use 'captureStillImageAsynchronouslyFromConnection' function in swift:
How to convert code AVFoundation objective c to Swift?
When I try to use a AVFoundation function as following:
var stillImageOutput: AVCaptureStillImageOutput!
//...Initialize stillImageOutput
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(imageSampleBuffer, error) in
if imageSampleBuffer {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer as CMSampleBuffer) // I get error on this line saying: 'Use of module ' CMSampleBuffer' as a type'
self.processImage(UIImage(data: imageData))
}
})
I got the error on XCode, which says 'Use of module ' CMSampleBuffer' as a type'.
I tried to rewrite that same line multiple times with slightly different ways, but I could not figure out the solution.
Am I doing something wrong or is it possibly the shaky XCode Beta not working properly?
Thank you in advance.
#Jack and #Christian's solutions worked for me.
I was not careful enough to import CoreMedia.
I never used this framework before, and did not know if the problem was due to not having imported a correct framework.
Thank you for your help!

Resources