Precompile/compile nunjucks refresh issue gulp-inline-source - gulp

Hi there this is a long shot but, hope someone can help,
I am using gulp-inline-source-html (https://github.com/exuanbo/gulp-inline-source-html) & gulp-nunjucks-render (https://github.com/carlitoplatanito/gulp-nunjucks-render) plus browserSync to show the updated UI
The plugin .pipe(inlineSource(... does something, but the problem is i don't think it properly writes the file after doing css changes, as the html in the build folder is not updated. Only when I do a hard refresh the UI is updated.
gulpfile.js
pipe(nunjucksRender({
path: njkPaths,
ext: "",
data: ENV_VARS,
envOptions: {
trimBlocks: true,
lstripBlocks: true
}
}))
.pipe(inlineSource({
compress: false,
saveRemote: true,
handlers: [require("./nunjucksHandler.js")] ??
}))
I was trying the precompile approach https://github.com/popeindustries/inline-source/issues/70#issuecomment-384548345 (comment) but got nowhere.
nunjucksHandler.js
const Nunjucks = require('nunjucks');
module.exports = function nunjucks(source, context) {
return new Promise((resolve, reject) => {
if (
source.fileContent &&
!source.content &&
source.type == "text/css"
) {
let content;
try {
content = Nunjucks.precompile(source.fileContent);
} catch (err) {
return reject(err);
}
// Need to expose templates for later use somehow...
source.content = content
}
resolve();
});
};
.nunjucks
<link inline href="{{ENV_PARTIALS_BASE_PATH}}/common/terms-and-conditions/index.css"
rel="stylesheet"/>
<section>html</section>
{% somenunjucks syntax etc %}

Related

Chrome Extension embedding script in active web page, in MV3?

beautiful people on the internet. I am new to chrome extension not new to writing code though. I have implemented webpack to use external packages. One major one in my application is npm package by the name "mark.js".
My application works like this i want some specific words to be highlighted in active webpage using this package. I have written code for this to achieve the functionality but the problem is with loading the script in a web page. I have performed different aspect of loading script but that doesnot work. The new MV3 version have some strict rules.
I want to achieve anything similar of loading script in an active webpage. Please help.
btn.addEventListener("click", async () => {
console.log("BUTTON IS PRESSED!!");
try {
await chrome.tabs.query(
{ active: true, currentWindow: true },
async function (tabs) {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: highlightText,
args: [arr],
});
}
);
} catch (e) {
console.log("ERROR AT CHROME TAB QUERY : ", e);
}
});
async function highlightText(arr) {
console.log(typeof Mark);
try {
var instance2 = new Mark(document.querySelector("body"));
// instance2.mark("is");
var success = [];
// const instance2 = new Mark(document.querySelector("body"));
await Promise.all(
arr.map(async function (obj) {
console.log("OBJECT TEXT : ", obj.text);
instance2.mark(obj.text, {
element: "span",
each: function (ele) {
console.log("STYLING : ");
ele.setAttribute("style", `background-color: ${obj.color};`);
if (obj.title && obj.title != "") {
ele.setAttribute("title", obj.title);
}
ele.innerHTML = obj.text;
success.push({
status: "Success",
text: obj.text,
});
},
});
})
);
console.log("SUCCESS : ", success);
} catch (error) {
console.log(error);
}
}
There's no need to use chrome.runtime.getURL. Since you use executeScript to run your code all you need is to inject mark.js before injecting the function.
Also, don't load popup.js in content_scripts, it's not a content script (these run in web pages), it's a script for your extension page. Actually, you don't need content_scripts at all.
btn.addEventListener('click', async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const target = { tabId: tab.id };
const exec = v => (await chrome.scripting.executeScript({ target, ...v }))[0].result;
if (!await exec({ func: () => !!window.Mark })) {
await exec({files: ['mark.js.min'] });
await exec({func: highlightText, args: [arr] });
}
});
For V3 I assume you will want to use Content Scripts in your manifest to inject the javascript into every webpage it matches. I recently open-sourced TorpedoRead and had to do both V2 and V3, I recommend checking the repo as it sounds like I did something similar to you (Firefox is V2, Chrome is V3).
The code below need to be added to your manifest.json and this will execute on every page based on the matches property. You can read more about content scripts here: https://developer.chrome.com/docs/extensions/mv3/content_scripts/
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["yourscript.js"]
}
],

Is there a way to lint .html files in Angular using a custom EsLint plugin?

