How to use parse5 - 10 common examples

To help you get started, we’ve selected a few parse5 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pluralsight-projects / Vue-BookListing / test / unit / mocha / part1 / book-list-will-contain-title-interpolation.spec.js View on Github external
it('should contain title interpolation in h1 @book-list-will-contain-title-interpolation', () => {
    let file;
    try {
      file = fs.readFileSync(path.join(process.cwd(), 'src/components/BookList.vue'), 'utf8');
    } catch (e) {
      assert(false, 'The BookList.vue file does not exist');
    }

    // Parse document
    const doc = parse5.parseFragment(file.replace(/\n/g, ''), { locationInfo: true });
    const nodes = doc.childNodes;

    // Parse for HTML in template
    const template = nodes.filter(node => node.nodeName === 'template');
    
    if (template.length == 0) {
      assert(false, "The BookList component does not contain a template tag")
    }
    
    const content = parse5.serialize(template[0].content);
    const dom = new JSDOM(content, { includeNodeLocations: true });
    const document = dom.window.document;

    // Test for booklist in the app div
    const results = document.querySelector('h1');
    assert(results != null, "The BookList template does not contain an h1 tag")
github pluralsight-projects / Vue-BookListing / test / unit / mocha / part1 / book-list-will-have-correct-styles.spec.js View on Github external
it('should contain correct styles @book-list-vue-will-have-correct-styles', () => {
    let file;
    try {
      file = fs.readFileSync(path.join(process.cwd(), 'src/components/BookList.vue'), 'utf8');
    } catch (e) {
      assert(false, 'The BookList.vue file does not exist');
    }

    // Parse document and retrieve the style section
    const doc = parse5.parseFragment(file.replace(/\n/g, ''), { locationInfo: true });
    const nodes = doc.childNodes;
    const styles = nodes.filter(node => node.nodeName === 'style');

    if (styles.length == 0) {
      assert(false, "The BookList.vue file does not contain a style element.")
    }
    if (styles[0].childNodes.length == 0) {
      assert(false, "The BookList style tag does not contain any CSS rules.")
    }
    
    const style = styles[0].childNodes[0].value;
    const parsed = cssom.parse(style);

    const results = parsed.cssRules.find(node => node.selectorText);

    assert(results.selectorText, 'The `"h1, h2"` selector is not present in BookList\'s styles');
github DefinitelyTyped / DefinitelyTyped / parse5 / parse5-tests.ts View on Github external
// Type definitions for parse5 2.1.5
// Project: https://github.com/inikulin/parse5
// Definitions by: Nico Jansen 
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/// 

import * as parse5 from 'parse5';

// parse5.SAXParser()
var parser = new parse5.SAXParser({ locationInfo: true });
parser.on('startTag', (name, attrs, selfClosing, location) => {
    console.log(name, attrs, selfClosing, location);
});
parser.on('text', (text, location)  => {
    console.log(text, location);
});

// parse5.parse()
parse5.parse('html', { locationInfo: true, treeAdapter: parse5.treeAdapters.default });
parse5.parse('html', {});
parse5.parse('html');

// parse5.ParserStream()
var parserStream = new parse5.ParserStream({ locationInfo: true, treeAdapter: parse5.treeAdapters.htmlparser2 });
parserStream = new parse5.ParserStream({ });
parserStream = new parse5.ParserStream();
github pluralsight-projects / Vue-BookListing / test / unit / mocha / part5 / book-form-contains-form-data.spec.js View on Github external
file = fs.readFileSync(path.join(process.cwd(), 'src/components/BookForm.vue'), 'utf8');
    } catch (e) {
      assert(false, 'The BookForm.vue file does not exist');
    }

    // Parse document
    const doc = parse5.parseFragment(file.replace(/\n/g, ''), { locationInfo: true });
    const nodes = doc.childNodes;

    // Parse for HTML in template
    const template = nodes.filter(node => node.nodeName === 'template');
    if (template.length == 0) {
      assert(false, "The BookForm component does not contain a template tag")
    }

    const content = parse5.serialize(template[0].content);
    const dom = new JSDOM(content, { includeNodeLocations: true, SVG_LCASE: true });
    const document = dom.window.document;

    // Test for for form existance
    const results = document.querySelector('form');
    if (results == null) {
      assert(false, "The BookForm template does not contain a `form` tag.")
    }
    assert(results.length > 0, 'The BookForm template does not contain a `form` tag');
  });
});
github DefinitelyTyped / DefinitelyTyped / types / parse5 / parse5-tests.ts View on Github external
scriptingEnabled: false,
    treeAdapter: defaultAdapter
};

parse5.parse("", opt); // $ExpectType Document

opt = {
    sourceCodeLocationInfo: true,
    scriptingEnabled: false,
    treeAdapter: defaultAdapter
};

parse5.parse("", opt); // $ExpectType Document

