UNPKG

@scriptables/manifest

Version:

Utilities to generate, parse, and update manifest headers in Scriptable scripts.

60 lines (59 loc) 2.23 kB
import { SCRIPT_HEADER_NOTICES } from "./scriptHeaderNotices.js"; function parse(script, headerParserOrOptions, options = {}) { if (script.length < 2 || script.charCodeAt(0) !== 47 || script.charCodeAt(1) !== 47) { return { header: null, headerContent: "", content: script || "" }; } const opts = { maxHeaderLines: 20, headerNotices: SCRIPT_HEADER_NOTICES, excludeNotices: false, ...typeof headerParserOrOptions === "function" ? options : headerParserOrOptions }; const lines = new Array(); let pos = 0; let noticeIdx = 0; let hasValidHeader = !opts.headerNotices.length; const maxPos = script.length; const maxLines = opts.maxHeaderLines; let lineStart = 0; let lineCount = 0; let headerEndPos = 0; while (lineCount < maxLines && pos < maxPos) { while (pos < maxPos && script.charCodeAt(pos) !== 10) pos++; const line = script.slice(lineStart, pos).trim(); if (!line.startsWith("//")) { headerEndPos = lineStart; break; } if (opts.headerNotices.length > 0 && noticeIdx < opts.headerNotices.length && line.includes(opts.headerNotices[noticeIdx])) { if (++noticeIdx === opts.headerNotices.length) hasValidHeader = true; } if (!opts.headerNotices.length || hasValidHeader || noticeIdx > 0) { lines.push(line); } lineCount++; pos++; lineStart = pos; } if (opts.headerNotices.length && !hasValidHeader) { return { header: null, headerContent: "", content: script }; } if (!headerEndPos) { headerEndPos = pos; } const result = { header: null, headerContent: lines.join("\n"), content: script.slice(headerEndPos).replace(/^\n+/, "") }; if (typeof headerParserOrOptions === "function" && lines.length) { const headerLines = opts.excludeNotices && opts.headerNotices.length ? lines.slice(opts.headerNotices.length) : lines; result.header = headerParserOrOptions(headerLines); } return result; } export { parse }; //# sourceMappingURL=parse.js.map //# sourceMappingURL=parse.js.map