I would like to create a custom linting rule for HTML files inside and Angular2+ project that warns me when there is a clickable element without an ID set. By clickable element I mean and other custom Angular components which will have a click event.
The project is currently using EsLint and I am trying to create a custom plugin which would do the job.
Right now I tried to run this rule from a plugin that enforces to have a class called "btn" at least. But linting does trigger any warning, more than that, it seems like it does not lint .html files at all.
module.exports = {
meta: {
docs: {
description: '',
category: 'Possible Errors',
recommended: true,
},
fixable: null,
},
create: function (context) {
return {
JSXOpeningElement: (node) => {
const nodeType = node.name.name;
if (nodeType !== 'button') {
return;
}
const legalClassNameAttributes = node.attributes.filter((attr) => {
const isClassName = attr.type === 'JSXAttribute' && attr.name.name === 'className';
return isClassName && (attr.value.type !== 'Literal' ||
attr.value.value.includes('btn'));
});
if (!legalClassNameAttributes.length) {
context.report({
message:
'Use correct class',
node,
});
}
},
};
},
};

Gulp 4 - How to generate dynamic tasks based on two arrays

I'm building an e-mail generation pipeline (multiple templates) using nunjucks and json translation files. This means I need to loop over the multiple templates and the translation files, however I can't seem to get it working.
Tried adding another loop inside the templates.map(), but that doesn't seem to be working (or I'm doing it completely wrong ofcourse). It almost works, but it crashes at some point, generating only a few of the templates. The first template works, but it crashes at the second template:
The following tasks did not complete: <anonymous>
Did you forget to signal async completion?
source: https://cobwwweb.com/dynamic-tasks-gulp-4
var templates = [];
var languages = ["nl", "en"];
function generateTemplates(done) {
const tasks = templates.map((template) => {
return () => {
const langs = languages.map((lang) => {
return () =>
gulp.src(`source/templates/${template}`)
.pipe(data(function () {
return require(`./source/translations/${lang}/${template.split('.')[0] }.json`);
}))
.pipe(nunjucksRender({
path: ['source/partials']
}))
.pipe(gulp.dest('dist/' + lang));
});
return gulp.series(...langs, (seriesDone) => {
seriesDone();
})();
}
});
return gulp.series(...tasks, (seriesDone) => {
seriesDone();
done();
})();
}
I also tried generating tasks using 2 for-loops, but this only generates the last template of the array of the last language in the array (example: only en/template2 will be generated correctly). I do see in the console that the tasks are starting and finishing, but I don't see them anywhere. Maybe the loop is finished mush faster than the generation of tasks? :
var templates = fs.readdirSync('./source/templates');
var languages = ["nl", "en"];
for (var lang of languages) {
for (var template of templates) {
gulp.task(`${lang}-${template}`, function (done) {
return gulp.src(`source/templates/${template}`)
.pipe(data(function () {
return require(`./source/translations/${lang}/${template.split('.')[0]}.json`);
}))
.pipe(nunjucksRender({
path: ['source/partials']
}))
.pipe(gulp.dest(`dist/${lang}`));
});
tasks.push(`${lang}-${template}`);
}
}
gulp.task('genlang', gulp.series(tasks));
My folder structure:
/dist
/source
--/partials
--/templates
--/template1.html
--/template2.html
--/translations
--/en
--/template1.json
--/template2.json
--/nl
--/template1.json
--/template2.json
Fixed it myself, I needed to have some done cb's in the returns:
function generateTemplates(done) {
const tasks = templates.map((template) => {
return (doneTasks) => {
const langs = languages.map((lang) => {
return (doneLanguages) => {
gulp.src(`source/templates/${template}`)
.pipe(data(() => require(`./source/translations/${lang}/${template.split('.')[0]}.json`)))
.pipe(nunjucksRender({
path: ['source/partials']
}))
.pipe(gulp.dest('./dist/' + lang));
doneLanguages();
}
});
return gulp.parallel(...langs, (seriesDone) => {
seriesDone();
doneTasks();
})();
};
});

Vue.js dynamic component loading + hot reload

I have Laravel 5.3.21 application with Vue.js 1.0.28
I'm using hot-reload workflow with browserify-hmr plugin.
Here is the simple gulpfile.js used to achieve that:
var elixir = require('laravel-elixir');
var gutil = require('gulp-util');
require('laravel-elixir-browserify-official');
require('laravel-elixir-vueify');
// If 'gulp watch' is run
if (gutil.env._.indexOf('watch') > -1) {
// Enable watchify for faster builds
elixir.config.js.browserify.watchify.enabled = true;
// Add the browserify HMR plugin
elixir.config.js.browserify.plugins.push({
name: 'browserify-hmr',
options: {
url: 'http://1.2.3.4:2096',
hostname: '1.2.3.4',
port: 2096
}
})
}
elixir.config.js.browserify.watchify.options.poll = true;
elixir(function (mix) {
mix.copy('node_modules/datatables.net-bs/css/dataTables.bootstrap.css',
'resources/assets/css/vendor/dataTables.bootstrap.css');
mix.styles([
'vendor/dataTables.bootstrap.css'
]);
mix.sass('app.scss');
mix.browserify('app.js');
});
I need to load components dynamically from the resources/assets/js/views/ folder, so I could make my front-end code modular and based on current route name $Laravel->routeName = request()->route()->getName() in Laravel.
For example:
// Global Settings.
Route::get('admin/settings', 'Admin#settings')
->name('admin_global_settings');
Then in resources/assets/js/views/admin/admin_global_settings.js I have code to initialize Vue.js component and register it with Vue.js instance:
var FeaturedOpportunities = require( '../../components/Featured-Opportunities.vue' );
window.Vue.component('FeaturedOpportunities', FeaturedOpportunities);
That is all nice but here is the problem in resources/assets/js/app.js:
window.Vue = require('vue');
require('vue-resource');
Vue.http.interceptors.push((request, next) => {
request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);
next();
});
// Problem is here, have to keep track of all my routes and their corresponding modules:
var routes = {
'organization_invites_roles': function () {
require('./views/organization/organization_invites_roles');
},
'admin_global_settings': function () {
require('./views/admin/admin_global_settings');
},
};
// Is there a way to load it dynamically?
if (Laravel.routeName) {
if (routes[Laravel.routeName]) {
routes[Laravel.routeName]();
}
}
new Vue({
el: 'body',
components: {
},
ready() {
console.log('Vue and Vueify all set to go!');
}
});
I've found some way that could probably solve this issue: Compiling dynamically required modules with Browserify but not sure if this applicable for my case.

