npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

stillat-blade-parser

v2.0.1

Published

Parses Laravel Blade template files, and provides static analysis features.

Downloads

585

Readme

Blade Parser

This library provides a Laravel Blade parser written in TypeScript. In addition to being able to parse Blade template files, this library also provides utilities and libraries that make it simpler to perform static analysis on Blade documents.

What this project is:

  • A standalone Blade parser written in TypeScript/JavaScript
  • A standalone Blade compiler written in TypeScript/JavaScript
  • A Blade static analysis library
  • A Blade error/diagnostics library
  • An advanced Blade document transformation library
  • A Blade Formatter for Prettier (more info here)

What this project is not:

  • A view engine. It will not be able to actually render your Blade templates

Installing

This package can be installed in your project using the following command:

npm install --save stillat-blade-parser

Basic Usage

The simplest way to get started using this library is to use the BladeDocument.fromText static helper method:

import { BladeDocument } from "stillat-blade-parser/out/document/bladeDocument";

const document = BladeDocument.fromText(`<html>
    <head>
        <title>{{ $title }}</title>
    </head>
</html>`);

This method will return an instance of BladeDocument, which provides many useful features and helpers.

As an example, we can ask the document for a list of all parsed nodes and do something special with any directives we find:

import { BladeDocument } from "stillat-blade-parser/out/document/bladeDocument";
import { DirectiveNode } from 'stillat-blade-parser/out/nodes/nodes';

const document = BladeDocument.fromText(`<html>
    <head>
        <title>{{ $title }}</title>
    </head>
</html>`);

document.getAllNodes().forEach((node) => {
    if (node instanceof DirectiveNode) {
        console.log(node.directiveName);
    }
});

Parsing Options

The Blade parser can be configured with a few options to help guide the parser. These configurable options are:

  • customIfs: A list of custom if directives
  • directives: A list of directives that can be parsed
  • ignoreDirectives: A list of directive names that should be ignored

All provided option values are case-insensitive. Do not include the @ when supplying directive names to the directives or ignoreDirectives lists.

Supplying Options to the Parser

To supply parser options, you must have an instance of BladeDocument before you parse the template contents. Each BladeDocument also contains a parser instance. We can use the getParser() method to retrieve the internal parser instance, which will allow us to set our options:

import { BladeDocument } from "stillat-blade-parser/out/document/bladeDocument";
import { ParserOptions } from 'stillat-blade-parser/out/parser/parserOptions';

const document = new BladeDocument(),
    options:ParserOptions = {
        customIfs: [],
        directives: [],
        ignoreDirectives: []
    };

// Set the parser options.
document.getParser().withParserOptions(options);

document.loadString(`Template content`);

The directives and ignoreDirectives Options

The directives and ignoreDirectives options are mutually exclusive, and only one will be used at a time. If values are provided for the directives configuration option, it will take precedence over the ignoreDirectives option.

The ignoreDirectives option is the default configuration setup, and allows developers to supply a list of directive names that should not be parsed. Because this parser library does not have any runtime access to your project's specific directives, it will attempt to parse everything that could be a valid directive.

By default, the ignoreDirectives option is set to the following:

const options:ParserOptions = {
    customIfs: [],
    directives: [],
    ignoreDirectives: [
        'media',
        'charset',
        'import',
        'namespace',
        'supports',
        'document',
        'page',
        'font-face',
        'keyframes',
        'viewport',
        'counter-style',
        'font-feature-values',
        'swash',
        'ornaments',
        'annotation',
        'stylistic',
        'styleset',
        'character-variant',
        'font-variant-alternates',
        'property',
        'color-profile',
        'click',
        'submit', 
        'scroll',
        'keydown',
        'keypress',
        'keyup',
        'blur', 
        'change',
        'contextmenu',
        'copy',
        'cut',
        'paste',
        'dblclick',
        'drag',
        'dragend',
        'dragenter',
        'dragleave',
        'dragover',
        'dragstart',
        'drop',
        'focus',
        'focusin',
        'focusout',
        'input',
        'mousedown',
        'mouseenter',
        'mouseleave',
        'mousemove',
        'mouseover',
        'mouseout',
        'mouseup',
        'mousewheel',
        'resize',
        'select',
        'touchcancel',
        'touchend',
        'touchmove',
        'touchstart',
        'wheel'
    ]
};

Whenever a potential directive is encountered and is present in the ignoreDirectives list, that section of the template is skipped over and that potential directive becomes part of the document's literal text.

In contrast, the directives configuration option can be used to supply a list of directive names that can be parsed. If a potential directive is encountered that is not in this list, that potential directive is skipped and becomes part of the document's literal text.

The customIfs Configuration Option

The customIfs configuration option is the parser's counterpart to Laravel's Custom If Statements feature. An important thing to note is this configuration option simply hints to the parser what will become an if statement internally.

This option can be set like so:

const options:ParserOptions = {
    customIfs: [
        'disk',
    ],
    directives: [],
    ignoreDirectives: []
};

In most situations you do not need to supply any value for this configuration option. The parser is capable of analyzing your Blade templates and detecting custom if statements automatically.

Formatting Conditional Element Open/Close Tags

Because of the formatter works internally, you will need to take a few steps if you need to format templates containing Blade code similar to the following:

@if ($someCondition)
    <x-slot:the_slot>
@endif

    <!-- More content here. -->

@if ($someCondition)
    </x-slot>
@endif

The above template will result in a Prettier error stating it encountered an unexpected closing tag. This can be resolved by wrapping the fragmented open/close tags with ignore comments:

@if ($someCondition)
    {{-- format-ignore-start --}}<x-slot:the_slot>{{-- format-ignore-end --}}
@endif

    <!-- More content here. -->

@if ($someCondition)
    {{-- format-ignore-start --}}</x-slot>{{-- format-ignore-end --}}
@endif

Reporting Issues

Please use the issues feature on GitHub to report bugs/issues. For general questions on how to use this library, please use the Discussions feature. Be considerate when interacting with others :)

Due to the complexity and scope of this project, when reporting bugs/issues please include all required information to reproduce the bug or issue. You are encouraged to attach any problematic templates to the issue as a file in addition to being included in the issue description (this helps to eliminate any formatting/adjustments that the GitHub UI may apply).

https://github.com/stillat/blade-parser-typescript

Contributing Changes

Thank you for considering contributing changes to this project!

Building from Source

To build this project from source, issue the following commands:

npm install
npm run compile

If you introduce changes that break existing tests with un-important whitespace changes, it is fine to simply update those tests to account for the new whitespace changes. An example of these types of changes would be the transformer_ tests. Breaking whitespace inside literal/node content (unless its a bug fix) is not acceptable, however.

Running the Tests

Before opening a pull request, do try and ensure that new features/changes have corresponding tests created. In addition, make sure to correct any failing tests.

To run the test suite issue the following command:

npm run test:parser

Debugging the Parser Library

The easiest method to debug the parser library is to use VS Code and select the Blade Parser Run and Debug configuration. This debug configuration will launch the /out/parser.ts file in debug mode, allowing you to run and debug code from within that file right within VS Code.

License

This library is open-sourced software licensed under the MIT license.

If you find this project useful, or are using it in a commercial setting, please consider funding the project to ensure it's continued development.