Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

raz

Package Overview
Dependencies
Maintainers
1
Versions
96
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

raz - npm Package Compare versions

Comparing version 0.0.78 to 0.0.80

core/bundle-js.js

9

core/errors/errors.en.js
const RazorError = require('./RazorError');
class ParserErrorFactory {

@@ -8,2 +7,3 @@ constructor(templateInfo, linesBaseNumber) {

this.info = templateInfo;
this.info.startLine = linesBaseNumber;
}

@@ -52,3 +52,3 @@

jsCodeBlockMissingClosingChar(line, codeFirstLine) {
var message = `The code or section block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup. The block starts at line ${line + 1} with text: "${codeFirstLine}"`;
var message = `The code or section block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup. The block starts at line ${line + this.startLineNum} with text: "${codeFirstLine}"`;
return RazorError.new({ message, info: this.info, line, capture: this.jsCodeBlockMissingClosingChar });

@@ -62,7 +62,2 @@ }

// invalidHtmlChar(ch, lineNum, posNum, afterText, expected) {
// var message = `"${ch}" is not a valid HTML character at line ${lineNum} pos ${posNum}` + (afterText ? ` after "${afterText}"` : expected ? ` (expected char = "${expected}")` : '.');
// return new RazorError(message, this.args, lineNum, posNum);
// }
missingMatchingStartTag(tag, line, pos) {

@@ -69,0 +64,0 @@ var message = `'${tag}' tag at line ${line + this.startLineNum} pos ${pos + 1} is missing matching start tag.`;

@@ -1,3 +0,2 @@

const htmlEncode = require('js-htmlencode');
const path = require('path');
const htmlEncode = require('../libs/js-htmlencode');

@@ -11,7 +10,5 @@ /////////////////////////////////////////////////////////////////////////

module.exports = class RazorError extends Error {
constructor(message, args, captureFrame) {
class RazorError extends Error {
constructor(message, captureFrame) {
super(message);
// this.name = this.constructor.name;
//this.data = Object.assign({ line: args.line, pos: args.pos, len: args.len }, this.data || {});

@@ -23,3 +20,3 @@ if (Error.captureStackTrace)

static new(args) {
let exc = new RazorError(args.message, args, args.capture || this.new);
let exc = new RazorError(args.message, args.capture || this.new);
this.extend(exc, args);

@@ -30,3 +27,3 @@ return exc;

static extend(exc, args) {
exc.name = RazorError.name;
exc.isRazorError = true;

@@ -54,3 +51,5 @@ if (exc.data) {

for (var data = this.data; data; data = data.inner) {
codeHtml += "<div class='arrow'>&#8681;</div>"
if (Utils.isServer)
codeHtml += "<div class='arrow'>&#8681;</div>"
codeHtml += dataToHtml(data, mainInfo);

@@ -138,5 +137,13 @@ codeHtml += '<hr />'

module.exports = RazorError;
function stackToHtml(exc, data, mainInfo) {
let lines = exc.stack.split('\n');
let fireFox = (typeof navigator !== 'undefined') && navigator.userAgent.toLowerCase().indexOf('firefox') !== -1; // for compatibility with FireFox
if (fireFox) {
let message = `${exc.name}: ${exc.message}`;
lines.unshift(message);
}
let html = '<div>';

@@ -146,4 +153,14 @@

let line = lines[i];
if (fireFox){
let parts = line.split('@');
if (parts.length === 2){
if (!parts[0]) // empty
parts[0] = "<anonymous>";
if (i === 0 && (line.startsWith("evalmachine.") || line.startsWith("undefined:"))) {
line = `at ${parts[0]} (${parts[1]})`;
}
}
else if (i === 0 && (line.startsWith("evalmachine.") || line.startsWith("undefined:"))) {
let nextLineExists = i < lines.length + 1;

@@ -200,3 +217,4 @@

lines = data.jshtml.split('\n');
html = "<ol start='0'>";
let startLine = data.startLine ? data.startLine : 0;
html = `<ol start='${startLine}'>`;

@@ -234,3 +252,3 @@ for (let i = 0; i < lines.length; i++) {

let end = htmlEncode(line.substring(pos + len));
htmlLine = `<span>${start}</span><span class='${multilight || "highlight"}' title='${mainInfo.title}'>${one}</span><span>${end}</span>`;
htmlLine = `<span>${start}</span><span class='${multilight || "highlight"} source-error' title='${mainInfo.title}'>${one}</span><span>${end}</span>`;
highlight = "class='highlight'";

@@ -257,3 +275,3 @@

//let fileFolder = path.dirname(data.filename);
let fileName = path.basename(data.filename);
let fileName = `<div class="filepath">${Utils.isServer ? Utils.path.basename(data.filename) : "Template:"}</div>`;

@@ -263,3 +281,3 @@ html += "</ol>";

<div class="code">
<div class="filepath">${fileName}</div>
${fileName}
${html}

@@ -266,0 +284,0 @@ </div>

@@ -34,12 +34,9 @@ 'use strict';

opts = opts || {};
const dbg = require('./dbg/debugger');
const debugMode = isDebugMode(opts);
const allowLoggingInDebugModel = false;
const log = require('./dbg/logger')({ on: debugMode && allowLoggingInDebugModel });
const debugMode = opts.debug;
const log = opts.log || { debug: () => { } };
log.debug(`Parse debug mode is '${!!debugMode}'.`);
const HtmlString = require('./HtmlString');
const htmlEncode = require('js-htmlencode');
const vm = debugMode ? require('vm') : null;
const htmlEncode = require('./libs/js-htmlencode');
const vm = opts.vm;

@@ -272,3 +269,3 @@ ////////////////////

function setDbg(code, block){
function setDbg(code, block) {
return `

@@ -315,3 +312,3 @@ Html.__dbg.pos = { start:${block.posStart}, end: ${block.posEnd} };

constructor(args) {
args.filePath = args.filePath || "no";
args.filePath = args.filePath || "js-script";
let linesBaseNumber = (debugMode && opts.express) ? 0 : 1; // in debug-mode the file-path of a template is added as a very first line comment

@@ -333,3 +330,3 @@ this.args = args;

compilePage(htmlObj, this.args.model, this.args.viewData, isDebugMode(opts), (err, html) => {
compilePage(htmlObj, this.args.model, this.args.viewData, debugMode, (err, html) => {
if (err)

@@ -360,3 +357,3 @@ return error(err, htmlObj.__dbg);

var html = this.getHtml(htmlArgs);
compilePageSync(html, this.args.model, this.args.viewData, isDebugMode(opts));
compilePageSync(html, this.args.model, this.args.viewData, debugMode);
this.checkSections();

@@ -1033,9 +1030,9 @@ }

if (["while", "catch", "if"].some(e => waitAcc === e)){
operatorExpectScope = '(';
if (["while", "catch", "if"].some(e => waitAcc === e)) {
operatorExpectScope = '(';
}
else if ("finally" === waitAcc){
else if ("finally" === waitAcc) {
operatorExpectScope = '{';
}
else if ("else" === waitAcc){
else if ("else" === waitAcc) {
operatorExpectScope = '{';

@@ -1073,5 +1070,5 @@ waitOperator = 'if';

if (operatorExpectScope && !Char.isWhiteSpace(ch) && ch !== operatorExpectScope){
if (operatorExpectScope && !Char.isWhiteSpace(ch) && ch !== operatorExpectScope) {
if (!waitOperator)
throw this.er.characterExpectedAfter(operatorExpectScope, this.lineNum, this.linePos(), operatorName); // [Code 58, Code 66.1, Code 67.1]
throw this.er.characterExpectedAfter(operatorExpectScope, this.lineNum, this.linePos(), operatorName); // [Code 58, Code 66.1, Code 67.1]
}

@@ -1451,8 +1448,4 @@

function isDebugMode(opts) {
return opts.debug || dbg.isDebugMode(opts.mode);
}
function toParserError(err, errorFactory) {
if (err.name === RazorError.name) {
if (err.isRazorError) {
// it could be the 2-nd or most time here from the stack

@@ -1465,17 +1458,14 @@ // Error.captureStackTrace(err, toParserError);

// ^
let pos = err.stack.indexOf(`${RazorError.name}: `);
let pos = err.stack.indexOf("\nError");
if (pos > 0)
err.stack = err.stack.substring(pos);
err.stack = err.stack.substring(pos + 1);
}
// Is not "born" as RazorError.
let isNotRazorError = !err.__dbg && err.name !== RazorError.name;
let isNotRazorError = !err.__dbg && !err.isRazorError;
if (isNotRazorError || err.__dbg && err.__dbg.viewName !== (err.data && err.data.filename))
errorFactory.extendError(err);
// if (err.stack)
// parserError.stack = err.stack;
return err;

@@ -1496,3 +1486,4 @@ }

},
compileSync: args => {
compileSync: function () {
let args = Array.prototype.slice.call(arguments);
args = prepareArgs(args);

@@ -1504,4 +1495,8 @@ return compileSync(args).html;

function prepareArgs(args) {
if (String.is(args))
args = { template: args };
if (args.length) { // it's called from `compileSync`
if (String.is(args[0]))
args = { template: args[0], model: args[1] }; // arguments are not passed as an object
else
args = args[0];
}

@@ -1513,3 +1508,1 @@ args.root = true;

}; // module.export
require('./utils');
const fs = require('fs');
const path = require('path');
Utils.path = path;
Utils.isServer = true;
// path.fileName = function (fullFileName, withExt) {
// if (withExt) return path.win32.basename(fullFileName);
// let extension = path.extname(fullFileName);
// return path.win32.basename(fullFileName, extension);
// };
path.cutLastSegment = function (dir) {
dir = path.normalize(dir);
let pos = dir.lastIndexOf(path.sep);
if (pos === -1) return '';
return dir.substring(0, pos);
};
const initParser = require('./parser');
const ErrorsFactory = require('./errors/errors');
const dbg = require('./dbg/debugger');
const allowLoggingInDebugModel = false;

@@ -16,3 +32,6 @@ 'use strict';

this.env = options.settings.env;
this.parser = initParser({ mode: this.env, express: true });
const debug = dbg.isDebugMode(this.env);
const log = require('./dbg/logger')({ on: debug && allowLoggingInDebugModel });
const vm = debug ? require('vm') : null;
this.parser = initParser({ debug, express: true, dbg, log, vm });
this.viewsDir = path.normalize(this.options.settings.views);

@@ -262,2 +281,2 @@ }

// }
}
}

@@ -5,2 +5,4 @@ ////////////////////////////////////////////////

if (typeof Utils === 'undefined') Utils = {};
String.whitespaces = '\r\n\t ';

@@ -78,3 +80,2 @@

if (!Char.isLetter) {

@@ -100,27 +101,2 @@ Char.isLetter = function (c) {

return Char.isLetter(c) || Char.isDigit(c) || '_$'.includes(c);
}
////////////////////////////////////////////////
// path
////////////////////////////////////////////////
const path = require('path');
path.fileName = function (fullFileName, withExt) {
if (withExt) return path.win32.basename(fullFileName);
let extension = path.extname(fullFileName);
return path.win32.basename(fullFileName, extension);
};
path.cutLastSegment = function (dir) {
dir = path.normalize(dir);
let pos = dir.lastIndexOf(path.sep);
if (pos === -1) return '';
return dir.substring(0, pos);
};
//deleteObjectProperties(obj) {
// for (var p in obj)
// if (Object.prototype.hasOwnProperty.call(obj, p))
// delete obj[p];
//}
}

@@ -79,3 +79,3 @@ [<< Back to start](../README.md)

if (env !== "production" && err.name == "RazorError") {
if (env !== "production" && err.isRazorError) {
var errorHtml = err.html();

@@ -96,3 +96,3 @@ res.status(500);

## Parser errors & runtime errors
Although all errors are exposed to the user as an exception named *"RazorError"*, in fact, there are 2 types of errors and they occur at different stages of template processing. They are *parser errors* and *runtime errors*.
There are 2 types of errors and they occur at different stages of template processing: they are *parser errors* and *runtime errors*.

@@ -99,0 +99,0 @@ You have already seen an example of the *parser error* in the ["Errors handling"](#errors-handling) section. Obviously, these errors occur in the process of parsing the template when the parser detects that there is something wrong with its structure. This can be both HTML errors and JavaScript syntax errors. But mostly at this stage HTML structure errors are detected (as in the example in the ["Errors handling"](#errors-handling) section).

@@ -108,6 +108,9 @@ # The overview of Razor-Express template engine (RAZ)

* If a partial view is specified *only by a file name* with or without an extension (as in the [Partial views section](#partial-views) example above) then the search begins with the directory in which the view that initiates the search is located. If the partial view is not found in the current directory the search goes on up the directory tree until it reaches the root views folder specified in the [Express app](https://expressjs.com/en/guide/using-template-engines.html) (which is set as `app.set('views', './views')` by default). If the file is still not found an error is returned.
* In the case where the *full path relative to the root views directory* is specified the file will be searched only in this directory. *Never include the views root folder name in the full path!*
* To make the search take place *only in the current directory*, use relative to the current directory path format `'./_partialView'`.
If a partial view is specified *only by a file name* with or without an extension (as in the [Partial views section](#partial-views) example above) then the search begins with the directory in which the view that initiates the search is located. If the partial view is not found in the current directory the search goes on up the directory tree until it reaches the root views folder specified in the [Express app](https://expressjs.com/en/guide/using-template-engines.html) (which is set as `app.set('views', './views')` by default). If the file is still not found an error is returned.
To specify a partial view by a path relative to the *root views directory* use slash `'/'` as the first character of the path. For example, with the path `"/partial-views/_login"` the partial view `"_login.raz"` file will be searched only in the `"[app-folder]/views/partial-views/"` directory, where `"[app-folder]"` is the full path to your NodeJS application script directory.
**_Never include the views root folder name_** in the relative paths - it is added automatically.
To set a path *relative to the current view directory*, use the relative to the current directory path formats, examples: `'./partial-views/_login'` or `'../partial-views/_login'`.
Different partial views with the same file name are allowed when the partial views are in different folders.

@@ -114,0 +117,0 @@

@@ -58,3 +58,3 @@ 'use strict';

if (dbg.isDebugMode(env) && err.name === RazorError.name) {
if (dbg.isDebugMode(env) && err.isRazorError) {
var errorHtml = err.html();

@@ -61,0 +61,0 @@ res.status(errorCode || 500);

{
"name": "raz",
"description": "Razor-like Template Engine for NodeJS Express library based on ASP.NET MVC Razor syntax. Template your views by mixing HTML markup with JavaScript server-side code!",
"version": "0.0.78",
"version": "0.0.80",
"author": {
"name": "Sergey Fisun",
"name": "Sergey F.",
"email": "develax@gmail.com",
"url": "https://www.npmjs.com/package/raz"
},
"license" : "MIT",
"keywords": [
"Razor",
"View",
"Template",
"Engine",
"NodeJS",
"Express",
"HTML",
"Parser"
],
"engines": {

@@ -28,10 +17,12 @@ "node": ">=10.10.0"

},
"main": "test/run-test-server.js",
"scripts": {
"build-js": "browserify ./core/bundle-js.js > raz.js",
"buildmon": "nodemon --watch core --exec \"npm run build-js\"",
"test": "mocha ./test/**/*.test.js",
"testmon": "nodemon --exec \"npm test\""
},
"dependencies": {
"js-htmlencode": "^0.3.0"
},
"dependencies": {},
"devDependencies": {
"browserify": "^16.2.3",
"chai": "^4.2.0",

@@ -45,3 +36,17 @@ "chai-http": "^4.2.0",

"proxyquire": "^2.1.0"
},
"license": "MIT",
"keywords": [
"Razor",
"View",
"Template",
"Engine",
"NodeJS",
"Express",
"HTML",
"Parser"
],
"bugs": {
"url": "https://github.com/DevelAx/RazorExpress/issues"
}
}

@@ -131,3 +131,3 @@ # RAZ: Razor-Express view template engine for NodeJS

Given all the mentioned and unmentioned pros and cons, I decided not to part with *Razor-syntax* and create something similar for using with [ExpressJS library](https://expressjs.com).
Given all the mentioned and unmentioned pros and cons, I decided not to part with *Razor-syntax* and create something similar for using with [ExpressJS library](https://expressjs.com) (it can work with other frameworks as well). This library works quite fast since it does not use third-party HTML parsers and regular expressions.

@@ -134,0 +134,0 @@ -----------------------

@@ -19,2 +19,9 @@ (function () {

describe("TEST BROWSER SIGNATURE", () => {
it("Test 1", () => {
let result = parser.compileSync("", { x: 1 });
expect(result).to.equal("");
});
});
describe("HTML CASES", () => {

@@ -21,0 +28,0 @@ describe("VALID HTML", () => {

@@ -6,3 +6,4 @@ //'use strict';

const path = require('path');
const app = require('express')();
const express = require('express');
const app = express();

@@ -24,2 +25,15 @@ const razor = require("../index");

// const raz = require("../index-browser");
// var result = raz.compile("<div>@Model</div>", 5);
var logger = function(req, res, next) {
console.log("request url: " + req.url);
next(); // Passing the request to the next handler in the stack.
}
app.use(logger);
var jsStatic = express.static(".");
app.use("/js", jsStatic);
app.get('/', (rq, rs) => {

@@ -37,2 +51,10 @@ rs.render("./home/index", { message: "This is my first NodeJS Express View engine!" });

app.get('/browser', (rq, rs) => {
rs.render("./home/browser", { message: "This is my first NodeJS Express View engine!" });
});
app.get('/browser-error', (rq, rs) => {
rs.render("./home/browser-error", { message: "This is my first NodeJS Express View engine!" });
});
app.get('*', (rq, rs) => {

@@ -39,0 +61,0 @@ let routePath = "." + rq.path;

@@ -10,4 +10,3 @@ console.log("STARTED: server.test.js");

const jquery = require('jquery');
// const path = require('path');
// const fs = require('fs');
const port = 8000;

@@ -41,3 +40,2 @@ const errorHeader = "A template compilation error occured";

const server = require('./server.live')().app;
const port = 8000;
var socket;

@@ -74,2 +72,3 @@

after(function (done) {
this.timeout(5000)
console.log(`Server is closing port ${port}.`);

@@ -206,20 +205,5 @@ socket.close((err) => {

let $ = jQuery(res.text);
let h1 = $('h1');
expect(h1.length).to.be.equal(1);
expect(h1.text()).to.have.string(errorHeader);
let errorMainLines = $('.error');
expect(errorMainLines, '1 error line is expected').to.have.lengthOf(1);
let errorText = "'</div>' tag at line 6 pos 1 is missing matching start tag";
let layouts = $(`#error:contains(${errorText})`);
expect(layouts, errorText).to.have.lengthOf(1);
let errorViews = $('.code');
expect(errorViews, '3 error views are expected').to.have.lengthOf(3);
let viewSourceHeader = $(errorViews[0]).find(`.filepath:contains(partialerror.raz)`);
expect(viewSourceHeader, '"partialerror.raz" header is expected').to.have.lengthOf(1);
let layoutSourceHeader = $(errorViews[1]).find(`.filepath:contains(_layout.raz)`);
expect(layoutSourceHeader, '"_layout.raz" header is expected').to.have.lengthOf(1);
let partialSourceHeader = $(errorViews[2]).find(`.filepath:contains(_partial.raz)`);
expect(partialSourceHeader, '"_partial.raz" header is expected').to.have.lengthOf(1);
errorText = $(errorViews[2]).find('.highlight').text();
expect(errorText).equal(errorText);
assertErrorHeader($);
assertErrorText($, "'</div>' tag at line 6 pos 1 is missing matching start tag");
assertSourceViews($, ["partialerror.raz", "_layout.raz", "_partial.raz"], "</div>");
console.log(`> testing rote ${route} is done`);

@@ -232,2 +216,85 @@ done();

});
{
let route = "/browser";
describe(route, () => {
console.log(`> testing rote ${route}...`);
it("razor-js", (done) => {
let options = {
resources: "usable",
runScripts: "dangerously"
};
JSDOM.fromURL("http://localhost:" + port + route, options)
.then(dom => {
setTimeout(() => {
let $ = jquery(dom.window);
let h1 = $('h1');
expect(h1.length).to.be.equal(1);
expect(h1.text()).to.have.string("RAZ browser dynamic test");
console.log(`> testing rote ${route} is done`);
done();
}, 1000);
},
err => done(err));
});
});
{
let route = "/browser-error";
describe(route, () => {
console.log(`> testing rote ${route}...`);
it("razor-js-error", (done) => {
let options = {
resources: "usable",
runScripts: "dangerously"
};
JSDOM.fromURL("http://localhost:" + port + route, options)
.then(dom => {
setTimeout(() => {
let $ = jquery(dom.window);
assertErrorHeader($);
assertErrorText($, "Error: '</span>' tag at line 5 pos 24 is missing matching start tag.");
assertSourceViews($, ["Template:"]);
console.log(`> testing rote ${route} is done`);
done();
}, 1000);
},
err => {
done(err);
});
});
});
}
}
});
function assertErrorHeader($) {
let h1 = $('h1');
expect(h1.length, "header must exist").to.be.equal(1);
expect(h1.text()).to.have.string(errorHeader);
}
function assertErrorText($, text) {
let errorMainLines = $('.error');
expect(errorMainLines, '1 error line is expected').to.have.lengthOf(1);
expect(errorMainLines.text(), "error message").to.have.string(text);
}
function assertSourceViews($, viewNames, lastViewNameErrorToken) {
let num = viewNames.length;
let errorViews = $('.code');
expect(errorViews, `${num} error views are expected`).to.have.lengthOf(num);
if (!viewNames) return;
for (var i = 0; i < viewNames.length; i++) {
let viewName = viewNames[i];
let viewSourceHeader = $(errorViews[i]).find(`.filepath:contains(${viewName})`);
expect(viewSourceHeader, `"${viewName}" header is expected`).to.have.lengthOf(1);
}
if (!lastViewNameErrorToken) return;
let errorText = $(errorViews[errorViews.length - 1]).find('.source-error').text();
expect(lastViewNameErrorToken).equal(errorText);
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc