UNPKG

@tbela99/css-parser

Version:

CSS parser, minifier and validator for node and the browser

103 lines (100 loc) 2.59 kB
import { encode } from './lib/encode.js'; /** * Source map class * @internal */ class SourceMap { /** * Last location */ lastLocation = null; /** * Version * @private */ #version = 3; /** * Sources * @private */ #sources = []; /** * Map * @private */ #map = new Map(); /** * Line * @private */ #line = -1; /** * Add a location * @param source * @param original */ add(source, original) { if (original.src !== "") { if (!this.#sources.includes(original.src)) { this.#sources.push(original.src); } const line = source.sta.lin - 1; let record; if (line > this.#line) { this.#line = line; } if (!this.#map.has(line)) { record = [ Math.max(0, source.sta.col - 1), this.#sources.indexOf(original.src), original.sta.lin - 1, original.sta.col - 1, ]; this.#map.set(line, [record]); } else { const arr = this.#map.get(line); record = [ Math.max(0, source.sta.col - 1 - arr[0][0]), this.#sources.indexOf(original.src) - arr[0][1], original.sta.lin - 1, original.sta.col - 1, ]; arr.push(record); } if (this.lastLocation != null) { record[2] -= this.lastLocation.sta.lin - 1; record[3] -= this.lastLocation.sta.col - 1; } this.lastLocation = original; } } /** * Convert to URL encoded string */ toUrl() { // /*# sourceMappingURL = ${url} */ return `data:application/json,${encodeURIComponent(JSON.stringify(this.toJSON()))}`; } /** * Convert to JSON object */ toJSON() { const mappings = []; let i = 0; for (; i <= this.#line; i++) { if (!this.#map.has(i)) { mappings.push(""); } else { mappings.push(this.#map.get(i).reduce((acc, curr) => acc + (acc === "" ? "" : ",") + encode(curr), "")); } } return { version: this.#version, sources: this.#sources.slice(), mappings: mappings.join(";"), }; } } export { SourceMap };