// parseFragment
const fragment = parse5.parseFragment("<div>");

fragment; // $ExpectType DocumentFragment

parse5.parseFragment("<div>", {});
parse5.parseFragment("<div>", { sourceCodeLocationInfo: true });
parse5.parseFragment("<div>", { treeAdapter: defaultAdapter });
parse5.parseFragment("<div>", {
    sourceCodeLocationInfo: true,
    treeAdapter: defaultAdapter
});
parse5.parseFragment("<div>", {
    sourceCodeLocationInfo: true,
    treeAdapter: defaultAdapter
});

const element = (parse5.parseFragment(</div></div></div></div></div></div>
github waterbearlang / waterbear / bin / refactorings / 02_drop_classes_for_ns.js View on Github external
var fs = require('fs')
var parse5 = require('parse5');
var parser = new parse5.Parser();

var filename = process.argv[2];
if (!filename){
    console.log('You must supply a filename');
    process.exit();
}
var origHtml = fs.readFileSync(filename, {encoding: 'utf-8'});
var document = parser.parseFragment(origHtml);

// Do the refactoring here
function walk(node, fn){
    fn(node);
    if (!node['childNodes']) return;
    node.childNodes.forEach(function(child){
        walk(child,fn);
    });
github waterbearlang / waterbear / bin / refactorings / 01_script_to_ns_fn.js View on Github external
// console.log(node.tagName);
    }
    if (!node['attrs']) return;
    node.attrs.forEach(function(attr){
        if (attr.name === 'script'){
            var script = attr.value;
            var nsFn = script.split('.');
            attr.name = 'ns'
            attr.value = nsFn[0];
            node.attrs.push({name: 'fn', value: nsFn[1]});
        }
    });
}
walk(document, hasScript);

var serializer = new parse5.Serializer();
var refactoredHtml = serializer.serialize(document);
fs.writeFileSync(filename, refactoredHtml);
github Polymer / tools / src / document-processor.ts View on Github external
}
      claimedDomModules.add(domModule);
      const template = dom5.query(domModule, (e) => e.tagName === 'template');
      if (template === null) {
        continue;
      }

      // It's ok to tag templates with the expression `Polymer.html` without
      // adding an import because `Polymer.html` is re-exported by both
      // polymer.html and polymer-element.html and, crucially, template
      // inlining happens before rewriting references.
      const templateLiteral = jsc.taggedTemplateExpression(
          jsc.memberExpression(
              jsc.identifier('Polymer'), jsc.identifier('html')),
          serializeNodeToTemplateLiteral(
              parse5.treeAdapters.default.getTemplateContent(template)));
      const nodePath = getNodePathInProgram(program, element.astNode);

      if (nodePath === undefined) {
        console.warn(
            new Warning({
              code: 'not-found',
              message: `Can't find recast node for element ${element.tagName}`,
              parsedDocument: this.document.parsedDocument,
              severity: Severity.WARNING,
              sourceRange: element.sourceRange!
            }).toString());
        continue;
      }

      const node = nodePath.node;
      if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
github Polymer / tools / packages / linter / src / polymer / elements / iron-flex-layout-classes.ts View on Github external
function searchUsedModulesAndIncludes(
    rootNode: dom5.Node,
    modules: Map = new Map(),
    includes: string[] =
        []): {modules: Map, includes: string[]} {
  for (const node of dom5.depthFirst(rootNode)) {
    if (!dom5.isElement(node)) {
      continue;
    }
    // Ensure we don't search into dom-module's templates.
    if (p.hasTagName('template')(node) &amp;&amp;
        !p.hasTagName('dom-module')(node.parentNode!)) {
      const templateContent = treeAdapters.default.getTemplateContent(node);
      searchUsedModulesAndIncludes(templateContent, modules, includes);
    } else if (isStyleInclude(node)) {
      dom5.getAttribute(node, 'include')!.split(' ').forEach((include) =&gt; {
        if (includes.indexOf(include) === -1) {
          includes.push(include);
        }
      });
    } else {
      styleModules.forEach((m) =&gt; {
        if (m.selector(node)) {
          if (!modules.has(m.module)) {
            modules.set(m.module, [node]);
          } else {
            modules.get(m.module)!.push(node);
          }
        }
github RubyLouvre / avalon / string-avalon.js View on Github external
var parse5 = require('parse5')
var parser = new parse5.Parser();
var serializer = new parse5.Serializer();
//https://github.com/exolution/xCube/blob/master/XParser.js
//Then feed it with an HTML document
//------------------------------------------
var expose = Date.now()
function log() {
    if (avalon.config.debug) {
// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
        console.log.apply(console, arguments)
    }
}
/**
 * Creates a new object without a prototype. This object is useful for lookup without having to
 * guard against prototypically inherited properties via hasOwnProperty.
 *
 * Related micro-benchmarks:
 * - http://jsperf.com/object-create2