This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+9
View File
@@ -0,0 +1,9 @@
# The MIT License
Copyright 2021 Harminder Virk, contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+509
View File
@@ -0,0 +1,509 @@
# edge-lexer
> Generate tokens by parsing a raw edge markup file
[![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] [![synk-image]][synk-url]
Edge lexer produces a list of `tokens` by scanning for [Edge whitelisted syntax](https://github.com/edge-js/syntax).
This module is a blend of a `lexer` and an `AST generator`, since Edge doesn't need a pure [lexer](https://en.wikipedia.org/wiki/Lexical_analysis) that scans for each character. Edge markup is written within other markup languages like **HTML** or **Markdown** and walking over each character is waste of resources.
Instead, this module starts by detecting for the [Edge whitelisted syntax](https://github.com/edge-js/syntax) and then starts the lexical analysis within the detected markup.
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of contents
- [Table of contents](#table-of-contents)
- [Highlights](#highlights)
- [Performance](#performance)
- [Usage](#usage)
- [Pre-processing lines](#pre-processing-lines)
- [Terms used](#terms-used)
- [Tokens](#tokens)
- [Tag Token](#tag-token)
- [Escaped Tag Token](#escaped-tag-token)
- [Raw Token](#raw-token)
- [Comment Token](#comment-token)
- [NewLine Token](#newline-token)
- [Mustache Token](#mustache-token)
- [Safe Mustache Token](#safe-mustache-token)
- [Escaped Mustache Token](#escaped-mustache-token)
- [Escaped Safe Mustache Token](#escaped-safe-mustache-token)
- [Properties](#properties)
- [BlockProp](#blockprop)
- [Prop](#prop)
- [Mustache expressions](#mustache-expressions)
- [Errors](#errors)
- [Example](#example)
- [Raised exceptions](#raised-exceptions)
- [Maintainers](#maintainers)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Highlights
- Zero dependencies (Actually one dependency that is also to standardize edge errors).
- Just uses one regex statement. That also tested against [safe-regex](https://github.com/substack/safe-regex) for ReDOS
- Allows multiline expressions
- Collects line and columns for accurate stack traces.
- Detects for unclosed tags.
- Detects for unwrapped expressions and raises appropriate errors.
---
## Performance
Following measures are taken to keep the analysis performant.
1. Only analyse markup that is detected as Edge whitelisted syntax.
2. Only analyse `tags`, that are passed to the tokenizer. Which means even if the syntax for tags is whitelisted, the tokeniser will analyse them if they are used by your app.
3. Do not analyse Javascript expression and leave that for [edge-parser](https://github.com/edge-js/parser).
4. Only uses one Regular expression.
---
## Usage
```js
import { Tokenizer } from 'edge-lexer'
const template = `Hello {{ username }}`
const tags = {
if: {
block: true,
seekable: true,
},
}
// Filename is required to add it to error messages
const options = {
filename: 'welcome.edge',
}
const tokenizer = new Tokenizer(template, tags, options)
tokenizer.parse()
console.log(tokenizer.tokens)
```
---
## Pre-processing lines
You can also pre-process lines before the tokenizer tokenizes them.
```ts
const options = {
filename: 'welcome.edge',
onLine: (line: string) => {
// transform here and return new string value
return line
},
}
const tokenizer = new Tokenizer(template, {}, options)
```
---
## Terms used
This guide makes use of the following terms to identify core pieces of the tokenizer.
| Term | Token Type | Description |
| --------------------- | -------------- | ----------------------------------------------------------------------------------------------------- |
| Tag | tag | Tags are used to define logical blocks in the template engine. For example `if tag` or `include tag`. |
| Escaped Tag | e\_\_tag | Escaped tag, Edge will not evaluate it at runtime. |
| Mustache | mustache | Javascript expression wrapped in curly braces. `{{ }}` |
| Safe Mustache | s\_\_mustache | Safe mustache, that doesn't escape the output `{{{ }}}` |
| Escaped Mustache | e\_\_mustache | Mustache tag that is escaped |
| Escaped Safe Mustache | es\_\_mustache | Safe Mustache tag that is escaped |
| Raw | raw | A raw string, which has no meaning for the template engine |
| NewLine | newline | Newline |
| Comment | comment | Edge specific comment block. This will be ripped off in the output. |
---
## Tokens
Following is the list of Nodes returned by the tokenizer.
#### Tag Token
```js
{
type: 'tag'
filename: 'eval.edge',
loc: {
start: {
line: 1,
col: 4
},
end: {
line: 1,
col: 13
}
},
properties: BlockProp,
children: []
}
```
#### Escaped Tag Token
```diff
{
- type: 'tag',
+ type: 'e__tag',
filename: 'eval.edge',
loc: {
start: {
line: 1,
col: 4
},
end: {
line: 1,
col: 13
}
},
properties: BlockProp,
children: []
}
```
#### Raw Token
```js
{
type: 'raw',
filename: 'eval.edge',
line: number,
value: string
}
```
#### Comment Token
```js
{
type: 'comment',
filename: 'eval.edge',
line: number,
value: string
}
```
#### NewLine Token
```js
{
type: 'newline',
line: number
}
```
#### Mustache Token
```js
{
type: 'mustache',
filename: 'eval.edge',
loc: {
start: {
line: 1,
col: 4
},
end: {
line: 1,
col: 13
}
},
properties: Prop
}
```
#### Safe Mustache Token
```diff
{
- type: 'mustache',
+ type: 's__mustache',
filename: 'eval.edge',
loc: {
start: {
line: 1,
col: 4
},
end: {
line: 1,
col: 13
}
},
properties: Prop
}
```
#### Escaped Mustache Token
```diff
{
- type: 'mustache',
+ type: 'e__mustache',
filename: 'eval.edge',
loc: {
start: {
line: 1,
col: 4
},
end: {
line: 1,
col: 13
}
},
properties: Prop
}
```
#### Escaped Safe Mustache Token
```diff
{
- type: 'mustache',
+ type: 'es__mustache',
filename: 'eval.edge',
loc: {
start: {
line: 1,
col: 4
},
end: {
line: 1,
col: 13
}
},
properties: Prop
}
```
| Key | Value | Description |
| ---------- | ------ | ------------------------------------------------------------------------------- |
| type | string | The type of node determines the behavior of node |
| loc | object | `loc` is only present for tags and mustache tokens |
| line | number | `line` is not present for tags and mustache tokens |
| properties | Prop | Meta data for the node. See [Properties](#properties) to more info |
| value | string | If token is a raw or comment token, then value is the string in the source file |
| children | array | Array of recursive nodes. Only exists, when token is a tag |
---
## Properties
The properties `Prop` is used to define meta data for a given Node. Nodes like `raw`, `comment` and `newline`, doesn't need any metadata.
#### BlockProp
The block prop is used by the `Block` node. The only difference from the regular `Prop` is the addition of `selfclosed` attribute.
```js
{
name: string
jsArg: string,
selfclosed: boolean
}
```
#### Prop
```js
{
jsArg: string,
}
```
| Key | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------- |
| jsArg | The `jsArg` is the Javascript expression to evaluate. Whitespaces and newlines are preserved inside the jsArg |
| selfclosed | Whether or not the tag was `selfclosed` during usage. |
---
## Mustache expressions
For mustache nodes props, the `name` is the type of mustache expressions. The lexer supports 4 mustache expressions.
**mustache**
```
{{ username }}
```
**e\_\_mustache (Escaped mustache)**
The following expression is ignored by edge. Helpful when you want this expression to be parsed by a frontend template engine
```
@{{ username }}
```
**s\_\_mustache (Safe mustache)**
The following expression output is considered HTML safe.
```
{{{ '<p> Hello world </p>' }}}
```
**es\_\_mustache (Escaped safe mustache)**
```
@{{{ '<p> Not touched </p>' }}}
```
---
## Errors
Errors raised by the `lexer` are always an instance of [edge-error](https://github.com/edge-js/error) and will contain following properties.
```js
error.message
error.line
error.col
error.filename
error.code
```
---
## Example
```html
{{-- Show username when exists --}} @if(username) {{-- Wrap inside h2 --}}
<h2>Hello {{ username }}</h2>
@endif
```
The output of the above text will be
```json
[
{
"type": "comment",
"filename": "eval.edge",
"value": " Show username when exists ",
"loc": {
"start": {
"line": 1,
"col": 4
},
"end": {
"line": 1,
"col": 35
}
}
},
{
"type": "tag",
"filename": "eval.edge",
"properties": {
"name": "if",
"jsArg": "username",
"selfclosed": false
},
"loc": {
"start": {
"line": 2,
"col": 4
},
"end": {
"line": 2,
"col": 13
}
},
"children": [
{
"type": "newline",
"filename": "eval.edge",
"line": 2
},
{
"type": "comment",
"filename": "eval.edge",
"value": " Wrap inside h2 ",
"loc": {
"start": {
"line": 3,
"col": 4
},
"end": {
"line": 3,
"col": 24
}
}
},
{
"type": "newline",
"filename": "eval.edge",
"line": 3
},
{
"type": "raw",
"value": "<h2> Hello ",
"filename": "eval.edge",
"line": 4
},
{
"type": "mustache",
"filename": "eval.edge",
"properties": {
"jsArg": " username "
},
"loc": {
"start": {
"line": 4,
"col": 13
},
"end": {
"line": 4,
"col": 25
}
}
},
{
"type": "raw",
"value": " </h2>",
"filename": "eval.edge",
"line": 4
}
]
}
]
```
## Raised exceptions
Following the links to documented error codes raised by the lexer.
- [E_CANNOT_SEEK_STATEMENT](errors/E_CANNOT_SEEK_STATEMENT.md)
- [E_UNCLOSED_CURLY_BRACE](errors/E_UNCLOSED_CURLY_BRACE.md)
- [E_UNCLOSED_PAREN](errors/E_UNCLOSED_PAREN.md)
- [E_UNCLOSED_TAG](errors/E_UNCLOSED_TAG.md)
- [E_UNOPENED_PAREN](errors/E_UNOPENED_PAREN.md)
## Maintainers
[Harminder virk](https://github.com/sponsors/thetutlage)
[gh-workflow-image]: https://img.shields.io/github/workflow/status/edge-js/lexer/test?style=for-the-badge
[gh-workflow-url]: https://github.com/edge-js/lexer/actions/workflows/test.yml "Github action"
[npm-image]: https://img.shields.io/npm/v/edge-lexer.svg?style=for-the-badge&logo=npm
[npm-url]: https://npmjs.org/package/edge-lexer 'npm'
[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
[license-url]: LICENSE.md
[license-image]: https://img.shields.io/github/license/edge-js/lexer?style=for-the-badge
[synk-image]: https://img.shields.io/snyk/vulnerabilities/github/edge-js/lexer?label=Synk%20Vulnerabilities&style=for-the-badge
[synk-url]: https://snyk.io/test/github/edge-js/lexer?targetFile=package.json "synk"
+3
View File
@@ -0,0 +1,3 @@
export { Tokenizer } from './src/tokenizer';
export * as utils from './src/utils';
export * from './src/types.js';
+33
View File
@@ -0,0 +1,33 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.utils = exports.Tokenizer = void 0;
var tokenizer_1 = require("./src/tokenizer");
Object.defineProperty(exports, "Tokenizer", { enumerable: true, get: function () { return tokenizer_1.Tokenizer; } });
exports.utils = __importStar(require("./src/utils"));
__exportStar(require("./src/types.js"), exports);
+3
View File
@@ -0,0 +1,3 @@
import type { Tags, RuntimeTag, RuntimeComment, RuntimeMustache, LexerTagDefinitionContract } from './types';
export declare function getTag(content: string, filename: string, line: number, col: number, tags: Tags, claimTag?: (name: string) => LexerTagDefinitionContract | null): RuntimeTag | null;
export declare function getMustache(content: string, filename: string, line: number, col: number): RuntimeMustache | RuntimeComment | null;
+72
View File
@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMustache = exports.getTag = void 0;
const TAG_REGEX = /^(\s*)(@{1,2})(!)?([a-zA-Z._]+)(\s{0,2})/;
function getTag(content, filename, line, col, tags, claimTag) {
const match = TAG_REGEX.exec(content);
if (!match) {
return null;
}
const name = match[4];
let tag = tags[name];
if (!tag && claimTag) {
tag = claimTag(name);
}
if (!tag) {
return null;
}
const escaped = match[2] === '@@';
const selfclosed = !!match[3];
const whitespaceLeft = match[1].length;
const whitespaceRight = match[5].length;
const seekable = tag.seekable;
const block = tag.block;
const noNewLine = !!tag.noNewLine;
col += whitespaceLeft + match[2].length + name.length + whitespaceRight;
if (selfclosed) {
col++;
}
const hasBrace = seekable && content[col] === '(';
return {
name,
filename,
seekable,
selfclosed,
block,
line,
col,
escaped,
hasBrace,
noNewLine,
};
}
exports.getTag = getTag;
function getMustache(content, filename, line, col) {
const mustacheIndex = content.indexOf('{{');
if (mustacheIndex === -1) {
return null;
}
const realCol = mustacheIndex;
const isComment = content[mustacheIndex + 2] === '-' && content[mustacheIndex + 3] === '-';
if (isComment) {
return {
isComment,
filename,
line,
col: col + realCol,
realCol,
};
}
const safe = content[mustacheIndex + 2] === '{';
const escaped = content[mustacheIndex - 1] === '@';
return {
isComment,
safe,
filename,
escaped,
line,
col: col + realCol,
realCol,
};
}
exports.getMustache = getMustache;
+21
View File
@@ -0,0 +1,21 @@
import { EdgeError } from 'edge-error';
export declare function cannotSeekStatement(chars: string, pos: {
line: number;
col: number;
}, filename: string): EdgeError;
export declare function unclosedParen(pos: {
line: number;
col: number;
}, filename: string): EdgeError;
export declare function unopenedParen(pos: {
line: number;
col: number;
}, filename: string): EdgeError;
export declare function unclosedCurlyBrace(pos: {
line: number;
col: number;
}, filename: string): EdgeError;
export declare function unclosedTag(tag: string, pos: {
line: number;
col: number;
}, filename: string): EdgeError;
+44
View File
@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unclosedTag = exports.unclosedCurlyBrace = exports.unopenedParen = exports.unclosedParen = exports.cannotSeekStatement = void 0;
const edge_error_1 = require("edge-error");
function cannotSeekStatement(chars, pos, filename) {
return new edge_error_1.EdgeError(`Unexpected token "${chars}"`, 'E_CANNOT_SEEK_STATEMENT', {
line: pos.line,
col: pos.col,
filename: filename,
});
}
exports.cannotSeekStatement = cannotSeekStatement;
function unclosedParen(pos, filename) {
return new edge_error_1.EdgeError('Missing token ")"', 'E_UNCLOSED_PAREN', {
line: pos.line,
col: pos.col,
filename: filename,
});
}
exports.unclosedParen = unclosedParen;
function unopenedParen(pos, filename) {
return new edge_error_1.EdgeError('Missing token "("', 'E_UNOPENED_PAREN', {
line: pos.line,
col: pos.col,
filename: filename,
});
}
exports.unopenedParen = unopenedParen;
function unclosedCurlyBrace(pos, filename) {
return new edge_error_1.EdgeError('Missing token "}"', 'E_UNCLOSED_CURLY_BRACE', {
line: pos.line,
col: pos.col,
filename: filename,
});
}
exports.unclosedCurlyBrace = unclosedCurlyBrace;
function unclosedTag(tag, pos, filename) {
return new edge_error_1.EdgeError(`Unclosed tag ${tag}`, 'E_UNCLOSED_TAG', {
line: pos.line,
col: pos.col,
filename: filename,
});
}
exports.unclosedTag = unclosedTag;
+19
View File
@@ -0,0 +1,19 @@
export declare class Scanner {
private pattern;
private line;
private col;
private tolaretionCounts;
private tolerateLhs;
private tolerateRhs;
private patternLength;
closed: boolean;
match: string;
leftOver: string;
loc: {
line: number;
col: number;
};
constructor(pattern: string, toleratePair: [string, string], line: number, col: number);
private matchesPattern;
scan(chunk: string): void;
}
+70
View File
@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Scanner = void 0;
class Scanner {
pattern;
line;
col;
tolaretionCounts = 0;
tolerateLhs = '';
tolerateRhs = '';
patternLength = 0;
closed = false;
match = '';
leftOver = '';
loc;
constructor(pattern, toleratePair, line, col) {
this.pattern = pattern;
this.line = line;
this.col = col;
this.tolerateLhs = toleratePair[0];
this.tolerateRhs = toleratePair[1];
this.patternLength = this.pattern.length;
this.loc = {
line: this.line,
col: this.col,
};
}
matchesPattern(chars, iterationCount) {
for (let i = 0; i < this.patternLength; i++) {
if (this.pattern[i] !== chars[iterationCount + i]) {
return false;
}
}
return true;
}
scan(chunk) {
if (chunk === '\n') {
this.loc.line++;
this.loc.col = 0;
this.match += '\n';
return;
}
if (!chunk.trim()) {
return;
}
const chunkLength = chunk.length;
let iterations = 0;
while (iterations < chunkLength) {
const char = chunk[iterations];
if (this.tolaretionCounts === 0 && this.matchesPattern(chunk, iterations)) {
iterations += this.patternLength;
this.closed = true;
break;
}
if (char === this.tolerateLhs) {
this.tolaretionCounts++;
}
if (char === this.tolerateRhs) {
this.tolaretionCounts--;
}
this.match += char;
iterations++;
}
if (this.closed) {
this.loc.col += iterations;
this.leftOver = chunk.slice(iterations);
}
}
}
exports.Scanner = Scanner;
+42
View File
@@ -0,0 +1,42 @@
import { Scanner } from './scanner';
import { Tags, Token, RuntimeTag, RuntimeComment, RuntimeMustache, LexerTagDefinitionContract } from './types';
export declare class Tokenizer {
private template;
private tagsDef;
private options;
tokens: Token[];
tagStatement: null | {
scanner: Scanner;
tag: RuntimeTag;
};
mustacheStatement: null | {
scanner: Scanner;
mustache: RuntimeMustache | RuntimeComment;
};
private line;
private isLastLineATag;
private dropNewLine;
private openedTags;
constructor(template: string, tagsDef: Tags, options: {
filename: string;
onLine?: (line: string) => string;
claimTag?: (name: string) => LexerTagDefinitionContract | null;
});
private getRawNode;
private getNewLineNode;
private getTagNode;
private consumeTag;
private handleTagOpening;
private feedCharsToCurrentTag;
private getMustacheType;
private getMustacheNode;
private getCommentNode;
private handleMustacheOpening;
private feedCharsToCurrentMustache;
private isClosingTag;
private consumeNode;
private pushNewLine;
private processText;
private checkForErrors;
parse(): void;
}
+267
View File
@@ -0,0 +1,267 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tokenizer = void 0;
const scanner_1 = require("./scanner");
const detector_1 = require("./detector");
const exceptions_1 = require("./exceptions");
const types_1 = require("./types");
class Tokenizer {
template;
tagsDef;
options;
tokens = [];
tagStatement = null;
mustacheStatement = null;
line = 0;
isLastLineATag = false;
dropNewLine = false;
openedTags = [];
constructor(template, tagsDef, options) {
this.template = template;
this.tagsDef = tagsDef;
this.options = options;
}
getRawNode(text) {
return {
type: 'raw',
value: text,
filename: this.options.filename,
line: this.line,
};
}
getNewLineNode(line) {
return {
type: 'newline',
filename: this.options.filename,
line: (line || this.line) - 1,
};
}
getTagNode(tag, jsArg, closingLoc) {
return {
type: tag.escaped ? types_1.TagTypes.ETAG : types_1.TagTypes.TAG,
filename: tag.filename,
properties: {
name: tag.name,
jsArg: jsArg,
selfclosed: tag.selfclosed,
},
loc: {
start: {
line: tag.line,
col: tag.col,
},
end: closingLoc,
},
children: [],
};
}
consumeTag(tag, jsArg, loc) {
if (tag.block && !tag.selfclosed) {
this.openedTags.push(this.getTagNode(tag, jsArg, loc));
}
else {
this.consumeNode(this.getTagNode(tag, jsArg, loc));
}
}
handleTagOpening(line, tag) {
if (tag.seekable && !tag.hasBrace) {
throw (0, exceptions_1.unopenedParen)({ line: tag.line, col: tag.col }, tag.filename);
}
if (!tag.seekable) {
this.consumeTag(tag, '', { line: tag.line, col: tag.col });
if (tag.noNewLine || line.endsWith('~')) {
this.dropNewLine = true;
}
return;
}
tag.col += 1;
this.tagStatement = {
tag: tag,
scanner: new scanner_1.Scanner(')', ['(', ')'], this.line, tag.col),
};
this.feedCharsToCurrentTag(line.slice(tag.col));
}
feedCharsToCurrentTag(content) {
const { tag, scanner } = this.tagStatement;
scanner.scan(content);
if (!scanner.closed) {
return;
}
this.consumeTag(tag, scanner.match, scanner.loc);
if (scanner.leftOver.trim() === '~') {
this.tagStatement = null;
this.dropNewLine = true;
return;
}
if (scanner.leftOver.trim()) {
throw (0, exceptions_1.cannotSeekStatement)(scanner.leftOver, scanner.loc, tag.filename);
}
if (tag.noNewLine) {
this.dropNewLine = true;
}
this.tagStatement = null;
}
getMustacheType(mustache) {
if (mustache.safe) {
return mustache.escaped ? types_1.MustacheTypes.ESMUSTACHE : types_1.MustacheTypes.SMUSTACHE;
}
return mustache.escaped ? types_1.MustacheTypes.EMUSTACHE : types_1.MustacheTypes.MUSTACHE;
}
getMustacheNode(mustache, jsArg, closingLoc) {
return {
type: this.getMustacheType(mustache),
filename: mustache.filename,
properties: {
jsArg: jsArg,
},
loc: {
start: {
line: mustache.line,
col: mustache.col,
},
end: closingLoc,
},
};
}
getCommentNode(comment, value, closingLoc) {
return {
type: 'comment',
filename: comment.filename,
value: value,
loc: {
start: {
line: comment.line,
col: comment.col,
},
end: closingLoc,
},
};
}
handleMustacheOpening(line, mustache) {
const pattern = mustache.isComment ? '--}}' : mustache.safe ? '}}}' : '}}';
const textLeftIndex = mustache.isComment || !mustache.escaped ? mustache.realCol : mustache.realCol - 1;
if (textLeftIndex > 0) {
this.consumeNode(this.getRawNode(line.slice(0, textLeftIndex)));
}
mustache.col += pattern.length;
mustache.realCol += pattern.length;
this.mustacheStatement = {
mustache,
scanner: new scanner_1.Scanner(pattern, ['{', '}'], mustache.line, mustache.col),
};
this.feedCharsToCurrentMustache(line.slice(mustache.realCol));
}
feedCharsToCurrentMustache(content) {
const { mustache, scanner } = this.mustacheStatement;
scanner.scan(content);
if (!scanner.closed) {
return;
}
if (mustache.isComment) {
this.consumeNode(this.getCommentNode(mustache, scanner.match, scanner.loc));
}
else {
this.consumeNode(this.getMustacheNode(mustache, scanner.match, scanner.loc));
}
if (scanner.leftOver.trim()) {
const anotherMustache = (0, detector_1.getMustache)(scanner.leftOver, this.options.filename, scanner.loc.line, scanner.loc.col);
if (anotherMustache) {
this.handleMustacheOpening(scanner.leftOver, anotherMustache);
return;
}
this.consumeNode(this.getRawNode(scanner.leftOver));
}
this.mustacheStatement = null;
}
isClosingTag(line) {
if (!this.openedTags.length) {
return false;
}
line = line.trim();
const recentTag = this.openedTags[this.openedTags.length - 1];
const endStatement = `@end${recentTag.properties.name}`;
return (line === endStatement || line === `${endStatement}~` || line === '@end' || line === '@end~');
}
consumeNode(tag) {
if (this.openedTags.length) {
this.openedTags[this.openedTags.length - 1].children.push(tag);
return;
}
this.tokens.push(tag);
}
pushNewLine(line) {
if ((line || this.line) === 1) {
return;
}
if (this.dropNewLine) {
this.dropNewLine = false;
return;
}
this.consumeNode(this.getNewLineNode(line));
}
processText(line) {
if (typeof this.options.onLine === 'function') {
line = this.options.onLine(line);
}
if (this.tagStatement) {
this.feedCharsToCurrentTag('\n');
this.feedCharsToCurrentTag(line);
return;
}
if (this.mustacheStatement) {
this.feedCharsToCurrentMustache('\n');
this.feedCharsToCurrentMustache(line);
return;
}
if (this.isClosingTag(line)) {
this.consumeNode(this.openedTags.pop());
if (line.endsWith('~')) {
this.dropNewLine = true;
}
return;
}
const tag = (0, detector_1.getTag)(line, this.options.filename, this.line, 0, this.tagsDef, this.options.claimTag);
if (tag) {
if (this.isLastLineATag) {
this.pushNewLine();
}
this.isLastLineATag = true;
this.handleTagOpening(line, tag);
return;
}
this.isLastLineATag = false;
const mustache = (0, detector_1.getMustache)(line, this.options.filename, this.line, 0);
if (mustache) {
this.pushNewLine();
this.handleMustacheOpening(line, mustache);
return;
}
this.pushNewLine();
this.consumeNode(this.getRawNode(line));
}
checkForErrors() {
if (this.tagStatement) {
const { tag } = this.tagStatement;
throw (0, exceptions_1.unclosedParen)({ line: tag.line, col: tag.col }, tag.filename);
}
if (this.mustacheStatement) {
const { mustache } = this.mustacheStatement;
throw (0, exceptions_1.unclosedCurlyBrace)({ line: mustache.line, col: mustache.col }, mustache.filename);
}
if (this.openedTags.length) {
const openedTag = this.openedTags[this.openedTags.length - 1];
throw (0, exceptions_1.unclosedTag)(openedTag.properties.name, openedTag.loc.start, openedTag.filename);
}
}
parse() {
const lines = this.template.split(/\r\n|\r|\n/g);
const linesLength = lines.length;
while (this.line < linesLength) {
const line = lines[this.line];
this.line++;
this.processText(line);
}
this.checkForErrors();
}
}
exports.Tokenizer = Tokenizer;
+92
View File
@@ -0,0 +1,92 @@
export declare enum MustacheTypes {
SMUSTACHE = "s__mustache",
ESMUSTACHE = "es__mustache",
MUSTACHE = "mustache",
EMUSTACHE = "e__mustache"
}
export declare enum TagTypes {
TAG = "tag",
ETAG = "e__tag"
}
export type TagProps = {
name: string;
jsArg: string;
selfclosed: boolean;
};
export type MustacheProps = {
jsArg: string;
};
export type LexerLoc = {
start: {
line: number;
col: number;
};
end: {
line: number;
col: number;
};
};
export interface LexerTagDefinitionContract {
block: boolean;
seekable: boolean;
noNewLine?: boolean;
}
export type RawToken = {
type: 'raw';
value: string;
line: number;
filename: string;
};
export type NewLineToken = {
type: 'newline';
line: number;
filename: string;
};
export type CommentToken = {
type: 'comment';
value: string;
loc: LexerLoc;
filename: string;
};
export type MustacheToken = {
type: MustacheTypes;
properties: MustacheProps;
loc: LexerLoc;
filename: string;
};
export type TagToken = {
type: TagTypes;
properties: TagProps;
loc: LexerLoc;
children: Token[];
filename: string;
};
export type Token = RawToken | NewLineToken | TagToken | MustacheToken | CommentToken;
export type RuntimeTag = LexerTagDefinitionContract & {
name: string;
filename: string;
selfclosed: boolean;
col: number;
line: number;
escaped: boolean;
hasBrace: boolean;
};
export type RuntimeMustache = {
isComment: false;
escaped: boolean;
filename: string;
safe: boolean;
line: number;
col: number;
realCol: number;
};
export type RuntimeComment = {
isComment: true;
filename: string;
line: number;
col: number;
realCol: number;
};
export interface Tags {
[name: string]: LexerTagDefinitionContract;
}
+15
View File
@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TagTypes = exports.MustacheTypes = void 0;
var MustacheTypes;
(function (MustacheTypes) {
MustacheTypes["SMUSTACHE"] = "s__mustache";
MustacheTypes["ESMUSTACHE"] = "es__mustache";
MustacheTypes["MUSTACHE"] = "mustache";
MustacheTypes["EMUSTACHE"] = "e__mustache";
})(MustacheTypes = exports.MustacheTypes || (exports.MustacheTypes = {}));
var TagTypes;
(function (TagTypes) {
TagTypes["TAG"] = "tag";
TagTypes["ETAG"] = "e__tag";
})(TagTypes = exports.TagTypes || (exports.TagTypes = {}));
+7
View File
@@ -0,0 +1,7 @@
import { Token, TagToken, MustacheToken } from './types';
export declare function isTag(token: Token, name?: string): token is TagToken;
export declare function isEscapedTag(token: Token, name?: string): token is TagToken;
export declare function isMustache(token: Token): token is MustacheToken;
export declare function isSafeMustache(token: Token): token is MustacheToken;
export declare function isEscapedMustache(token: Token): token is MustacheToken;
export declare function getLineAndColumn(token: Token): [number, number];
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLineAndColumn = exports.isEscapedMustache = exports.isSafeMustache = exports.isMustache = exports.isEscapedTag = exports.isTag = void 0;
const types_1 = require("./types");
function isTag(token, name) {
if (token.type === types_1.TagTypes.TAG || token.type === types_1.TagTypes.ETAG) {
return name ? token.properties.name === name : true;
}
return false;
}
exports.isTag = isTag;
function isEscapedTag(token, name) {
if (token.type === types_1.TagTypes.ETAG) {
return name ? token.properties.name === name : true;
}
return false;
}
exports.isEscapedTag = isEscapedTag;
function isMustache(token) {
return (token.type === types_1.MustacheTypes.EMUSTACHE ||
token.type === types_1.MustacheTypes.ESMUSTACHE ||
token.type === types_1.MustacheTypes.MUSTACHE ||
token.type === types_1.MustacheTypes.SMUSTACHE);
}
exports.isMustache = isMustache;
function isSafeMustache(token) {
return token.type === types_1.MustacheTypes.ESMUSTACHE || token.type === types_1.MustacheTypes.SMUSTACHE;
}
exports.isSafeMustache = isSafeMustache;
function isEscapedMustache(token) {
return token.type === types_1.MustacheTypes.EMUSTACHE || token.type === types_1.MustacheTypes.ESMUSTACHE;
}
exports.isEscapedMustache = isEscapedMustache;
function getLineAndColumn(token) {
if (token.type === 'newline' || token.type === 'raw') {
return [token.line, 0];
}
return [token.loc.start.line, token.loc.start.col];
}
exports.getLineAndColumn = getLineAndColumn;
+9
View File
@@ -0,0 +1,9 @@
# The MIT License
Copyright 2022 Harminder Virk, contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+40
View File
@@ -0,0 +1,40 @@
# edge-error
> Create errors with custom stack trace pointing to a ".edge" file
[![github-actions-image]][github-actions-url] [![npm-image]][npm-url] [![license-image]][license-url] [![typescript-image]][typescript-url]
The package extends the native Error class and adds support for pushing an error stack frame pointing to a ".edge" template file.
## Usage
Install the package from the npm packages registry.
```bash
npm i edge-error
# yarn
yarn add edge-error
```
Then use it as follows
```js
import { EdgeError } from 'edge-error'
throw new EdgeError('message', 'status', {
line: 1,
col: 2,
filename: 'absolute/path/to/index.edge'
})
```
[github-actions-image]: https://img.shields.io/github/workflow/status/edge-js/error/test?style=for-the-badge
[github-actions-url]: https://github.com/edge-js/error/actions/workflows/test.yml "github-actions"
[npm-image]: https://img.shields.io/npm/v/edge-error.svg?style=for-the-badge&logo=npm
[npm-url]: https://npmjs.org/package/edge-error "npm"
[license-image]: https://img.shields.io/npm/l/edge-error?color=blueviolet&style=for-the-badge
[license-url]: LICENSE.md "license"
[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
[typescript-url]: "typescript"
@@ -0,0 +1,9 @@
import { ExceptionOptions } from './types';
export declare class EdgeError extends Error {
message: string;
code: string;
line: number;
col: number;
filename: string;
constructor(message: string, code: string, options: ExceptionOptions);
}
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EdgeError = void 0;
class EdgeError extends Error {
message;
code;
line;
col;
filename;
constructor(message, code, options) {
super(message);
this.message = message;
this.code = code;
this.line = options.line;
this.col = options.col;
this.filename = options.filename;
const stack = this.stack.split('\n');
stack.splice(1, 0, ` at anonymous (${this.filename}:${this.line}:${this.col})`);
this.stack = stack.join('\n');
}
}
exports.EdgeError = EdgeError;
@@ -0,0 +1,5 @@
export declare type ExceptionOptions = {
line: number;
col: number;
filename: string;
};
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+107
View File
@@ -0,0 +1,107 @@
{
"name": "edge-error",
"version": "3.0.0",
"description": "Create errors with custom stack trace pointing to the .edge template file",
"main": "build/index.js",
"files": [
"build/index.d.ts",
"build/index.js",
"build/types.d.ts",
"build/types.js"
],
"exports": {
".": "./build/index.js",
"./types": "./build/types.js"
},
"scripts": {
"pretest": "npm run lint",
"test": "npm run vscode:test",
"vscode:test": "node --require=@adonisjs/require-ts/build/register bin/test.ts",
"clean": "del-cli build",
"compile": "npm run lint && npm run clean && tsc",
"build": "npm run compile",
"lint": "eslint . --ext=.ts",
"release": "np",
"version": "npm run build",
"sync-labels": "github-label-sync --labels .github/labels.js edge-js/error",
"format": "prettier --write .",
"prepublishOnly": "npm run build"
},
"keywords": [
"edge-error",
"edge.js"
],
"author": "virk",
"license": "MIT",
"devDependencies": {
"@adonisjs/require-ts": "^2.0.12",
"@commitlint/cli": "^17.1.2",
"@commitlint/config-conventional": "^17.1.0",
"@japa/assert": "^1.3.6",
"@japa/run-failed-tests": "^1.1.0",
"@japa/runner": "^2.2.1",
"@japa/spec-reporter": "^1.3.1",
"@types/node": "^18.7.18",
"del-cli": "^5.0.0",
"eslint": "^8.23.1",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-adonis": "^2.1.1",
"eslint-plugin-prettier": "^4.2.1",
"github-label-sync": "^2.2.0",
"husky": "^8.0.1",
"np": "^7.6.2",
"prettier": "^2.7.1",
"typescript": "^4.8.3"
},
"directories": {
"test": "test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/edge-js/edge-error.git"
},
"bugs": {
"url": "https://github.com/edge-js/edge-error/issues"
},
"homepage": "https://github.com/edge-js/edge-error#readme",
"np": {
"contents": ".",
"message": "chore(release): %s",
"anyBranch": false
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"eslintConfig": {
"extends": [
"plugin:adonis/typescriptPackage",
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
}
]
}
},
"eslintIgnore": [
"build"
],
"prettier": {
"trailingComma": "es5",
"semi": false,
"singleQuote": true,
"useTabs": false,
"quoteProps": "consistent",
"bracketSpacing": true,
"arrowParens": "always",
"printWidth": 100
}
}
+111
View File
@@ -0,0 +1,111 @@
{
"name": "edge-lexer",
"version": "5.0.2",
"description": "Edge parser to convert text markup to lexer tokens",
"main": "build/index.js",
"files": [
"build/src",
"build/index.d.ts",
"build/index.js"
],
"exports": {
".": "./build/index.js",
"./types": "./build/src/types.js",
"./utils": "./build/src/utils.js"
},
"scripts": {
"pretest": "npm run lint",
"test": "npm run vscode:test",
"vscode:test": "node --require=@adonisjs/require-ts/build/register bin/test.ts",
"build": "npm run compile",
"clean": "del-cli build",
"compile": "npm run lint && npm run clean && tsc",
"release": "np",
"version": "npm run build",
"prepublishOnly": "npm run build",
"lint": "eslint . --ext=.ts",
"sync-labels": "github-label-sync --labels .github/labels.json edge-js/lexer",
"format": "prettier --write ."
},
"keywords": [
"edge",
"template",
"template-engine"
],
"author": "virk",
"license": "MIT",
"devDependencies": {
"@adonisjs/require-ts": "^2.0.13",
"@commitlint/cli": "^17.4.4",
"@commitlint/config-conventional": "^17.4.4",
"@japa/assert": "^1.4.1",
"@japa/run-failed-tests": "^1.1.1",
"@japa/runner": "^2.5.1",
"@japa/spec-reporter": "^1.3.3",
"@types/dedent": "^0.7.0",
"@types/node": "^18.15.3",
"benchmark": "^2.1.4",
"dedent": "^0.7.0",
"del-cli": "^5.0.0",
"eslint": "^8.36.0",
"eslint-config-prettier": "^8.7.0",
"eslint-plugin-adonis": "^2.1.1",
"eslint-plugin-prettier": "^4.2.1",
"github-label-sync": "^2.3.1",
"husky": "^8.0.3",
"np": "^7.6.3",
"prettier": "^2.8.5",
"typescript": "^5.0.2"
},
"dependencies": {
"edge-error": "^3.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/edge-js/lexer.git"
},
"bugs": {
"url": "https://github.com/edge-js/lexer/issues"
},
"homepage": "https://github.com/edge-js/lexer#readme",
"np": {
"contents": ".",
"message": "chore(release): %s",
"anyBranch": false
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"eslintConfig": {
"extends": [
"plugin:adonis/typescriptPackage",
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
}
]
}
},
"eslintIgnore": [
"build"
],
"prettier": {
"trailingComma": "es5",
"semi": false,
"singleQuote": true,
"useTabs": false,
"quoteProps": "consistent",
"bracketSpacing": true,
"arrowParens": "always",
"printWidth": 100
}
}