collectionfs generate download url

I am working on a project using meteor and collectionfs.
I upload files to collectionfs and have a filehandler in place. I can use the
{{cfsFileUrl "defaultFilehandler"}}
Handlebar Helper to display the url where the image is saved, but I can't download images from this URL.
When I copy it into my browser:
localhost:3000/cfs/contacts/Nj3WzrBKhqd9Mc9NP_defaultHandler.png
meteor routes me to the meteor page ( as if i had writen localhost:3000 )
Ultimately I would like to achieve two things:
1st
display the image using an html tag:
<img src=??? alt="your image" />
2nd
I would like to make sure that the user is allowed to see this image.
Having the 'download-url' is not sufficient security for me.
In order to get to the point i went through the normal tutorial from collectionFS:
client js
ContactsFS = new CollectionFS('contacts', { autopublish: false });
Deps.autorun(function() {
Meteor.subscribe('myContactsFiles');
});
Template.queueControl.events({
'change .fileUploader': function (e) {
var files = e.target.files;
for (var i = 0, f; f = files[i]; i++) {
ContactsFS.storeFile(f);
}
}
});
server js
ContactsFS = new CollectionFS('contacts', { autopublish: false });
ContactsFS.allow({
insert: function(userId, file) {
console.log('user'+userId+"file"+JSON.stringify(file));
console.log("WILL SAVE:"+userId && file.owner === userId );
return userId && file.owner === userId;
},
update: function(userId, files, fields, modifier) {
return _.all(files, function (file) {
return (userId == file.owner);
}); //EO iterate through files
},
remove: function(userId, files) { return false; }
});
Meteor.publish('myContactsFiles', function() {
if (this.userId) {
return ContactsFS.find({ owner: this.userId }, { limit: 30 });
}
});
ContactsFS.fileHandlers({
default1: function(options) { // Options contains blob and fileRecord — same is expected in return if should be saved on filesytem, can be modified
return { blob: options.blob, fileRecord: options.fileRecord }; // if no blob then save result in fileHandle (added createdAt)
}});
Answer 1:
You can use the updated 0.3.3+ version of collectionFS to publicly make those files accessable, or view them.
<img src="{{cfsFileUrl 'default1'}}">
where default1 is the name of the handler function you defined in ContactsFS.fileHandlers
Answer 2:
There is no secure solution build into collectionFS as of now, its in the making tho.