all files / src/ SimpleAnalyzer.ts

91.67% Statements 22/24
50% Branches 4/8
100% Functions 3/3
91.67% Lines 22/24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                         10× 10× 10× 10×         10×                
import * as parse5 from "parse5";
import { Tagname, Attribute, AttributeValue, AttributeNS, TemplateAnalysis, POSITION_UNKNOWN  } from "@opticss/template-api";
import { AttributeValueParser } from "./AttributeValueParser";
import { TestTemplate } from "./TestTemplate";
 
export interface HasAnalysisId {
  analysisId: string;
}
 
export class SimpleAnalyzer {
  template: TestTemplate;
  includeSourceInformation: boolean;
  valueParser: AttributeValueParser;
  /**
   * Creates an instance of SimpleAnalyzer.
   * @param template The template to be analyzed.
   * @param [includeSourceInformation=false] Whether to record source positions
   *   for elements in the analysis.
   */
  constructor(template: TestTemplate, includeSourceInformation = false) {
    this.template = template;
    this.includeSourceInformation = includeSourceInformation;
    this.valueParser = new AttributeValueParser(template.plainHtml);
  }
  private attrValue(attrNamespace: string | null | undefined, attrName: string, valueStr: string): AttributeValue {
    return this.valueParser.parse(attrNamespace, attrName, valueStr);
  }
  analyze(): Promise<TemplateAnalysis<"TestTemplate">> {
    let analysis = new TemplateAnalysis<"TestTemplate">(this.template);
    const parser = new parse5.SAXParser({ locationInfo: this.includeSourceInformation });
    parser.on("startTag", (name, attrs, _selfClosing, location) => {
      let startLocation = location ? {line: location.line, column: location.col} : POSITION_UNKNOWN;
      let endLocation = location ? {line: location.line, column: location.col + location.endOffset} : POSITION_UNKNOWN;
      analysis.startElement(new Tagname({constant: name}), startLocation);
      attrs.forEach(attr => {
        Iif (attr.namespace) {
          analysis.addAttribute(new AttributeNS(attr.namespace, attr.name, this.attrValue(attr.namespace, attr.name, attr.value)));
        } else {
          analysis.addAttribute(new Attribute(attr.name, this.attrValue(attr.namespace, attr.name, attr.value)));
        }
      });
      analysis.endElement(endLocation);
    });
    return new Promise((resolve, reject) => {
      parser.write(this.template.contents, (err: any) => {
        Iif (err) {
          reject(err);
        } else {
          resolve(analysis);
        }
      });
    });
  }
}