How to sanitize HTML in the filename - Javascript Coffeescript - coffeescript

i am very new to javascript/coffescript
I have no clue how to go about sanitizing an HTML in the filename
i would like to sanitize this html <br><small>Uploading #{data.files[0].name}</small> in the below code
if one could offer me some guidance would be grateful
filename: document_upload.coffee
#= require async_actions
$ () ->
$('#file-upload').fileupload
dataType: 'json'
submit: (e, data) ->
if fileValid data.files[0]
el = $('.document.uploading').clone().append "<br><small>Uploading #{data.files[0].name}</small>"
debugger
$('.documents').append el.css 'display', 'block'
else
return false
done: (e, data) ->
window.location.reload()
fail: (e, data) ->
el = $ '.documents .document:last-child'
el.addClass 'error'
el.children().fadeOut 300, () ->
el.find('span').removeClass('fa-refresh fa-spin').addClass 'fa-warning'
el.find('small').text 'Upload error'
el.children().fadeIn()

There are lots of sanitization libraries you could try out:
sanitize-html
HtmlSanitizer
Caja (by Google)
Other packages via NPM

Related

How to polylfill Buffer for jsonwebtoken in Wepack 5

I am upgrading to Webpack 5 and I have an issue with the package jsonwebtoken (https://github.com/auth0/node-jsonwebtoken) that needs Buffer (at https://github.com/auth0/node-jsonwebtoken/blob/master/sign.js#L91)
Since Webpack 5 polyfills are not included for nodejs functions and wen I try to use the function sign from jsonwebtoken it throws the following error :
message: "Buffer is not defined"
stack: "ReferenceError: Buffer is not defined↵
at module.exports (webpack-internal:///./node_modules/jsonwebtoken/sign.js:91:26)↵
To solve the issue I installed https://github.com/feross/buffer with
npm install buffer
and in my webpack config I added
resolve: {
fallback: {
"Buffer": require.resolve('buffer/'),
}
or
resolve: {
fallback: {
"buffer": require.resolve('buffer/'),
}
I also tried
resolve: {
fallback: {
"buffer": require.resolve('buffer/').Buffer,
}
But this last one produce a Webpack schema error :
configuration.resolve.fallback['Buffer'] should be one of these:
[non-empty string, ...] | false | non-empty string
-> New request.
Details:
* configuration.resolve.fallback['Buffer'] should be an array:
[non-empty string, ...]
-> Multiple alternative requests.
* configuration.resolve.fallback['Buffer'] should be false.
-> Ignore request (replace with empty module).
* configuration.resolve.fallback['Buffer'] should be a non-empty string.
-> New request.
at validate (/home/ant1/packcity/front-pmd/node_modules/webpack/node_modules/schema-utils/dist/validate.js:104:11)
Despite my trials it is not working and the error persists.
Did someone succeed in adding the polyfill for Buffer in their app bundled with Webpack ?
Any help would be really appreciated.
I just solved my issue by adding
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
}),
As suggested here https://github.com/ipfs/js-ipfs/issues/3369#issuecomment-721975183
I found this question when having a similar issue with Gatsby. To fix, I added:
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
plugins: [
new webpack.ProvidePlugin({
Buffer: [require.resolve("buffer/"), "Buffer"],
}),
]
}
}
to my gatsby-node.js config.
I have solved it this way in Gatsby. I didn't have to install the buffer dependency. Just added this to my gatsby-node.js file.
exports.onCreateWebpackConfig = ({ actions, stage, plugins }) => {
if (stage === 'build-javascript' || stage === 'develop') {
actions.setWebpackConfig({
plugins: [plugins.provide({ Buffer: ['buffer/', 'Buffer'] })]
});
}
};

In a vscode extension is there a way to programatically Invoke "repl.action.copyall" through vscode.commands.executeCommand(...)

In short, Im looking for a way to capture the text content of the debug console inside a vscode extension. The following code snippet does pretty much exactly what I want only for the Terminal instead of the debug console. You can also right click in the console and select -> copy all. In the end I wont be pasting it to a new code window but pushing it to an endpoint to automate test reporting.
vscode.commands.executeCommand('workbench.action.terminal.selectAll').then(() => {
vscode.commands.executeCommand('workbench.action.terminal.copySelection').then(() => {
vscode.commands.executeCommand('workbench.action.terminal.clearSelection').then(() => {
vscode.commands.executeCommand('workbench.action.files.newUntitledFile').then(() => {
vscode.commands.executeCommand('editor.action.clipboardPasteAction');
});
});
});
});
I have tried this but I get an error in the console.log
vscode.commands.executeCommand('repl.action.copyall').then(() => {
vscode.commands.executeCommand('workbench.action.files.newUntitledFile').then(() => {
vscode.commands.executeCommand('editor.action.clipboardPasteAction');
});
});
rejected promise not handled within 1 second: Error: command 'repl.action.copyall' not found
extensionHostProcess.js:1048
stack trace: Error: command 'repl.action.copyall' not found
at u._tryExecuteCommand (file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:4213:713)
at file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:4213:594
Any help pointing me in the right direction would be appreciated!
don't do callback hell with Promises
Just return a new Promise in the then() handler
vscode.commands.executeCommand('workbench.action.terminal.selectAll')
.then(() => vscode.commands.executeCommand('workbench.action.terminal.copySelection'))
.then(() => vscode.commands.executeCommand('workbench.action.terminal.clearSelection'))
.then(() => vscode.commands.executeCommand('workbench.action.files.newUntitledFile'))
.then(() => vscode.commands.executeCommand('editor.action.clipboardPasteAction'))

froalaEditor.file.beforeUpload Event not firing

I'm attempting implement the custom file upload feature of the Angular Froala WYSIWYS Editor. I've pasted my configuration options below.
In the console, I can see that both the froalaEditor.file.beforeUpload and froalaEditor.file.inserted events are triggered, but no HTTP action of any kind is fired and neither the froalaEditor.file.uploaded nor the froalaEditor.file.error events are triggered.
Does any know why Froala is not attempting to POST to my fileUploadUrl?
options: Object = {
fileUploadUrl: 'https://localhost:5001/api/file',
events: {
'froalaEditor.file.beforeUpload': function (e: any, editor: any, files: any) {
console.log('BEFORE UPLOAD', e, editor, files, files[0]);
},
'froalaEditor.file.inserted': function (e, editor, $file, response) {
console.log('INSERTED', e, editor, $file, response);
},
'froalaEditor.file.uploaded': function (e, editor, response) {
console.log('UPLOADED', e, editor, response);
},
'froalaEditor.file.error': function (e, editor, error, response) {
console.log('ERROR', e, editor, error, response);
},
}}
Version Info:
Angular CLI: 7.3.0
angular-froala-wysiwyg: "^2.9.1"
1)
While using command froalaEditor.file.beforeUpload and froalaEditor.file.inserted, if you wish to see the HTTP response on your URL kindly have the following property included -
fileUploadMethod: 'POST'
2)
Events can be triggered using -
console.log("Custom Message")
Refer JSFiddle - https://jsfiddle.net/dyt52pqk/2/

Twitter Typeahead.js with Yahoo Finance in AJAX

I am trying to couple the new version of Typeahead.js and using it with JSON that needs to be pulled from AJAX and not from a JSON file like they have in their examples. I just can't get it to work, I don't want to cache the JSON result or anything, I want to pull it live from Yahoo.
My HTML input is <input type="text" id="symbol" name="symbol" autofocus autocomplete="off" placeholder="Symbol" onkeyup="onSymbolChange(this.value)" />
My AJAX/PHP file has this to retrieve data (this part work, I tested it with Firebug)
header('Content-type:text/html; charset=UTF-8;');
$action = (isset($_GET['action'])) ? $_GET['action'] : null;
$symbol = (isset($_GET['symbol'])) ? $_GET['symbol'] : null;
switch($action) {
case 'autocjson':
getYahooSymbolAutoComplete($symbol);
break;
}
function getYahooSymbolAutoCompleteJson($symbolChar) {
$data = #file_get_contents("http://d.yimg.com/aq/autoc?callback=YAHOO.util.ScriptNodeDataSource.callbacks&query=$symbolChar");
// parse yahoo data into a list of symbols
$result = [];
$json = json_decode(substr($data, strlen('YAHOO.util.ScriptNodeDataSource.callbacks('), -1));
foreach ($json->ResultSet->Result as $stock) {
$result[] = '('.$stock->symbol.') '.$stock->name;
}
echo json_encode(['symbols' => $result]);
}
The JS file (this is where I'm struggling)
function onSymbolChange(symbolChar) {
$.ajax({
url: 'yahoo_autocomplete_ajax.php',
type: 'GET',
dataType: 'json',
data: {
action: 'autocjson',
symbol: symbolChar
},
success: function(response) {
$('#symbol').typeahead({
name: 'symbol',
remote: response.symbols
});
}
});
}
I don't think that I'm suppose to attach a typeahead inside an AJAX success response, but I don't see much examples with AJAX (except for a previous version of typeahead)... I see the JSON response with Firebug after typing a character but the input doesn't react so good. Any guidance would really be appreciated, I'm working on a proof of concept at this point... It's also worth to know that I'm using AJAX because I am in HTTPS and using a direct http to Yahoo API is giving all kind of problems with Chrome and new Firefox for insecure page.
UPDATE
To make it to work, thanks to Hieu Nguyen, I had to modify the AJAX JSON response from this echo json_encode(['symbols' => $result]); to instead this echo json_encode($result); and modify the JS file to use the code as suggested here:
$('#symbol').typeahead({
name: 'symbol',
remote: 'yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY'
});
I have to do it in reverse, i.e: hook the ajax call inside typeahead remote handler. You can try:
$('#symbol').typeahead({
name: 'symbol',
remote: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY'
});
You don't have to create onSymbolChange() function since typeahead will take care of that already.
You can also filter and debug the response from backend by using:
$('#symbol').typeahead({
name: 'symbol',
remote: {
url: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY',
filter: function(resp) {
var dataset = [];
console.log(resp); // debug the response here
// do some filtering if needed with the response
return dataset;
}
}
});
Hope it helps!

Chaining Promises in Coffeescript

Is there a way to chain Promises together in Coffeescript. For example, consider the following javascript code,
return $.getJSON('/api/post.json')
.then(function(response) {
// do something
})
.then(function(response) {
// do something
})
.then(null, function(err) {
// do something
});
Each of the then's is optional, and the final then needs to be returned by the function.
Currently I am writing this in coffeescript as,
promise = $.getJSON('/api/post.json')
promise = promise.then (response) ->
// do something
promise = promise.then (response) ->
// do something
promise = promise.then null, (err) ->
// do something
return promise
Is there a better way to do this? Thanks.
Ezekiel shows the right way, but it doesn't need the parentheses around the functions. Just do:
$.getJSON '/api/post.json' # As of CoffeeScript 1.7, you don't need the parentheses here either.
.then (response) ->
# do something
response # if you would not return anything, promise would be fulfilled with undefined
.then (response) ->
# do something
undefined # necessary to prevent empty function body
.then null, (err) ->
# handle error
I think it's surprisingly clean.
The one thing that's relatively messy is when you need to add onRejected and onFulfilled handlers at the same time.
Note: Last time I checked, this did not work in CoffeeScript Redux, but this was a few months ago.
Note 2: You need at least one line of actual code (i.e. not just a comment) in each function body for this to work. Typically, you will, so it's not a big issue.
This is my personal favorite way to write promises, with a little bit extra indentation
doSomething = () -> new RSVP.Promise (resolve, reject) ->
if 1 is 1
resolve 'Success'
else
reject 'Error'
doSomething()
.then (res) ->
console.log 'Step 1 Success Handler'
, (err) ->
console.log 'Step 1 Error Handler'
.then (res) ->
console.log 'Step 2 Success Handler'
.then (res) ->
console.log 'Step 3 Success Handler'
, (err) ->
console.log 'Step 3 Error Handler'
Which compiles to:
var doSomething;
doSomething = function() {
return new RSVP.Promise(function(resolve, reject) {
if (1 === 1) {
return resolve('Success');
} else {
return reject('Error');
}
});
};
doSomething().then(function(res) {
return console.log('Step 1 Success Handler');
}, function(err) {
return console.log('Step 1 Error Handler');
}).then(function(res) {
return console.log('Step 2 Success Handler');
}).then(function(res) {
return console.log('Step 3 Success Handler');
}, function(err) {
return console.log('Step 3 Error Handler');
});
There are some instances where this works really well too:
step1Success = (res) -> console.log 'Step 1 Success Handler'
step1Error = (err) -> console.log 'Step 1 Error Handler'
step2Success = (res) -> console.log 'Step 2 Success Handler'
step3Success = (res) -> console.log 'Step 3 Success Handler'
step3Error = (err) -> console.log 'Step 3 Error Handler'
doSomething()
.then(step1Success, step1Error)
.then(step2Success)
.then(step3Success, step3Error)
Tested on coffee-script v1.6.3
This is probably the best you'll do:
$.getJSON('/api/post.json')
.then( (response) ->
# do something
).then( (response) ->
# do something
).then null, (err) ->
# do something
Note the parentheses surrounding the then() arguments. Nothing earth shattering but hopefully this helps.