Files
jpmschweitzerandClaude Opus 4.7 a86b84ef61 add gitignore and commit Obsidian vault config
Exclude .env (a GOOGLE_CLOUD_PROJECT value was present at the repo root),
.claude/settings.local.json, OS cruft, and personal Obsidian workspace
state (workspace.json, workspace-mobile.json, cache). Commit the rest of
.obsidian/ so the vault reopens with the same plugins, graph settings,
and daily-notes config on any machine.

Also expand Obsidian's userIgnoreFilters so .claude, .env, and .gitignore
don't pollute the file explorer, search, or graph view.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 15:25:42 +02:00

7209 lines
239 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key2 of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key2) && key2 !== except)
__defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// node_modules/hogan.js/lib/compiler.js
var require_compiler = __commonJS({
"node_modules/hogan.js/lib/compiler.js"(exports) {
(function(Hogan4) {
var rIsWhitespace = /\S/, rQuot = /\"/g, rNewline = /\n/g, rCr = /\r/g, rSlash = /\\/g, rLineSep = /\u2028/, rParagraphSep = /\u2029/;
Hogan4.tags = {
"#": 1,
"^": 2,
"<": 3,
"$": 4,
"/": 5,
"!": 6,
">": 7,
"=": 8,
"_v": 9,
"{": 10,
"&": 11,
"_t": 12
};
Hogan4.scan = function scan(text, delimiters) {
var len = text.length, IN_TEXT = 0, IN_TAG_TYPE = 1, IN_TAG = 2, state = IN_TEXT, tagType = null, tag = null, buf = "", tokens = [], seenTag = false, i = 0, lineStart = 0, otag = "{{", ctag = "}}";
function addBuf() {
if (buf.length > 0) {
tokens.push({ tag: "_t", text: new String(buf) });
buf = "";
}
}
function lineIsWhitespace() {
var isAllWhitespace = true;
for (var j = lineStart; j < tokens.length; j++) {
isAllWhitespace = Hogan4.tags[tokens[j].tag] < Hogan4.tags["_v"] || tokens[j].tag == "_t" && tokens[j].text.match(rIsWhitespace) === null;
if (!isAllWhitespace) {
return false;
}
}
return isAllWhitespace;
}
function filterLine(haveSeenTag, noNewLine) {
addBuf();
if (haveSeenTag && lineIsWhitespace()) {
for (var j = lineStart, next; j < tokens.length; j++) {
if (tokens[j].text) {
if ((next = tokens[j + 1]) && next.tag == ">") {
next.indent = tokens[j].text.toString();
}
tokens.splice(j, 1);
}
}
} else if (!noNewLine) {
tokens.push({ tag: "\n" });
}
seenTag = false;
lineStart = tokens.length;
}
function changeDelimiters(text2, index) {
var close = "=" + ctag, closeIndex = text2.indexOf(close, index), delimiters2 = trim(
text2.substring(text2.indexOf("=", index) + 1, closeIndex)
).split(" ");
otag = delimiters2[0];
ctag = delimiters2[delimiters2.length - 1];
return closeIndex + close.length - 1;
}
if (delimiters) {
delimiters = delimiters.split(" ");
otag = delimiters[0];
ctag = delimiters[1];
}
for (i = 0; i < len; i++) {
if (state == IN_TEXT) {
if (tagChange(otag, text, i)) {
--i;
addBuf();
state = IN_TAG_TYPE;
} else {
if (text.charAt(i) == "\n") {
filterLine(seenTag);
} else {
buf += text.charAt(i);
}
}
} else if (state == IN_TAG_TYPE) {
i += otag.length - 1;
tag = Hogan4.tags[text.charAt(i + 1)];
tagType = tag ? text.charAt(i + 1) : "_v";
if (tagType == "=") {
i = changeDelimiters(text, i);
state = IN_TEXT;
} else {
if (tag) {
i++;
}
state = IN_TAG;
}
seenTag = i;
} else {
if (tagChange(ctag, text, i)) {
tokens.push({
tag: tagType,
n: trim(buf),
otag,
ctag,
i: tagType == "/" ? seenTag - otag.length : i + ctag.length
});
buf = "";
i += ctag.length - 1;
state = IN_TEXT;
if (tagType == "{") {
if (ctag == "}}") {
i++;
} else {
cleanTripleStache(tokens[tokens.length - 1]);
}
}
} else {
buf += text.charAt(i);
}
}
}
filterLine(seenTag, true);
return tokens;
};
function cleanTripleStache(token) {
if (token.n.substr(token.n.length - 1) === "}") {
token.n = token.n.substring(0, token.n.length - 1);
}
}
function trim(s) {
if (s.trim) {
return s.trim();
}
return s.replace(/^\s*|\s*$/g, "");
}
function tagChange(tag, text, index) {
if (text.charAt(index) != tag.charAt(0)) {
return false;
}
for (var i = 1, l = tag.length; i < l; i++) {
if (text.charAt(index + i) != tag.charAt(i)) {
return false;
}
}
return true;
}
var allowedInSuper = { "_t": true, "\n": true, "$": true, "/": true };
function buildTree(tokens, kind, stack, customTags) {
var instructions = [], opener = null, tail = null, token = null;
tail = stack[stack.length - 1];
while (tokens.length > 0) {
token = tokens.shift();
if (tail && tail.tag == "<" && !(token.tag in allowedInSuper)) {
throw new Error("Illegal content in < super tag.");
}
if (Hogan4.tags[token.tag] <= Hogan4.tags["$"] || isOpener(token, customTags)) {
stack.push(token);
token.nodes = buildTree(tokens, token.tag, stack, customTags);
} else if (token.tag == "/") {
if (stack.length === 0) {
throw new Error("Closing tag without opener: /" + token.n);
}
opener = stack.pop();
if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) {
throw new Error("Nesting error: " + opener.n + " vs. " + token.n);
}
opener.end = token.i;
return instructions;
} else if (token.tag == "\n") {
token.last = tokens.length == 0 || tokens[0].tag == "\n";
}
instructions.push(token);
}
if (stack.length > 0) {
throw new Error("missing closing tag: " + stack.pop().n);
}
return instructions;
}
function isOpener(token, tags) {
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].o == token.n) {
token.tag = "#";
return true;
}
}
}
function isCloser(close, open, tags) {
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].c == close && tags[i].o == open) {
return true;
}
}
}
function stringifySubstitutions(obj) {
var items = [];
for (var key2 in obj) {
items.push('"' + esc(key2) + '": function(c,p,t,i) {' + obj[key2] + "}");
}
return "{ " + items.join(",") + " }";
}
function stringifyPartials(codeObj) {
var partials = [];
for (var key2 in codeObj.partials) {
partials.push('"' + esc(key2) + '":{name:"' + esc(codeObj.partials[key2].name) + '", ' + stringifyPartials(codeObj.partials[key2]) + "}");
}
return "partials: {" + partials.join(",") + "}, subs: " + stringifySubstitutions(codeObj.subs);
}
Hogan4.stringify = function(codeObj, text, options) {
return "{code: function (c,p,i) { " + Hogan4.wrapMain(codeObj.code) + " }," + stringifyPartials(codeObj) + "}";
};
var serialNo = 0;
Hogan4.generate = function(tree, text, options) {
serialNo = 0;
var context = { code: "", subs: {}, partials: {} };
Hogan4.walk(tree, context);
if (options.asString) {
return this.stringify(context, text, options);
}
return this.makeTemplate(context, text, options);
};
Hogan4.wrapMain = function(code) {
return 'var t=this;t.b(i=i||"");' + code + "return t.fl();";
};
Hogan4.template = Hogan4.Template;
Hogan4.makeTemplate = function(codeObj, text, options) {
var template = this.makePartials(codeObj);
template.code = new Function("c", "p", "i", this.wrapMain(codeObj.code));
return new this.template(template, text, this, options);
};
Hogan4.makePartials = function(codeObj) {
var key2, template = { subs: {}, partials: codeObj.partials, name: codeObj.name };
for (key2 in template.partials) {
template.partials[key2] = this.makePartials(template.partials[key2]);
}
for (key2 in codeObj.subs) {
template.subs[key2] = new Function("c", "p", "t", "i", codeObj.subs[key2]);
}
return template;
};
function esc(s) {
return s.replace(rSlash, "\\\\").replace(rQuot, '\\"').replace(rNewline, "\\n").replace(rCr, "\\r").replace(rLineSep, "\\u2028").replace(rParagraphSep, "\\u2029");
}
function chooseMethod(s) {
return ~s.indexOf(".") ? "d" : "f";
}
function createPartial(node, context) {
var prefix = "<" + (context.prefix || "");
var sym = prefix + node.n + serialNo++;
context.partials[sym] = { name: node.n, partials: {} };
context.code += 't.b(t.rp("' + esc(sym) + '",c,p,"' + (node.indent || "") + '"));';
return sym;
}
Hogan4.codegen = {
"#": function(node, context) {
context.code += "if(t.s(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,1),c,p,0,' + node.i + "," + node.end + ',"' + node.otag + " " + node.ctag + '")){t.rs(c,p,function(c,p,t){';
Hogan4.walk(node.nodes, context);
context.code += "});c.pop();}";
},
"^": function(node, context) {
context.code += "if(!t.s(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,1),c,p,1,0,0,"")){';
Hogan4.walk(node.nodes, context);
context.code += "};";
},
">": createPartial,
"<": function(node, context) {
var ctx = { partials: {}, code: "", subs: {}, inPartial: true };
Hogan4.walk(node.nodes, ctx);
var template = context.partials[createPartial(node, context)];
template.subs = ctx.subs;
template.partials = ctx.partials;
},
"$": function(node, context) {
var ctx = { subs: {}, code: "", partials: context.partials, prefix: node.n };
Hogan4.walk(node.nodes, ctx);
context.subs[node.n] = ctx.code;
if (!context.inPartial) {
context.code += 't.sub("' + esc(node.n) + '",c,p,i);';
}
},
"\n": function(node, context) {
context.code += write('"\\n"' + (node.last ? "" : " + i"));
},
"_v": function(node, context) {
context.code += "t.b(t.v(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,0)));';
},
"_t": function(node, context) {
context.code += write('"' + esc(node.text) + '"');
},
"{": tripleStache,
"&": tripleStache
};
function tripleStache(node, context) {
context.code += "t.b(t.t(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,0)));';
}
function write(s) {
return "t.b(" + s + ");";
}
Hogan4.walk = function(nodelist, context) {
var func;
for (var i = 0, l = nodelist.length; i < l; i++) {
func = Hogan4.codegen[nodelist[i].tag];
func && func(nodelist[i], context);
}
return context;
};
Hogan4.parse = function(tokens, text, options) {
options = options || {};
return buildTree(tokens, "", [], options.sectionTags || []);
};
Hogan4.cache = {};
Hogan4.cacheKey = function(text, options) {
return [text, !!options.asString, !!options.disableLambda, options.delimiters, !!options.modelGet].join("||");
};
Hogan4.compile = function(text, options) {
options = options || {};
var key2 = Hogan4.cacheKey(text, options);
var template = this.cache[key2];
if (template) {
var partials = template.partials;
for (var name in partials) {
delete partials[name].instance;
}
return template;
}
template = this.generate(this.parse(this.scan(text, options.delimiters), text, options), text, options);
return this.cache[key2] = template;
};
})(typeof exports !== "undefined" ? exports : Hogan);
}
});
// node_modules/hogan.js/lib/template.js
var require_template = __commonJS({
"node_modules/hogan.js/lib/template.js"(exports) {
var Hogan4 = {};
(function(Hogan5) {
Hogan5.Template = function(codeObj, text, compiler, options) {
codeObj = codeObj || {};
this.r = codeObj.code || this.r;
this.c = compiler;
this.options = options || {};
this.text = text || "";
this.partials = codeObj.partials || {};
this.subs = codeObj.subs || {};
this.buf = "";
};
Hogan5.Template.prototype = {
// render: replaced by generated code.
r: function(context, partials, indent) {
return "";
},
// variable escaping
v: hoganEscape,
// triple stache
t: coerceToString,
render: function render2(context, partials, indent) {
return this.ri([context], partials || {}, indent);
},
// render internal -- a hook for overrides that catches partials too
ri: function(context, partials, indent) {
return this.r(context, partials, indent);
},
// ensurePartial
ep: function(symbol, partials) {
var partial = this.partials[symbol];
var template = partials[partial.name];
if (partial.instance && partial.base == template) {
return partial.instance;
}
if (typeof template == "string") {
if (!this.c) {
throw new Error("No compiler available.");
}
template = this.c.compile(template, this.options);
}
if (!template) {
return null;
}
this.partials[symbol].base = template;
if (partial.subs) {
if (!partials.stackText)
partials.stackText = {};
for (key in partial.subs) {
if (!partials.stackText[key]) {
partials.stackText[key] = this.activeSub !== void 0 && partials.stackText[this.activeSub] ? partials.stackText[this.activeSub] : this.text;
}
}
template = createSpecializedPartial(
template,
partial.subs,
partial.partials,
this.stackSubs,
this.stackPartials,
partials.stackText
);
}
this.partials[symbol].instance = template;
return template;
},
// tries to find a partial in the current scope and render it
rp: function(symbol, context, partials, indent) {
var partial = this.ep(symbol, partials);
if (!partial) {
return "";
}
return partial.ri(context, partials, indent);
},
// render a section
rs: function(context, partials, section) {
var tail = context[context.length - 1];
if (!isArray(tail)) {
section(context, partials, this);
return;
}
for (var i = 0; i < tail.length; i++) {
context.push(tail[i]);
section(context, partials, this);
context.pop();
}
},
// maybe start a section
s: function(val, ctx, partials, inverted, start, end, tags) {
var pass;
if (isArray(val) && val.length === 0) {
return false;
}
if (typeof val == "function") {
val = this.ms(val, ctx, partials, inverted, start, end, tags);
}
pass = !!val;
if (!inverted && pass && ctx) {
ctx.push(typeof val == "object" ? val : ctx[ctx.length - 1]);
}
return pass;
},
// find values with dotted names
d: function(key2, ctx, partials, returnFound) {
var found, names = key2.split("."), val = this.f(names[0], ctx, partials, returnFound), doModelGet = this.options.modelGet, cx = null;
if (key2 === "." && isArray(ctx[ctx.length - 2])) {
val = ctx[ctx.length - 1];
} else {
for (var i = 1; i < names.length; i++) {
found = findInScope(names[i], val, doModelGet);
if (found !== void 0) {
cx = val;
val = found;
} else {
val = "";
}
}
}
if (returnFound && !val) {
return false;
}
if (!returnFound && typeof val == "function") {
ctx.push(cx);
val = this.mv(val, ctx, partials);
ctx.pop();
}
return val;
},
// find values with normal names
f: function(key2, ctx, partials, returnFound) {
var val = false, v = null, found = false, doModelGet = this.options.modelGet;
for (var i = ctx.length - 1; i >= 0; i--) {
v = ctx[i];
val = findInScope(key2, v, doModelGet);
if (val !== void 0) {
found = true;
break;
}
}
if (!found) {
return returnFound ? false : "";
}
if (!returnFound && typeof val == "function") {
val = this.mv(val, ctx, partials);
}
return val;
},
// higher order templates
ls: function(func, cx, partials, text, tags) {
var oldTags = this.options.delimiters;
this.options.delimiters = tags;
this.b(this.ct(coerceToString(func.call(cx, text)), cx, partials));
this.options.delimiters = oldTags;
return false;
},
// compile text
ct: function(text, cx, partials) {
if (this.options.disableLambda) {
throw new Error("Lambda features disabled.");
}
return this.c.compile(text, this.options).render(cx, partials);
},
// template result buffering
b: function(s) {
this.buf += s;
},
fl: function() {
var r = this.buf;
this.buf = "";
return r;
},
// method replace section
ms: function(func, ctx, partials, inverted, start, end, tags) {
var textSource, cx = ctx[ctx.length - 1], result = func.call(cx);
if (typeof result == "function") {
if (inverted) {
return true;
} else {
textSource = this.activeSub && this.subsText && this.subsText[this.activeSub] ? this.subsText[this.activeSub] : this.text;
return this.ls(result, cx, partials, textSource.substring(start, end), tags);
}
}
return result;
},
// method replace variable
mv: function(func, ctx, partials) {
var cx = ctx[ctx.length - 1];
var result = func.call(cx);
if (typeof result == "function") {
return this.ct(coerceToString(result.call(cx)), cx, partials);
}
return result;
},
sub: function(name, context, partials, indent) {
var f = this.subs[name];
if (f) {
this.activeSub = name;
f(context, partials, this, indent);
this.activeSub = false;
}
}
};
function findInScope(key2, scope, doModelGet) {
var val;
if (scope && typeof scope == "object") {
if (scope[key2] !== void 0) {
val = scope[key2];
} else if (doModelGet && scope.get && typeof scope.get == "function") {
val = scope.get(key2);
}
}
return val;
}
function createSpecializedPartial(instance, subs, partials, stackSubs, stackPartials, stackText) {
function PartialTemplate() {
}
;
PartialTemplate.prototype = instance;
function Substitutions() {
}
;
Substitutions.prototype = instance.subs;
var key2;
var partial = new PartialTemplate();
partial.subs = new Substitutions();
partial.subsText = {};
partial.buf = "";
stackSubs = stackSubs || {};
partial.stackSubs = stackSubs;
partial.subsText = stackText;
for (key2 in subs) {
if (!stackSubs[key2])
stackSubs[key2] = subs[key2];
}
for (key2 in stackSubs) {
partial.subs[key2] = stackSubs[key2];
}
stackPartials = stackPartials || {};
partial.stackPartials = stackPartials;
for (key2 in partials) {
if (!stackPartials[key2])
stackPartials[key2] = partials[key2];
}
for (key2 in stackPartials) {
partial.partials[key2] = stackPartials[key2];
}
return partial;
}
var rAmp = /&/g, rLt = /</g, rGt = />/g, rApos = /\'/g, rQuot = /\"/g, hChars = /[&<>\"\']/;
function coerceToString(val) {
return String(val === null || val === void 0 ? "" : val);
}
function hoganEscape(str) {
str = coerceToString(str);
return hChars.test(str) ? str.replace(rAmp, "&amp;").replace(rLt, "&lt;").replace(rGt, "&gt;").replace(rApos, "&#39;").replace(rQuot, "&quot;") : str;
}
var isArray = Array.isArray || function(a) {
return Object.prototype.toString.call(a) === "[object Array]";
};
})(typeof exports !== "undefined" ? exports : Hogan4);
}
});
// node_modules/hogan.js/lib/hogan.js
var require_hogan = __commonJS({
"node_modules/hogan.js/lib/hogan.js"(exports, module2) {
var Hogan4 = require_compiler();
Hogan4.Template = require_template().Template;
Hogan4.template = Hogan4.Template;
module2.exports = Hogan4;
}
});
// node_modules/typed-assert/build/index.js
var require_build = __commonJS({
"node_modules/typed-assert/build/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.check = exports.isPromise = exports.isInstanceOf = exports.isOneOfType = exports.isOneOf = exports.isOptionOfType = exports.isArrayOfType = exports.isRecordOfType = exports.isArray = exports.isRecordWithKeys = exports.isRecord = exports.isDate = exports.isString = exports.isNumber = exports.isBoolean = exports.isExactly = exports.isNotVoid = exports.isNotUndefined = exports.isNotNull = exports.isNever = exports.isUnknown = exports.safeJsonParse = exports.setBaseAssert = exports.assert = exports.defaultAssert = void 0;
var expectedToBe = (type) => `expected to be ${type}`;
var defaultAssert = (condition, message) => {
if (!condition) {
throw new TypeError(message);
}
};
exports.defaultAssert = defaultAssert;
var baseAssert = exports.defaultAssert;
var assert = (condition, message) => baseAssert(condition, message);
exports.assert = assert;
function setBaseAssert(assert2) {
if (assert2) {
baseAssert = assert2;
}
}
exports.setBaseAssert = setBaseAssert;
var safeJsonParse = (json) => JSON.parse(json);
exports.safeJsonParse = safeJsonParse;
function isUnknown(_input) {
return true;
}
exports.isUnknown = isUnknown;
function isNever(_input, message = expectedToBe("unreachable")) {
throw new TypeError(message);
}
exports.isNever = isNever;
function isNotNull(input, message = expectedToBe("not null")) {
(0, exports.assert)(input !== null, message);
}
exports.isNotNull = isNotNull;
function isNotUndefined2(input, message = expectedToBe("not undefined")) {
(0, exports.assert)(input !== void 0, message);
}
exports.isNotUndefined = isNotUndefined2;
function isNotVoid(input, message = expectedToBe("neither null nor undefined")) {
(0, exports.assert)(input !== null && input !== void 0, message);
}
exports.isNotVoid = isNotVoid;
function isExactly(input, value, message = expectedToBe(`exactly ${value}`)) {
(0, exports.assert)(input === value, message);
}
exports.isExactly = isExactly;
function isBoolean(input, message = expectedToBe("a boolean")) {
(0, exports.assert)(typeof input === "boolean", message);
}
exports.isBoolean = isBoolean;
function isNumber(input, message = expectedToBe("a number")) {
(0, exports.assert)(typeof input === "number", message);
}
exports.isNumber = isNumber;
function isString2(input, message = expectedToBe("a string")) {
(0, exports.assert)(typeof input === "string", message);
}
exports.isString = isString2;
function isDate(input, message = expectedToBe("a Date")) {
(0, exports.assert)(input instanceof Date, message);
}
exports.isDate = isDate;
function isRecord(input, message = expectedToBe("a record")) {
(0, exports.assert)(typeof input === "object", message);
isNotNull(input, message);
for (const key2 of Object.keys(input)) {
isString2(key2, message);
}
}
exports.isRecord = isRecord;
function isRecordWithKeys(input, keys, message = expectedToBe(`a record with keys ${keys.join(", ")}`)) {
isRecord(input, message);
for (const key2 of keys) {
isNotUndefined2(input[key2]);
}
}
exports.isRecordWithKeys = isRecordWithKeys;
function isArray(input, message = expectedToBe("an array")) {
(0, exports.assert)(Array.isArray(input), message);
}
exports.isArray = isArray;
function isRecordOfType(input, assertT, message = expectedToBe("a record of given type"), itemMessage = expectedToBe("of given type")) {
isRecord(input, message);
for (const item of Object.values(input)) {
assertT(item, itemMessage);
}
}
exports.isRecordOfType = isRecordOfType;
function isArrayOfType(input, assertT, message = expectedToBe("an array of given type"), itemMessage = expectedToBe("of given type")) {
isArray(input, message);
for (const item of input) {
assertT(item, itemMessage);
}
}
exports.isArrayOfType = isArrayOfType;
function isOptionOfType(input, assertT, message = expectedToBe("option of given type")) {
if (input === void 0) {
return;
}
assertT(input, message);
}
exports.isOptionOfType = isOptionOfType;
function isOneOf(input, values, message = expectedToBe(`one of ${values.join(", ")}`)) {
(0, exports.assert)(values.includes(input), message);
}
exports.isOneOf = isOneOf;
function isOneOfType(input, assertT, message = expectedToBe(`one of type`), itemMessage) {
for (const assert2 of assertT) {
try {
assert2(input, itemMessage);
return;
} catch (_) {
}
}
throw new TypeError(message);
}
exports.isOneOfType = isOneOfType;
function isInstanceOf(input, constructor, message = expectedToBe("an instance of given constructor")) {
(0, exports.assert)(input instanceof constructor, message);
}
exports.isInstanceOf = isInstanceOf;
function isPromise(input, message = expectedToBe("a promise")) {
isInstanceOf(input, Promise, message);
}
exports.isPromise = isPromise;
function check(assertT) {
return (input) => {
try {
assertT(input);
return true;
} catch (_) {
return false;
}
};
}
exports.check = check;
}
});
// node_modules/ms/index.js
var require_ms = __commonJS({
"node_modules/ms/index.js"(exports, module2) {
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
module2.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse3(val);
} else if (type === "number" && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse3(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return void 0;
}
}
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms / s) + "s";
}
return ms + "ms";
}
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms, msAbs, s, "second");
}
return ms + " ms";
}
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
}
}
});
// node_modules/debug/src/common.js
var require_common = __commonJS({
"node_modules/debug/src/common.js"(exports, module2) {
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms();
createDebug.destroy = destroy;
Object.keys(env).forEach((key2) => {
createDebug[key2] = env[key2];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug2(...args) {
if (!debug2.enabled) {
return;
}
const self = debug2;
const curr = Number(/* @__PURE__ */ new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug2.namespace = namespace;
debug2.useColors = createDebug.useColors();
debug2.color = createDebug.selectColor(namespace);
debug2.extend = extend;
debug2.destroy = createDebug.destroy;
Object.defineProperty(debug2, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug2);
}
return debug2;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
continue;
}
namespaces = split[i].replace(/\*/g, ".*?");
if (namespaces[0] === "-") {
createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
} else {
createDebug.names.push(new RegExp("^" + namespaces + "$"));
}
}
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name) {
if (name[name.length - 1] === "*") {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module2.exports = setup;
}
});
// node_modules/debug/src/browser.js
var require_browser = __commonJS({
"node_modules/debug/src/browser.js"(exports, module2) {
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") {
return;
}
index++;
if (match === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem("debug", namespaces);
} else {
exports.storage.removeItem("debug");
}
} catch (error) {
}
}
function load() {
let r;
try {
r = exports.storage.getItem("debug");
} catch (error) {
}
if (!r && typeof process !== "undefined" && "env" in process) {
r = process.env.DEBUG;
}
return r;
}
function localstorage() {
try {
return localStorage;
} catch (error) {
}
}
module2.exports = require_common()(exports);
var { formatters } = module2.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
}
});
// node_modules/@kwsites/file-exists/dist/src/index.js
var require_src = __commonJS({
"node_modules/@kwsites/file-exists/dist/src/index.js"(exports) {
"use strict";
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = require("fs");
var debug_1 = __importDefault(require_browser());
var log = debug_1.default("@kwsites/file-exists");
function check(path, isFile, isDirectory) {
log(`checking %s`, path);
try {
const stat = fs_1.statSync(path);
if (stat.isFile() && isFile) {
log(`[OK] path represents a file`);
return true;
}
if (stat.isDirectory() && isDirectory) {
log(`[OK] path represents a directory`);
return true;
}
log(`[FAIL] path represents something other than a file or directory`);
return false;
} catch (e) {
if (e.code === "ENOENT") {
log(`[FAIL] path is not accessible: %o`, e);
return false;
}
log(`[FATAL] %o`, e);
throw e;
}
}
function exists2(path, type = exports.READABLE) {
return check(path, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0);
}
exports.exists = exists2;
exports.FILE = 1;
exports.FOLDER = 2;
exports.READABLE = exports.FILE + exports.FOLDER;
}
});
// node_modules/@kwsites/file-exists/dist/index.js
var require_dist = __commonJS({
"node_modules/@kwsites/file-exists/dist/index.js"(exports) {
"use strict";
function __export3(m) {
for (var p in m)
if (!exports.hasOwnProperty(p))
exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export3(require_src());
}
});
// node_modules/@kwsites/promise-deferred/dist/index.js
var require_dist2 = __commonJS({
"node_modules/@kwsites/promise-deferred/dist/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDeferred = exports.deferred = void 0;
function deferred2() {
let done;
let fail;
let status = "pending";
const promise = new Promise((_done, _fail) => {
done = _done;
fail = _fail;
});
return {
promise,
done(result) {
if (status === "pending") {
status = "resolved";
done(result);
}
},
fail(error) {
if (status === "pending") {
status = "rejected";
fail(error);
}
},
get fulfilled() {
return status !== "pending";
},
get status() {
return status;
}
};
}
exports.deferred = deferred2;
exports.createDeferred = deferred2;
exports.default = deferred2;
}
});
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => RenderDiffPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian2 = require("obsidian");
// node_modules/diff2html/lib-esm/types.js
var LineType;
(function(LineType2) {
LineType2["INSERT"] = "insert";
LineType2["DELETE"] = "delete";
LineType2["CONTEXT"] = "context";
})(LineType || (LineType = {}));
var OutputFormatType = {
LINE_BY_LINE: "line-by-line",
SIDE_BY_SIDE: "side-by-side"
};
var LineMatchingType = {
LINES: "lines",
WORDS: "words",
NONE: "none"
};
var DiffStyleType = {
WORD: "word",
CHAR: "char"
};
// node_modules/diff2html/lib-esm/utils.js
var specials = [
"-",
"[",
"]",
"/",
"{",
"}",
"(",
")",
"*",
"+",
"?",
".",
"\\",
"^",
"$",
"|"
];
var regex = RegExp("[" + specials.join("\\") + "]", "g");
function escapeForRegExp(str) {
return str.replace(regex, "\\$&");
}
function unifyPath(path) {
return path ? path.replace(/\\/g, "/") : path;
}
function hashCode(text) {
var i, chr, len;
var hash = 0;
for (i = 0, len = text.length; i < len; i++) {
chr = text.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0;
}
return hash;
}
// node_modules/diff2html/lib-esm/diff-parser.js
var __spreadArray = function(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
function getExtension(filename, language) {
var filenameParts = filename.split(".");
return filenameParts.length > 1 ? filenameParts[filenameParts.length - 1] : language;
}
function startsWithAny(str, prefixes) {
return prefixes.reduce(function(startsWith, prefix) {
return startsWith || str.startsWith(prefix);
}, false);
}
var baseDiffFilenamePrefixes = ["a/", "b/", "i/", "w/", "c/", "o/"];
function getFilename(line, linePrefix, extraPrefix) {
var prefixes = extraPrefix !== void 0 ? __spreadArray(__spreadArray([], baseDiffFilenamePrefixes, true), [extraPrefix], false) : baseDiffFilenamePrefixes;
var FilenameRegExp = linePrefix ? new RegExp("^".concat(escapeForRegExp(linePrefix), ' "?(.+?)"?$')) : new RegExp('^"?(.+?)"?$');
var _a2 = FilenameRegExp.exec(line) || [], _b = _a2[1], filename = _b === void 0 ? "" : _b;
var matchingPrefix = prefixes.find(function(p) {
return filename.indexOf(p) === 0;
});
var fnameWithoutPrefix = matchingPrefix ? filename.slice(matchingPrefix.length) : filename;
return fnameWithoutPrefix.replace(/\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4}.*$/, "");
}
function getSrcFilename(line, srcPrefix) {
return getFilename(line, "---", srcPrefix);
}
function getDstFilename(line, dstPrefix) {
return getFilename(line, "+++", dstPrefix);
}
function parse(diffInput, config) {
if (config === void 0) {
config = {};
}
var files = [];
var currentFile = null;
var currentBlock = null;
var oldLine = null;
var oldLine2 = null;
var newLine = null;
var possibleOldName = null;
var possibleNewName = null;
var oldFileNameHeader = "--- ";
var newFileNameHeader = "+++ ";
var hunkHeaderPrefix = "@@";
var oldMode = /^old mode (\d{6})/;
var newMode = /^new mode (\d{6})/;
var deletedFileMode = /^deleted file mode (\d{6})/;
var newFileMode = /^new file mode (\d{6})/;
var copyFrom = /^copy from "?(.+)"?/;
var copyTo = /^copy to "?(.+)"?/;
var renameFrom = /^rename from "?(.+)"?/;
var renameTo = /^rename to "?(.+)"?/;
var similarityIndex = /^similarity index (\d+)%/;
var dissimilarityIndex = /^dissimilarity index (\d+)%/;
var index = /^index ([\da-z]+)\.\.([\da-z]+)\s*(\d{6})?/;
var binaryFiles = /^Binary files (.*) and (.*) differ/;
var binaryDiff = /^GIT binary patch/;
var combinedIndex = /^index ([\da-z]+),([\da-z]+)\.\.([\da-z]+)/;
var combinedMode = /^mode (\d{6}),(\d{6})\.\.(\d{6})/;
var combinedNewFile = /^new file mode (\d{6})/;
var combinedDeletedFile = /^deleted file mode (\d{6}),(\d{6})/;
var diffLines = diffInput.replace(/\\ No newline at end of file/g, "").replace(/\r\n?/g, "\n").split("\n");
function saveBlock() {
if (currentBlock !== null && currentFile !== null) {
currentFile.blocks.push(currentBlock);
currentBlock = null;
}
}
function saveFile() {
if (currentFile !== null) {
if (!currentFile.oldName && possibleOldName !== null) {
currentFile.oldName = possibleOldName;
}
if (!currentFile.newName && possibleNewName !== null) {
currentFile.newName = possibleNewName;
}
if (currentFile.newName) {
files.push(currentFile);
currentFile = null;
}
}
possibleOldName = null;
possibleNewName = null;
}
function startFile() {
saveBlock();
saveFile();
currentFile = {
blocks: [],
deletedLines: 0,
addedLines: 0
};
}
function startBlock(line) {
saveBlock();
var values;
if (currentFile !== null) {
if (values = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@.*/.exec(line)) {
currentFile.isCombined = false;
oldLine = parseInt(values[1], 10);
newLine = parseInt(values[2], 10);
} else if (values = /^@@@ -(\d+)(?:,\d+)? -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@@.*/.exec(line)) {
currentFile.isCombined = true;
oldLine = parseInt(values[1], 10);
oldLine2 = parseInt(values[2], 10);
newLine = parseInt(values[3], 10);
} else {
if (line.startsWith(hunkHeaderPrefix)) {
console.error("Failed to parse lines, starting in 0!");
}
oldLine = 0;
newLine = 0;
currentFile.isCombined = false;
}
}
currentBlock = {
lines: [],
oldStartLine: oldLine,
oldStartLine2: oldLine2,
newStartLine: newLine,
header: line
};
}
function createLine(line) {
if (currentFile === null || currentBlock === null || oldLine === null || newLine === null)
return;
var currentLine = {
content: line
};
var addedPrefixes = currentFile.isCombined ? ["+ ", " +", "++"] : ["+"];
var deletedPrefixes = currentFile.isCombined ? ["- ", " -", "--"] : ["-"];
if (startsWithAny(line, addedPrefixes)) {
currentFile.addedLines++;
currentLine.type = LineType.INSERT;
currentLine.oldNumber = void 0;
currentLine.newNumber = newLine++;
} else if (startsWithAny(line, deletedPrefixes)) {
currentFile.deletedLines++;
currentLine.type = LineType.DELETE;
currentLine.oldNumber = oldLine++;
currentLine.newNumber = void 0;
} else {
currentLine.type = LineType.CONTEXT;
currentLine.oldNumber = oldLine++;
currentLine.newNumber = newLine++;
}
currentBlock.lines.push(currentLine);
}
function existHunkHeader(line, lineIdx) {
var idx = lineIdx;
while (idx < diffLines.length - 3) {
if (line.startsWith("diff")) {
return false;
}
if (diffLines[idx].startsWith(oldFileNameHeader) && diffLines[idx + 1].startsWith(newFileNameHeader) && diffLines[idx + 2].startsWith(hunkHeaderPrefix)) {
return true;
}
idx++;
}
return false;
}
diffLines.forEach(function(line, lineIndex) {
if (!line || line.startsWith("*")) {
return;
}
var values;
var prevLine = diffLines[lineIndex - 1];
var nxtLine = diffLines[lineIndex + 1];
var afterNxtLine = diffLines[lineIndex + 2];
if (line.startsWith("diff --git") || line.startsWith("diff --combined")) {
startFile();
var gitDiffStart = /^diff --git "?([a-ciow]\/.+)"? "?([a-ciow]\/.+)"?/;
if (values = gitDiffStart.exec(line)) {
possibleOldName = getFilename(values[1], void 0, config.dstPrefix);
possibleNewName = getFilename(values[2], void 0, config.srcPrefix);
}
if (currentFile === null) {
throw new Error("Where is my file !!!");
}
currentFile.isGitDiff = true;
return;
}
if (line.startsWith("Binary files") && !(currentFile === null || currentFile === void 0 ? void 0 : currentFile.isGitDiff)) {
startFile();
var unixDiffBinaryStart = /^Binary files "?([a-ciow]\/.+)"? and "?([a-ciow]\/.+)"? differ/;
if (values = unixDiffBinaryStart.exec(line)) {
possibleOldName = getFilename(values[1], void 0, config.dstPrefix);
possibleNewName = getFilename(values[2], void 0, config.srcPrefix);
}
if (currentFile === null) {
throw new Error("Where is my file !!!");
}
currentFile.isBinary = true;
return;
}
if (!currentFile || !currentFile.isGitDiff && currentFile && line.startsWith(oldFileNameHeader) && nxtLine.startsWith(newFileNameHeader) && afterNxtLine.startsWith(hunkHeaderPrefix)) {
startFile();
}
if (currentFile === null || currentFile === void 0 ? void 0 : currentFile.isTooBig) {
return;
}
if (currentFile && (typeof config.diffMaxChanges === "number" && currentFile.addedLines + currentFile.deletedLines > config.diffMaxChanges || typeof config.diffMaxLineLength === "number" && line.length > config.diffMaxLineLength)) {
currentFile.isTooBig = true;
currentFile.addedLines = 0;
currentFile.deletedLines = 0;
currentFile.blocks = [];
currentBlock = null;
var message = typeof config.diffTooBigMessage === "function" ? config.diffTooBigMessage(files.length) : "Diff too big to be displayed";
startBlock(message);
return;
}
if (line.startsWith(oldFileNameHeader) && nxtLine.startsWith(newFileNameHeader) || line.startsWith(newFileNameHeader) && prevLine.startsWith(oldFileNameHeader)) {
if (currentFile && !currentFile.oldName && line.startsWith("--- ") && (values = getSrcFilename(line, config.srcPrefix))) {
currentFile.oldName = values;
currentFile.language = getExtension(currentFile.oldName, currentFile.language);
return;
}
if (currentFile && !currentFile.newName && line.startsWith("+++ ") && (values = getDstFilename(line, config.dstPrefix))) {
currentFile.newName = values;
currentFile.language = getExtension(currentFile.newName, currentFile.language);
return;
}
}
if (currentFile && (line.startsWith(hunkHeaderPrefix) || currentFile.isGitDiff && currentFile.oldName && currentFile.newName && !currentBlock)) {
startBlock(line);
return;
}
if (currentBlock && (line.startsWith("+") || line.startsWith("-") || line.startsWith(" "))) {
createLine(line);
return;
}
var doesNotExistHunkHeader = !existHunkHeader(line, lineIndex);
if (currentFile === null) {
throw new Error("Where is my file !!!");
}
if (values = oldMode.exec(line)) {
currentFile.oldMode = values[1];
} else if (values = newMode.exec(line)) {
currentFile.newMode = values[1];
} else if (values = deletedFileMode.exec(line)) {
currentFile.deletedFileMode = values[1];
currentFile.isDeleted = true;
} else if (values = newFileMode.exec(line)) {
currentFile.newFileMode = values[1];
currentFile.isNew = true;
} else if (values = copyFrom.exec(line)) {
if (doesNotExistHunkHeader) {
currentFile.oldName = values[1];
}
currentFile.isCopy = true;
} else if (values = copyTo.exec(line)) {
if (doesNotExistHunkHeader) {
currentFile.newName = values[1];
}
currentFile.isCopy = true;
} else if (values = renameFrom.exec(line)) {
if (doesNotExistHunkHeader) {
currentFile.oldName = values[1];
}
currentFile.isRename = true;
} else if (values = renameTo.exec(line)) {
if (doesNotExistHunkHeader) {
currentFile.newName = values[1];
}
currentFile.isRename = true;
} else if (values = binaryFiles.exec(line)) {
currentFile.isBinary = true;
currentFile.oldName = getFilename(values[1], void 0, config.srcPrefix);
currentFile.newName = getFilename(values[2], void 0, config.dstPrefix);
startBlock("Binary file");
} else if (binaryDiff.test(line)) {
currentFile.isBinary = true;
startBlock(line);
} else if (values = similarityIndex.exec(line)) {
currentFile.unchangedPercentage = parseInt(values[1], 10);
} else if (values = dissimilarityIndex.exec(line)) {
currentFile.changedPercentage = parseInt(values[1], 10);
} else if (values = index.exec(line)) {
currentFile.checksumBefore = values[1];
currentFile.checksumAfter = values[2];
values[3] && (currentFile.mode = values[3]);
} else if (values = combinedIndex.exec(line)) {
currentFile.checksumBefore = [values[2], values[3]];
currentFile.checksumAfter = values[1];
} else if (values = combinedMode.exec(line)) {
currentFile.oldMode = [values[2], values[3]];
currentFile.newMode = values[1];
} else if (values = combinedNewFile.exec(line)) {
currentFile.newFileMode = values[1];
currentFile.isNew = true;
} else if (values = combinedDeletedFile.exec(line)) {
currentFile.deletedFileMode = values[1];
currentFile.isDeleted = true;
}
});
saveBlock();
saveFile();
return files;
}
// node_modules/diff/lib/index.mjs
function Diff() {
}
Diff.prototype = {
diff: function diff(oldString, newString) {
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
var callback = options.callback;
if (typeof options === "function") {
callback = options;
options = {};
}
this.options = options;
var self = this;
function done(value) {
if (callback) {
setTimeout(function() {
callback(void 0, value);
}, 0);
return true;
} else {
return value;
}
}
oldString = this.castInput(oldString);
newString = this.castInput(newString);
oldString = this.removeEmpty(this.tokenize(oldString));
newString = this.removeEmpty(this.tokenize(newString));
var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen;
if (options.maxEditLength) {
maxEditLength = Math.min(maxEditLength, options.maxEditLength);
}
var bestPath = [{
newPos: -1,
components: []
}];
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done([{
value: this.join(newString),
count: newString.length
}]);
}
function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath = void 0;
var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
bestPath[diagonalPath - 1] = void 0;
}
var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = void 0;
continue;
}
if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, void 0, true);
} else {
basePath = addPath;
basePath.newPos++;
self.pushComponent(basePath.components, true, void 0);
}
_oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
} else {
bestPath[diagonalPath] = basePath;
}
}
editLength++;
}
if (callback) {
(function exec() {
setTimeout(function() {
if (editLength > maxEditLength) {
return callback();
}
if (!execEditLength()) {
exec();
}
}, 0);
})();
} else {
while (editLength <= maxEditLength) {
var ret = execEditLength();
if (ret) {
return ret;
}
}
}
},
pushComponent: function pushComponent(components, added, removed) {
var last2 = components[components.length - 1];
if (last2 && last2.added === added && last2.removed === removed) {
components[components.length - 1] = {
count: last2.count + 1,
added,
removed
};
} else {
components.push({
count: 1,
added,
removed
});
}
},
extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.components.push({
count: commonCount
});
}
basePath.newPos = newPos;
return oldPos;
},
equals: function equals(left, right) {
if (this.options.comparator) {
return this.options.comparator(left, right);
} else {
return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
},
removeEmpty: function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
},
castInput: function castInput(value) {
return value;
},
tokenize: function tokenize(value) {
return value.split("");
},
join: function join(chars) {
return chars.join("");
}
};
function buildValues(diff2, components, newString, oldString, useLongestToken) {
var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
var component = components[componentPos];
if (!component.removed) {
if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count);
value = value.map(function(value2, i) {
var oldValue = oldString[oldPos + i];
return oldValue.length > value2.length ? oldValue : value2;
});
component.value = diff2.join(value);
} else {
component.value = diff2.join(newString.slice(newPos, newPos + component.count));
}
newPos += component.count;
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
oldPos += component.count;
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
}
}
var lastComponent = components[componentLen - 1];
if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff2.equals("", lastComponent.value)) {
components[componentLen - 2].value += lastComponent.value;
components.pop();
}
return components;
}
function clonePath(path) {
return {
newPos: path.newPos,
components: path.components.slice(0)
};
}
var characterDiff = new Diff();
function diffChars(oldStr, newStr, options) {
return characterDiff.diff(oldStr, newStr, options);
}
var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
var reWhitespace = /\S/;
var wordDiff = new Diff();
wordDiff.equals = function(left, right) {
if (this.options.ignoreCase) {
left = left.toLowerCase();
right = right.toLowerCase();
}
return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
};
wordDiff.tokenize = function(value) {
var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
for (var i = 0; i < tokens.length - 1; i++) {
if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
tokens[i] += tokens[i + 2];
tokens.splice(i + 1, 2);
i--;
}
}
return tokens;
};
function diffWordsWithSpace(oldStr, newStr, options) {
return wordDiff.diff(oldStr, newStr, options);
}
var lineDiff = new Diff();
lineDiff.tokenize = function(value) {
var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2 && !this.options.newlineIsToken) {
retLines[retLines.length - 1] += line;
} else {
if (this.options.ignoreWhitespace) {
line = line.trim();
}
retLines.push(line);
}
}
return retLines;
};
var sentenceDiff = new Diff();
sentenceDiff.tokenize = function(value) {
return value.split(/(\S.+?[.!?])(?=\s+|$)/);
};
var cssDiff = new Diff();
cssDiff.tokenize = function(value) {
return value.split(/([{}:;,]|\s+)/);
};
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function(obj2) {
return typeof obj2;
};
} else {
_typeof = function(obj2) {
return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
};
}
return _typeof(obj);
}
var objectPrototypeToString = Object.prototype.toString;
var jsonDiff = new Diff();
jsonDiff.useLongestToken = true;
jsonDiff.tokenize = lineDiff.tokenize;
jsonDiff.castInput = function(value) {
var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
return typeof v === "undefined" ? undefinedReplacement : v;
} : _this$options$stringi;
return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
};
jsonDiff.equals = function(left, right) {
return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
};
function canonicalize(obj, stack, replacementStack, replacer, key2) {
stack = stack || [];
replacementStack = replacementStack || [];
if (replacer) {
obj = replacer(key2, obj);
}
var i;
for (i = 0; i < stack.length; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ("[object Array]" === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0; i < obj.length; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key2);
}
stack.pop();
replacementStack.pop();
return canonicalizedObj;
}
if (obj && obj.toJSON) {
obj = obj.toJSON();
}
if (_typeof(obj) === "object" && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [], _key;
for (_key in obj) {
if (obj.hasOwnProperty(_key)) {
sortedKeys.push(_key);
}
}
sortedKeys.sort();
for (i = 0; i < sortedKeys.length; i += 1) {
_key = sortedKeys[i];
canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
var arrayDiff = new Diff();
arrayDiff.tokenize = function(value) {
return value.slice();
};
arrayDiff.join = arrayDiff.removeEmpty = function(value) {
return value;
};
// node_modules/diff2html/lib-esm/rematch.js
function levenshtein(a, b) {
if (a.length === 0) {
return b.length;
}
if (b.length === 0) {
return a.length;
}
var matrix = [];
var i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
var j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
}
}
}
return matrix[b.length][a.length];
}
function newDistanceFn(str) {
return function(x, y) {
var xValue = str(x).trim();
var yValue = str(y).trim();
var lev = levenshtein(xValue, yValue);
return lev / (xValue.length + yValue.length);
};
}
function newMatcherFn(distance2) {
function findBestMatch(a, b, cache) {
if (cache === void 0) {
cache = /* @__PURE__ */ new Map();
}
var bestMatchDist = Infinity;
var bestMatch;
for (var i = 0; i < a.length; ++i) {
for (var j = 0; j < b.length; ++j) {
var cacheKey = JSON.stringify([a[i], b[j]]);
var md = void 0;
if (!(cache.has(cacheKey) && (md = cache.get(cacheKey)))) {
md = distance2(a[i], b[j]);
cache.set(cacheKey, md);
}
if (md < bestMatchDist) {
bestMatchDist = md;
bestMatch = { indexA: i, indexB: j, score: bestMatchDist };
}
}
}
return bestMatch;
}
function group(a, b, level, cache) {
if (level === void 0) {
level = 0;
}
if (cache === void 0) {
cache = /* @__PURE__ */ new Map();
}
var bm = findBestMatch(a, b, cache);
if (!bm || a.length + b.length < 3) {
return [[a, b]];
}
var a1 = a.slice(0, bm.indexA);
var b1 = b.slice(0, bm.indexB);
var aMatch = [a[bm.indexA]];
var bMatch = [b[bm.indexB]];
var tailA = bm.indexA + 1;
var tailB = bm.indexB + 1;
var a2 = a.slice(tailA);
var b2 = b.slice(tailB);
var group1 = group(a1, b1, level + 1, cache);
var groupMatch = group(aMatch, bMatch, level + 1, cache);
var group2 = group(a2, b2, level + 1, cache);
var result = groupMatch;
if (bm.indexA > 0 || bm.indexB > 0) {
result = group1.concat(result);
}
if (a.length > tailA || b.length > tailB) {
result = result.concat(group2);
}
return result;
}
return group;
}
// node_modules/diff2html/lib-esm/render-utils.js
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var CSSLineClass = {
INSERTS: "d2h-ins",
DELETES: "d2h-del",
CONTEXT: "d2h-cntx",
INFO: "d2h-info",
INSERT_CHANGES: "d2h-ins d2h-change",
DELETE_CHANGES: "d2h-del d2h-change"
};
var defaultRenderConfig = {
matching: LineMatchingType.NONE,
matchWordsThreshold: 0.25,
maxLineLengthHighlight: 1e4,
diffStyle: DiffStyleType.WORD
};
var separator = "/";
var distance = newDistanceFn(function(change) {
return change.value;
});
var matcher = newMatcherFn(distance);
function isDevNullName(name) {
return name.indexOf("dev/null") !== -1;
}
function removeInsElements(line) {
return line.replace(/(<ins[^>]*>((.|\n)*?)<\/ins>)/g, "");
}
function removeDelElements(line) {
return line.replace(/(<del[^>]*>((.|\n)*?)<\/del>)/g, "");
}
function toCSSClass(lineType) {
switch (lineType) {
case LineType.CONTEXT:
return CSSLineClass.CONTEXT;
case LineType.INSERT:
return CSSLineClass.INSERTS;
case LineType.DELETE:
return CSSLineClass.DELETES;
}
}
function prefixLength(isCombined) {
return isCombined ? 2 : 1;
}
function escapeForHtml(str) {
return str.slice(0).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/\//g, "&#x2F;");
}
function deconstructLine(line, isCombined, escape) {
if (escape === void 0) {
escape = true;
}
var indexToSplit = prefixLength(isCombined);
return {
prefix: line.substring(0, indexToSplit),
content: escape ? escapeForHtml(line.substring(indexToSplit)) : line.substring(indexToSplit)
};
}
function filenameDiff(file) {
var oldFilename = unifyPath(file.oldName);
var newFilename = unifyPath(file.newName);
if (oldFilename !== newFilename && !isDevNullName(oldFilename) && !isDevNullName(newFilename)) {
var prefixPaths = [];
var suffixPaths = [];
var oldFilenameParts = oldFilename.split(separator);
var newFilenameParts = newFilename.split(separator);
var oldFilenamePartsSize = oldFilenameParts.length;
var newFilenamePartsSize = newFilenameParts.length;
var i = 0;
var j = oldFilenamePartsSize - 1;
var k = newFilenamePartsSize - 1;
while (i < j && i < k) {
if (oldFilenameParts[i] === newFilenameParts[i]) {
prefixPaths.push(newFilenameParts[i]);
i += 1;
} else {
break;
}
}
while (j > i && k > i) {
if (oldFilenameParts[j] === newFilenameParts[k]) {
suffixPaths.unshift(newFilenameParts[k]);
j -= 1;
k -= 1;
} else {
break;
}
}
var finalPrefix = prefixPaths.join(separator);
var finalSuffix = suffixPaths.join(separator);
var oldRemainingPath = oldFilenameParts.slice(i, j + 1).join(separator);
var newRemainingPath = newFilenameParts.slice(i, k + 1).join(separator);
if (finalPrefix.length && finalSuffix.length) {
return finalPrefix + separator + "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}" + separator + finalSuffix;
} else if (finalPrefix.length) {
return finalPrefix + separator + "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}";
} else if (finalSuffix.length) {
return "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}" + separator + finalSuffix;
}
return oldFilename + " \u2192 " + newFilename;
} else if (!isDevNullName(newFilename)) {
return newFilename;
} else {
return oldFilename;
}
}
function getHtmlId(file) {
return "d2h-".concat(hashCode(filenameDiff(file)).toString().slice(-6));
}
function getFileIcon(file) {
var templateName = "file-changed";
if (file.isRename) {
templateName = "file-renamed";
} else if (file.isCopy) {
templateName = "file-renamed";
} else if (file.isNew) {
templateName = "file-added";
} else if (file.isDeleted) {
templateName = "file-deleted";
} else if (file.newName !== file.oldName) {
templateName = "file-renamed";
}
return templateName;
}
function diffHighlight(diffLine1, diffLine2, isCombined, config) {
if (config === void 0) {
config = {};
}
var _a2 = __assign(__assign({}, defaultRenderConfig), config), matching = _a2.matching, maxLineLengthHighlight = _a2.maxLineLengthHighlight, matchWordsThreshold = _a2.matchWordsThreshold, diffStyle = _a2.diffStyle;
var line1 = deconstructLine(diffLine1, isCombined, false);
var line2 = deconstructLine(diffLine2, isCombined, false);
if (line1.content.length > maxLineLengthHighlight || line2.content.length > maxLineLengthHighlight) {
return {
oldLine: {
prefix: line1.prefix,
content: escapeForHtml(line1.content)
},
newLine: {
prefix: line2.prefix,
content: escapeForHtml(line2.content)
}
};
}
var diff2 = diffStyle === "char" ? diffChars(line1.content, line2.content) : diffWordsWithSpace(line1.content, line2.content);
var changedWords = [];
if (diffStyle === "word" && matching === "words") {
var removed = diff2.filter(function(element) {
return element.removed;
});
var added = diff2.filter(function(element) {
return element.added;
});
var chunks = matcher(added, removed);
chunks.forEach(function(chunk) {
if (chunk[0].length === 1 && chunk[1].length === 1) {
var dist = distance(chunk[0][0], chunk[1][0]);
if (dist < matchWordsThreshold) {
changedWords.push(chunk[0][0]);
changedWords.push(chunk[1][0]);
}
}
});
}
var highlightedLine = diff2.reduce(function(highlightedLine2, part) {
var elemType = part.added ? "ins" : part.removed ? "del" : null;
var addClass = changedWords.indexOf(part) > -1 ? ' class="d2h-change"' : "";
var escapedValue = escapeForHtml(part.value);
return elemType !== null ? "".concat(highlightedLine2, "<").concat(elemType).concat(addClass, ">").concat(escapedValue, "</").concat(elemType, ">") : "".concat(highlightedLine2).concat(escapedValue);
}, "");
return {
oldLine: {
prefix: line1.prefix,
content: removeInsElements(highlightedLine)
},
newLine: {
prefix: line2.prefix,
content: removeDelElements(highlightedLine)
}
};
}
// node_modules/diff2html/lib-esm/file-list-renderer.js
var baseTemplatesPath = "file-summary";
var iconsBaseTemplatesPath = "icon";
function render(diffFiles, hoganUtils) {
var files = diffFiles.map(function(file) {
return hoganUtils.render(baseTemplatesPath, "line", {
fileHtmlId: getHtmlId(file),
oldName: file.oldName,
newName: file.newName,
fileName: filenameDiff(file),
deletedLines: "-" + file.deletedLines,
addedLines: "+" + file.addedLines
}, {
fileIcon: hoganUtils.template(iconsBaseTemplatesPath, getFileIcon(file))
});
}).join("\n");
return hoganUtils.render(baseTemplatesPath, "wrapper", {
filesNumber: diffFiles.length,
files
});
}
// node_modules/diff2html/lib-esm/line-by-line-renderer.js
var __assign2 = function() {
__assign2 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign2.apply(this, arguments);
};
var defaultLineByLineRendererConfig = __assign2(__assign2({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 });
var genericTemplatesPath = "generic";
var baseTemplatesPath2 = "line-by-line";
var iconsBaseTemplatesPath2 = "icon";
var tagsBaseTemplatesPath = "tag";
var LineByLineRenderer = function() {
function LineByLineRenderer2(hoganUtils, config) {
if (config === void 0) {
config = {};
}
this.hoganUtils = hoganUtils;
this.config = __assign2(__assign2({}, defaultLineByLineRendererConfig), config);
}
LineByLineRenderer2.prototype.render = function(diffFiles) {
var _this = this;
var diffsHtml = diffFiles.map(function(file) {
var diffs;
if (file.blocks.length) {
diffs = _this.generateFileHtml(file);
} else {
diffs = _this.generateEmptyDiff();
}
return _this.makeFileDiffHtml(file, diffs);
}).join("\n");
return this.hoganUtils.render(genericTemplatesPath, "wrapper", { content: diffsHtml });
};
LineByLineRenderer2.prototype.makeFileDiffHtml = function(file, diffs) {
if (this.config.renderNothingWhenEmpty && Array.isArray(file.blocks) && file.blocks.length === 0)
return "";
var fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath2, "file-diff");
var filePathTemplate = this.hoganUtils.template(genericTemplatesPath, "file-path");
var fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath2, "file");
var fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath, getFileIcon(file));
return fileDiffTemplate.render({
file,
fileHtmlId: getHtmlId(file),
diffs,
filePath: filePathTemplate.render({
fileDiffName: filenameDiff(file)
}, {
fileIcon: fileIconTemplate,
fileTag: fileTagTemplate
})
});
};
LineByLineRenderer2.prototype.generateEmptyDiff = function() {
return this.hoganUtils.render(genericTemplatesPath, "empty-diff", {
contentClass: "d2h-code-line",
CSSLineClass
});
};
LineByLineRenderer2.prototype.generateFileHtml = function(file) {
var _this = this;
var matcher2 = newMatcherFn(newDistanceFn(function(e) {
return deconstructLine(e.content, file.isCombined).content;
}));
return file.blocks.map(function(block) {
var lines = _this.hoganUtils.render(genericTemplatesPath, "block-header", {
CSSLineClass,
blockHeader: file.isTooBig ? block.header : escapeForHtml(block.header),
lineClass: "d2h-code-linenumber",
contentClass: "d2h-code-line"
});
_this.applyLineGroupping(block).forEach(function(_a2) {
var contextLines = _a2[0], oldLines = _a2[1], newLines = _a2[2];
if (oldLines.length && newLines.length && !contextLines.length) {
_this.applyRematchMatching(oldLines, newLines, matcher2).map(function(_a3) {
var oldLines2 = _a3[0], newLines2 = _a3[1];
var _b2 = _this.processChangedLines(file, file.isCombined, oldLines2, newLines2), left2 = _b2.left, right2 = _b2.right;
lines += left2;
lines += right2;
});
} else if (contextLines.length) {
contextLines.forEach(function(line) {
var _a3 = deconstructLine(line.content, file.isCombined), prefix = _a3.prefix, content = _a3.content;
lines += _this.generateSingleLineHtml(file, {
type: CSSLineClass.CONTEXT,
prefix,
content,
oldNumber: line.oldNumber,
newNumber: line.newNumber
});
});
} else if (oldLines.length || newLines.length) {
var _b = _this.processChangedLines(file, file.isCombined, oldLines, newLines), left = _b.left, right = _b.right;
lines += left;
lines += right;
} else {
console.error("Unknown state reached while processing groups of lines", contextLines, oldLines, newLines);
}
});
return lines;
}).join("\n");
};
LineByLineRenderer2.prototype.applyLineGroupping = function(block) {
var blockLinesGroups = [];
var oldLines = [];
var newLines = [];
for (var i = 0; i < block.lines.length; i++) {
var diffLine = block.lines[i];
if (diffLine.type !== LineType.INSERT && newLines.length || diffLine.type === LineType.CONTEXT && oldLines.length > 0) {
blockLinesGroups.push([[], oldLines, newLines]);
oldLines = [];
newLines = [];
}
if (diffLine.type === LineType.CONTEXT) {
blockLinesGroups.push([[diffLine], [], []]);
} else if (diffLine.type === LineType.INSERT && oldLines.length === 0) {
blockLinesGroups.push([[], [], [diffLine]]);
} else if (diffLine.type === LineType.INSERT && oldLines.length > 0) {
newLines.push(diffLine);
} else if (diffLine.type === LineType.DELETE) {
oldLines.push(diffLine);
}
}
if (oldLines.length || newLines.length) {
blockLinesGroups.push([[], oldLines, newLines]);
oldLines = [];
newLines = [];
}
return blockLinesGroups;
};
LineByLineRenderer2.prototype.applyRematchMatching = function(oldLines, newLines, matcher2) {
var comparisons = oldLines.length * newLines.length;
var maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map(function(elem) {
return elem.content.length;
})));
var doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words");
return doMatching ? matcher2(oldLines, newLines) : [[oldLines, newLines]];
};
LineByLineRenderer2.prototype.processChangedLines = function(file, isCombined, oldLines, newLines) {
var fileHtml = {
right: "",
left: ""
};
var maxLinesNumber = Math.max(oldLines.length, newLines.length);
for (var i = 0; i < maxLinesNumber; i++) {
var oldLine = oldLines[i];
var newLine = newLines[i];
var diff2 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0;
var preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? __assign2(__assign2({}, diff2 !== void 0 ? {
prefix: diff2.oldLine.prefix,
content: diff2.oldLine.content,
type: CSSLineClass.DELETE_CHANGES
} : __assign2(__assign2({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { oldNumber: oldLine.oldNumber, newNumber: oldLine.newNumber }) : void 0;
var preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? __assign2(__assign2({}, diff2 !== void 0 ? {
prefix: diff2.newLine.prefix,
content: diff2.newLine.content,
type: CSSLineClass.INSERT_CHANGES
} : __assign2(__assign2({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { oldNumber: newLine.oldNumber, newNumber: newLine.newNumber }) : void 0;
var _a2 = this.generateLineHtml(file, preparedOldLine, preparedNewLine), left = _a2.left, right = _a2.right;
fileHtml.left += left;
fileHtml.right += right;
}
return fileHtml;
};
LineByLineRenderer2.prototype.generateLineHtml = function(file, oldLine, newLine) {
return {
left: this.generateSingleLineHtml(file, oldLine),
right: this.generateSingleLineHtml(file, newLine)
};
};
LineByLineRenderer2.prototype.generateSingleLineHtml = function(file, line) {
if (line === void 0)
return "";
var lineNumberHtml = this.hoganUtils.render(baseTemplatesPath2, "numbers", {
oldNumber: line.oldNumber || "",
newNumber: line.newNumber || ""
});
return this.hoganUtils.render(genericTemplatesPath, "line", {
type: line.type,
lineClass: "d2h-code-linenumber",
contentClass: "d2h-code-line",
prefix: line.prefix === " " ? "&nbsp;" : line.prefix,
content: line.content,
lineNumber: lineNumberHtml,
line,
file
});
};
return LineByLineRenderer2;
}();
var line_by_line_renderer_default = LineByLineRenderer;
// node_modules/diff2html/lib-esm/side-by-side-renderer.js
var __assign3 = function() {
__assign3 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign3.apply(this, arguments);
};
var defaultSideBySideRendererConfig = __assign3(__assign3({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 });
var genericTemplatesPath2 = "generic";
var baseTemplatesPath3 = "side-by-side";
var iconsBaseTemplatesPath3 = "icon";
var tagsBaseTemplatesPath2 = "tag";
var SideBySideRenderer = function() {
function SideBySideRenderer2(hoganUtils, config) {
if (config === void 0) {
config = {};
}
this.hoganUtils = hoganUtils;
this.config = __assign3(__assign3({}, defaultSideBySideRendererConfig), config);
}
SideBySideRenderer2.prototype.render = function(diffFiles) {
var _this = this;
var diffsHtml = diffFiles.map(function(file) {
var diffs;
if (file.blocks.length) {
diffs = _this.generateFileHtml(file);
} else {
diffs = _this.generateEmptyDiff();
}
return _this.makeFileDiffHtml(file, diffs);
}).join("\n");
return this.hoganUtils.render(genericTemplatesPath2, "wrapper", { content: diffsHtml });
};
SideBySideRenderer2.prototype.makeFileDiffHtml = function(file, diffs) {
if (this.config.renderNothingWhenEmpty && Array.isArray(file.blocks) && file.blocks.length === 0)
return "";
var fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath3, "file-diff");
var filePathTemplate = this.hoganUtils.template(genericTemplatesPath2, "file-path");
var fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath3, "file");
var fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath2, getFileIcon(file));
return fileDiffTemplate.render({
file,
fileHtmlId: getHtmlId(file),
diffs,
filePath: filePathTemplate.render({
fileDiffName: filenameDiff(file)
}, {
fileIcon: fileIconTemplate,
fileTag: fileTagTemplate
})
});
};
SideBySideRenderer2.prototype.generateEmptyDiff = function() {
return {
right: "",
left: this.hoganUtils.render(genericTemplatesPath2, "empty-diff", {
contentClass: "d2h-code-side-line",
CSSLineClass
})
};
};
SideBySideRenderer2.prototype.generateFileHtml = function(file) {
var _this = this;
var matcher2 = newMatcherFn(newDistanceFn(function(e) {
return deconstructLine(e.content, file.isCombined).content;
}));
return file.blocks.map(function(block) {
var fileHtml = {
left: _this.makeHeaderHtml(block.header, file),
right: _this.makeHeaderHtml("")
};
_this.applyLineGroupping(block).forEach(function(_a2) {
var contextLines = _a2[0], oldLines = _a2[1], newLines = _a2[2];
if (oldLines.length && newLines.length && !contextLines.length) {
_this.applyRematchMatching(oldLines, newLines, matcher2).map(function(_a3) {
var oldLines2 = _a3[0], newLines2 = _a3[1];
var _b2 = _this.processChangedLines(file.isCombined, oldLines2, newLines2), left2 = _b2.left, right2 = _b2.right;
fileHtml.left += left2;
fileHtml.right += right2;
});
} else if (contextLines.length) {
contextLines.forEach(function(line) {
var _a3 = deconstructLine(line.content, file.isCombined), prefix = _a3.prefix, content = _a3.content;
var _b2 = _this.generateLineHtml({
type: CSSLineClass.CONTEXT,
prefix,
content,
number: line.oldNumber
}, {
type: CSSLineClass.CONTEXT,
prefix,
content,
number: line.newNumber
}), left2 = _b2.left, right2 = _b2.right;
fileHtml.left += left2;
fileHtml.right += right2;
});
} else if (oldLines.length || newLines.length) {
var _b = _this.processChangedLines(file.isCombined, oldLines, newLines), left = _b.left, right = _b.right;
fileHtml.left += left;
fileHtml.right += right;
} else {
console.error("Unknown state reached while processing groups of lines", contextLines, oldLines, newLines);
}
});
return fileHtml;
}).reduce(function(accomulated, html2) {
return { left: accomulated.left + html2.left, right: accomulated.right + html2.right };
}, { left: "", right: "" });
};
SideBySideRenderer2.prototype.applyLineGroupping = function(block) {
var blockLinesGroups = [];
var oldLines = [];
var newLines = [];
for (var i = 0; i < block.lines.length; i++) {
var diffLine = block.lines[i];
if (diffLine.type !== LineType.INSERT && newLines.length || diffLine.type === LineType.CONTEXT && oldLines.length > 0) {
blockLinesGroups.push([[], oldLines, newLines]);
oldLines = [];
newLines = [];
}
if (diffLine.type === LineType.CONTEXT) {
blockLinesGroups.push([[diffLine], [], []]);
} else if (diffLine.type === LineType.INSERT && oldLines.length === 0) {
blockLinesGroups.push([[], [], [diffLine]]);
} else if (diffLine.type === LineType.INSERT && oldLines.length > 0) {
newLines.push(diffLine);
} else if (diffLine.type === LineType.DELETE) {
oldLines.push(diffLine);
}
}
if (oldLines.length || newLines.length) {
blockLinesGroups.push([[], oldLines, newLines]);
oldLines = [];
newLines = [];
}
return blockLinesGroups;
};
SideBySideRenderer2.prototype.applyRematchMatching = function(oldLines, newLines, matcher2) {
var comparisons = oldLines.length * newLines.length;
var maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map(function(elem) {
return elem.content.length;
})));
var doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words");
return doMatching ? matcher2(oldLines, newLines) : [[oldLines, newLines]];
};
SideBySideRenderer2.prototype.makeHeaderHtml = function(blockHeader, file) {
return this.hoganUtils.render(genericTemplatesPath2, "block-header", {
CSSLineClass,
blockHeader: (file === null || file === void 0 ? void 0 : file.isTooBig) ? blockHeader : escapeForHtml(blockHeader),
lineClass: "d2h-code-side-linenumber",
contentClass: "d2h-code-side-line"
});
};
SideBySideRenderer2.prototype.processChangedLines = function(isCombined, oldLines, newLines) {
var fileHtml = {
right: "",
left: ""
};
var maxLinesNumber = Math.max(oldLines.length, newLines.length);
for (var i = 0; i < maxLinesNumber; i++) {
var oldLine = oldLines[i];
var newLine = newLines[i];
var diff2 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0;
var preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? __assign3(__assign3({}, diff2 !== void 0 ? {
prefix: diff2.oldLine.prefix,
content: diff2.oldLine.content,
type: CSSLineClass.DELETE_CHANGES
} : __assign3(__assign3({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { number: oldLine.oldNumber }) : void 0;
var preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? __assign3(__assign3({}, diff2 !== void 0 ? {
prefix: diff2.newLine.prefix,
content: diff2.newLine.content,
type: CSSLineClass.INSERT_CHANGES
} : __assign3(__assign3({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { number: newLine.newNumber }) : void 0;
var _a2 = this.generateLineHtml(preparedOldLine, preparedNewLine), left = _a2.left, right = _a2.right;
fileHtml.left += left;
fileHtml.right += right;
}
return fileHtml;
};
SideBySideRenderer2.prototype.generateLineHtml = function(oldLine, newLine) {
return {
left: this.generateSingleHtml(oldLine),
right: this.generateSingleHtml(newLine)
};
};
SideBySideRenderer2.prototype.generateSingleHtml = function(line) {
var lineClass = "d2h-code-side-linenumber";
var contentClass = "d2h-code-side-line";
return this.hoganUtils.render(genericTemplatesPath2, "line", {
type: (line === null || line === void 0 ? void 0 : line.type) || "".concat(CSSLineClass.CONTEXT, " d2h-emptyplaceholder"),
lineClass: line !== void 0 ? lineClass : "".concat(lineClass, " d2h-code-side-emptyplaceholder"),
contentClass: line !== void 0 ? contentClass : "".concat(contentClass, " d2h-code-side-emptyplaceholder"),
prefix: (line === null || line === void 0 ? void 0 : line.prefix) === " " ? "&nbsp;" : line === null || line === void 0 ? void 0 : line.prefix,
content: line === null || line === void 0 ? void 0 : line.content,
lineNumber: line === null || line === void 0 ? void 0 : line.number
});
};
return SideBySideRenderer2;
}();
var side_by_side_renderer_default = SideBySideRenderer;
// node_modules/diff2html/lib-esm/hoganjs-utils.js
var Hogan3 = __toESM(require_hogan());
// node_modules/diff2html/lib-esm/diff2html-templates.js
var Hogan2 = __toESM(require_hogan());
var defaultTemplates = {};
defaultTemplates["file-summary-line"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<li class="d2h-file-list-line">');
t.b("\n" + i);
t.b(' <span class="d2h-file-name-wrapper">');
t.b("\n" + i);
t.b(t.rp("<fileIcon0", c, p, " "));
t.b(' <a href="#');
t.b(t.v(t.f("fileHtmlId", c, p, 0)));
t.b('" class="d2h-file-name">');
t.b(t.v(t.f("fileName", c, p, 0)));
t.b("</a>");
t.b("\n" + i);
t.b(' <span class="d2h-file-stats">');
t.b("\n" + i);
t.b(' <span class="d2h-lines-added">');
t.b(t.v(t.f("addedLines", c, p, 0)));
t.b("</span>");
t.b("\n" + i);
t.b(' <span class="d2h-lines-deleted">');
t.b(t.v(t.f("deletedLines", c, p, 0)));
t.b("</span>");
t.b("\n" + i);
t.b(" </span>");
t.b("\n" + i);
t.b(" </span>");
t.b("\n" + i);
t.b("</li>");
return t.fl();
}, partials: { "<fileIcon0": { name: "fileIcon", partials: {}, subs: {} } }, subs: {} });
defaultTemplates["file-summary-wrapper"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<div class="d2h-file-list-wrapper">');
t.b("\n" + i);
t.b(' <div class="d2h-file-list-header">');
t.b("\n" + i);
t.b(' <span class="d2h-file-list-title">Files changed (');
t.b(t.v(t.f("filesNumber", c, p, 0)));
t.b(")</span>");
t.b("\n" + i);
t.b(' <a class="d2h-file-switch d2h-hide">hide</a>');
t.b("\n" + i);
t.b(' <a class="d2h-file-switch d2h-show">show</a>');
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(' <ol class="d2h-file-list">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.f("files", c, p, 0)));
t.b("\n" + i);
t.b(" </ol>");
t.b("\n" + i);
t.b("</div>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["generic-block-header"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b("<tr>");
t.b("\n" + i);
t.b(' <td class="');
t.b(t.v(t.f("lineClass", c, p, 0)));
t.b(" ");
t.b(t.v(t.d("CSSLineClass.INFO", c, p, 0)));
t.b('"></td>');
t.b("\n" + i);
t.b(' <td class="');
t.b(t.v(t.d("CSSLineClass.INFO", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(' <div class="');
t.b(t.v(t.f("contentClass", c, p, 0)));
t.b('">');
if (t.s(t.f("blockHeader", c, p, 1), c, p, 0, 156, 173, "{{ }}")) {
t.rs(c, p, function(c2, p2, t2) {
t2.b(t2.t(t2.f("blockHeader", c2, p2, 0)));
});
c.pop();
}
if (!t.s(t.f("blockHeader", c, p, 1), c, p, 1, 0, 0, "")) {
t.b("&nbsp;");
}
;
t.b("</div>");
t.b("\n" + i);
t.b(" </td>");
t.b("\n" + i);
t.b("</tr>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["generic-empty-diff"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b("<tr>");
t.b("\n" + i);
t.b(' <td class="');
t.b(t.v(t.d("CSSLineClass.INFO", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(' <div class="');
t.b(t.v(t.f("contentClass", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(" File without changes");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(" </td>");
t.b("\n" + i);
t.b("</tr>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["generic-file-path"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<span class="d2h-file-name-wrapper">');
t.b("\n" + i);
t.b(t.rp("<fileIcon0", c, p, " "));
t.b(' <span class="d2h-file-name">');
t.b(t.v(t.f("fileDiffName", c, p, 0)));
t.b("</span>");
t.b("\n" + i);
t.b(t.rp("<fileTag1", c, p, " "));
t.b("</span>");
t.b("\n" + i);
t.b('<label class="d2h-file-collapse">');
t.b("\n" + i);
t.b(' <input class="d2h-file-collapse-input" type="checkbox" name="viewed" value="viewed">');
t.b("\n" + i);
t.b(" Viewed");
t.b("\n" + i);
t.b("</label>");
return t.fl();
}, partials: { "<fileIcon0": { name: "fileIcon", partials: {}, subs: {} }, "<fileTag1": { name: "fileTag", partials: {}, subs: {} } }, subs: {} });
defaultTemplates["generic-line"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b("<tr>");
t.b("\n" + i);
t.b(' <td class="');
t.b(t.v(t.f("lineClass", c, p, 0)));
t.b(" ");
t.b(t.v(t.f("type", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.f("lineNumber", c, p, 0)));
t.b("\n" + i);
t.b(" </td>");
t.b("\n" + i);
t.b(' <td class="');
t.b(t.v(t.f("type", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(' <div class="');
t.b(t.v(t.f("contentClass", c, p, 0)));
t.b('">');
t.b("\n" + i);
if (t.s(t.f("prefix", c, p, 1), c, p, 0, 162, 238, "{{ }}")) {
t.rs(c, p, function(c2, p2, t2) {
t2.b(' <span class="d2h-code-line-prefix">');
t2.b(t2.t(t2.f("prefix", c2, p2, 0)));
t2.b("</span>");
t2.b("\n" + i);
});
c.pop();
}
if (!t.s(t.f("prefix", c, p, 1), c, p, 1, 0, 0, "")) {
t.b(' <span class="d2h-code-line-prefix">&nbsp;</span>');
t.b("\n" + i);
}
;
if (t.s(t.f("content", c, p, 1), c, p, 0, 371, 445, "{{ }}")) {
t.rs(c, p, function(c2, p2, t2) {
t2.b(' <span class="d2h-code-line-ctn">');
t2.b(t2.t(t2.f("content", c2, p2, 0)));
t2.b("</span>");
t2.b("\n" + i);
});
c.pop();
}
if (!t.s(t.f("content", c, p, 1), c, p, 1, 0, 0, "")) {
t.b(' <span class="d2h-code-line-ctn"><br></span>');
t.b("\n" + i);
}
;
t.b(" </div>");
t.b("\n" + i);
t.b(" </td>");
t.b("\n" + i);
t.b("</tr>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["generic-wrapper"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<div class="d2h-wrapper">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.f("content", c, p, 0)));
t.b("\n" + i);
t.b("</div>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["icon-file-added"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<svg aria-hidden="true" class="d2h-icon d2h-added" height="16" title="added" version="1.1" viewBox="0 0 14 16"');
t.b("\n" + i);
t.b(' width="14">');
t.b("\n" + i);
t.b(' <path d="M13 1H1C0.45 1 0 1.45 0 2v12c0 0.55 0.45 1 1 1h12c0.55 0 1-0.45 1-1V2c0-0.55-0.45-1-1-1z m0 13H1V2h12v12zM6 9H3V7h3V4h2v3h3v2H8v3H6V9z"></path>');
t.b("\n" + i);
t.b("</svg>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["icon-file-changed"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<svg aria-hidden="true" class="d2h-icon d2h-changed" height="16" title="modified" version="1.1"');
t.b("\n" + i);
t.b(' viewBox="0 0 14 16" width="14">');
t.b("\n" + i);
t.b(' <path d="M13 1H1C0.45 1 0 1.45 0 2v12c0 0.55 0.45 1 1 1h12c0.55 0 1-0.45 1-1V2c0-0.55-0.45-1-1-1z m0 13H1V2h12v12zM4 8c0-1.66 1.34-3 3-3s3 1.34 3 3-1.34 3-3 3-3-1.34-3-3z"></path>');
t.b("\n" + i);
t.b("</svg>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["icon-file-deleted"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<svg aria-hidden="true" class="d2h-icon d2h-deleted" height="16" title="removed" version="1.1"');
t.b("\n" + i);
t.b(' viewBox="0 0 14 16" width="14">');
t.b("\n" + i);
t.b(' <path d="M13 1H1C0.45 1 0 1.45 0 2v12c0 0.55 0.45 1 1 1h12c0.55 0 1-0.45 1-1V2c0-0.55-0.45-1-1-1z m0 13H1V2h12v12zM11 9H3V7h8v2z"></path>');
t.b("\n" + i);
t.b("</svg>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["icon-file-renamed"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<svg aria-hidden="true" class="d2h-icon d2h-moved" height="16" title="renamed" version="1.1"');
t.b("\n" + i);
t.b(' viewBox="0 0 14 16" width="14">');
t.b("\n" + i);
t.b(' <path d="M6 9H3V7h3V4l5 4-5 4V9z m8-7v12c0 0.55-0.45 1-1 1H1c-0.55 0-1-0.45-1-1V2c0-0.55 0.45-1 1-1h12c0.55 0 1 0.45 1 1z m-1 0H1v12h12V2z"></path>');
t.b("\n" + i);
t.b("</svg>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["icon-file"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<svg aria-hidden="true" class="d2h-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12">');
t.b("\n" + i);
t.b(' <path d="M6 5H2v-1h4v1zM2 8h7v-1H2v1z m0 2h7v-1H2v1z m0 2h7v-1H2v1z m10-7.5v9.5c0 0.55-0.45 1-1 1H1c-0.55 0-1-0.45-1-1V2c0-0.55 0.45-1 1-1h7.5l3.5 3.5z m-1 0.5L8 2H1v12h10V5z"></path>');
t.b("\n" + i);
t.b("</svg>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["line-by-line-file-diff"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<div id="');
t.b(t.v(t.f("fileHtmlId", c, p, 0)));
t.b('" class="d2h-file-wrapper" data-lang="');
t.b(t.v(t.d("file.language", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(' <div class="d2h-file-header">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.f("filePath", c, p, 0)));
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(' <div class="d2h-file-diff">');
t.b("\n" + i);
t.b(' <div class="d2h-code-wrapper">');
t.b("\n" + i);
t.b(' <table class="d2h-diff-table">');
t.b("\n" + i);
t.b(' <tbody class="d2h-diff-tbody">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.f("diffs", c, p, 0)));
t.b("\n" + i);
t.b(" </tbody>");
t.b("\n" + i);
t.b(" </table>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b("</div>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["line-by-line-numbers"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<div class="line-num1">');
t.b(t.v(t.f("oldNumber", c, p, 0)));
t.b("</div>");
t.b("\n" + i);
t.b('<div class="line-num2">');
t.b(t.v(t.f("newNumber", c, p, 0)));
t.b("</div>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["side-by-side-file-diff"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<div id="');
t.b(t.v(t.f("fileHtmlId", c, p, 0)));
t.b('" class="d2h-file-wrapper" data-lang="');
t.b(t.v(t.d("file.language", c, p, 0)));
t.b('">');
t.b("\n" + i);
t.b(' <div class="d2h-file-header">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.f("filePath", c, p, 0)));
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(' <div class="d2h-files-diff">');
t.b("\n" + i);
t.b(' <div class="d2h-file-side-diff">');
t.b("\n" + i);
t.b(' <div class="d2h-code-wrapper">');
t.b("\n" + i);
t.b(' <table class="d2h-diff-table">');
t.b("\n" + i);
t.b(' <tbody class="d2h-diff-tbody">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.d("diffs.left", c, p, 0)));
t.b("\n" + i);
t.b(" </tbody>");
t.b("\n" + i);
t.b(" </table>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(' <div class="d2h-file-side-diff">');
t.b("\n" + i);
t.b(' <div class="d2h-code-wrapper">');
t.b("\n" + i);
t.b(' <table class="d2h-diff-table">');
t.b("\n" + i);
t.b(' <tbody class="d2h-diff-tbody">');
t.b("\n" + i);
t.b(" ");
t.b(t.t(t.d("diffs.right", c, p, 0)));
t.b("\n" + i);
t.b(" </tbody>");
t.b("\n" + i);
t.b(" </table>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b(" </div>");
t.b("\n" + i);
t.b("</div>");
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["tag-file-added"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<span class="d2h-tag d2h-added d2h-added-tag">ADDED</span>');
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["tag-file-changed"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<span class="d2h-tag d2h-changed d2h-changed-tag">CHANGED</span>');
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["tag-file-deleted"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<span class="d2h-tag d2h-deleted d2h-deleted-tag">DELETED</span>');
return t.fl();
}, partials: {}, subs: {} });
defaultTemplates["tag-file-renamed"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
t.b(i = i || "");
t.b('<span class="d2h-tag d2h-moved d2h-moved-tag">RENAMED</span>');
return t.fl();
}, partials: {}, subs: {} });
// node_modules/diff2html/lib-esm/hoganjs-utils.js
var __assign4 = function() {
__assign4 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign4.apply(this, arguments);
};
var HoganJsUtils = function() {
function HoganJsUtils2(_a2) {
var _b = _a2.compiledTemplates, compiledTemplates = _b === void 0 ? {} : _b, _c = _a2.rawTemplates, rawTemplates2 = _c === void 0 ? {} : _c;
var compiledRawTemplates = Object.entries(rawTemplates2).reduce(function(previousTemplates, _a3) {
var _b2;
var name = _a3[0], templateString = _a3[1];
var compiledTemplate = Hogan3.compile(templateString, { asString: false });
return __assign4(__assign4({}, previousTemplates), (_b2 = {}, _b2[name] = compiledTemplate, _b2));
}, {});
this.preCompiledTemplates = __assign4(__assign4(__assign4({}, defaultTemplates), compiledTemplates), compiledRawTemplates);
}
HoganJsUtils2.compile = function(templateString) {
return Hogan3.compile(templateString, { asString: false });
};
HoganJsUtils2.prototype.render = function(namespace, view, params, partials, indent) {
var templateKey = this.templateKey(namespace, view);
try {
var template = this.preCompiledTemplates[templateKey];
return template.render(params, partials, indent);
} catch (e) {
throw new Error("Could not find template to render '".concat(templateKey, "'"));
}
};
HoganJsUtils2.prototype.template = function(namespace, view) {
return this.preCompiledTemplates[this.templateKey(namespace, view)];
};
HoganJsUtils2.prototype.templateKey = function(namespace, view) {
return "".concat(namespace, "-").concat(view);
};
return HoganJsUtils2;
}();
var hoganjs_utils_default = HoganJsUtils;
// node_modules/diff2html/lib-esm/diff2html.js
var __assign5 = function() {
__assign5 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign5.apply(this, arguments);
};
var defaultDiff2HtmlConfig = __assign5(__assign5(__assign5({}, defaultLineByLineRendererConfig), defaultSideBySideRendererConfig), { outputFormat: OutputFormatType.LINE_BY_LINE, drawFileList: true });
function parse2(diffInput, configuration) {
if (configuration === void 0) {
configuration = {};
}
return parse(diffInput, __assign5(__assign5({}, defaultDiff2HtmlConfig), configuration));
}
function html(diffInput, configuration) {
if (configuration === void 0) {
configuration = {};
}
var config = __assign5(__assign5({}, defaultDiff2HtmlConfig), configuration);
var diffJson = typeof diffInput === "string" ? parse(diffInput, config) : diffInput;
var hoganUtils = new hoganjs_utils_default(config);
var fileList = config.drawFileList ? render(diffJson, hoganUtils) : "";
var diffOutput = config.outputFormat === "side-by-side" ? new side_by_side_renderer_default(hoganUtils, config).render(diffJson) : new line_by_line_renderer_default(hoganUtils, config).render(diffJson);
return fileList + diffOutput;
}
// src/utils.ts
var import_obsidian = require("obsidian");
var import_typed_assert = __toESM(require_build());
// node_modules/simple-git/dist/esm/index.js
var import_file_exists = __toESM(require_dist(), 1);
var import_debug = __toESM(require_browser(), 1);
var import_child_process = require("child_process");
var import_promise_deferred = __toESM(require_dist2(), 1);
var import_promise_deferred2 = __toESM(require_dist2(), 1);
var __defProp2 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp2(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp2.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __markAsModule = (target) => __defProp2(target, "__esModule", { value: true });
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
};
var __commonJS2 = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export2 = (target, all) => {
for (var name in all)
__defProp2(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, copyDefault, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key2 of __getOwnPropNames2(module2))
if (!__hasOwnProp2.call(target, key2) && (copyDefault || key2 !== "default"))
__defProp2(target, key2, { get: () => module2[key2], enumerable: !(desc = __getOwnPropDesc2(module2, key2)) || desc.enumerable });
}
return target;
};
var __toCommonJS2 = /* @__PURE__ */ ((cache) => {
return (module2, temp) => {
return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
};
})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
var GitError;
var init_git_error = __esm({
"src/lib/errors/git-error.ts"() {
GitError = class extends Error {
constructor(task, message) {
super(message);
this.task = task;
Object.setPrototypeOf(this, new.target.prototype);
}
};
}
});
var GitResponseError;
var init_git_response_error = __esm({
"src/lib/errors/git-response-error.ts"() {
init_git_error();
GitResponseError = class extends GitError {
constructor(git, message) {
super(void 0, message || String(git));
this.git = git;
}
};
}
});
var TaskConfigurationError;
var init_task_configuration_error = __esm({
"src/lib/errors/task-configuration-error.ts"() {
init_git_error();
TaskConfigurationError = class extends GitError {
constructor(message) {
super(void 0, message);
}
};
}
});
function asFunction(source) {
return typeof source === "function" ? source : NOOP;
}
function isUserFunction(source) {
return typeof source === "function" && source !== NOOP;
}
function splitOn(input, char) {
const index = input.indexOf(char);
if (index <= 0) {
return [input, ""];
}
return [input.substr(0, index), input.substr(index + 1)];
}
function first(input, offset = 0) {
return isArrayLike(input) && input.length > offset ? input[offset] : void 0;
}
function last(input, offset = 0) {
if (isArrayLike(input) && input.length > offset) {
return input[input.length - 1 - offset];
}
}
function isArrayLike(input) {
return !!(input && typeof input.length === "number");
}
function toLinesWithContent(input = "", trimmed2 = true, separator2 = "\n") {
return input.split(separator2).reduce((output, line) => {
const lineContent = trimmed2 ? line.trim() : line;
if (lineContent) {
output.push(lineContent);
}
return output;
}, []);
}
function forEachLineWithContent(input, callback) {
return toLinesWithContent(input, true).map((line) => callback(line));
}
function folderExists(path) {
return (0, import_file_exists.exists)(path, import_file_exists.FOLDER);
}
function append(target, item) {
if (Array.isArray(target)) {
if (!target.includes(item)) {
target.push(item);
}
} else {
target.add(item);
}
return item;
}
function including(target, item) {
if (Array.isArray(target) && !target.includes(item)) {
target.push(item);
}
return target;
}
function remove(target, item) {
if (Array.isArray(target)) {
const index = target.indexOf(item);
if (index >= 0) {
target.splice(index, 1);
}
} else {
target.delete(item);
}
return item;
}
function asArray(source) {
return Array.isArray(source) ? source : [source];
}
function asStringArray(source) {
return asArray(source).map(String);
}
function asNumber(source, onNaN = 0) {
if (source == null) {
return onNaN;
}
const num = parseInt(source, 10);
return isNaN(num) ? onNaN : num;
}
function prefixedArray(input, prefix) {
const output = [];
for (let i = 0, max = input.length; i < max; i++) {
output.push(prefix, input[i]);
}
return output;
}
function bufferToString(input) {
return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8");
}
function pick(source, properties) {
return Object.assign({}, ...properties.map((property) => property in source ? { [property]: source[property] } : {}));
}
function delay(duration = 0) {
return new Promise((done) => setTimeout(done, duration));
}
var NULL;
var NOOP;
var objectToString;
var init_util = __esm({
"src/lib/utils/util.ts"() {
NULL = "\0";
NOOP = () => {
};
objectToString = Object.prototype.toString.call.bind(Object.prototype.toString);
}
});
function filterType(input, filter, def) {
if (filter(input)) {
return input;
}
return arguments.length > 2 ? def : void 0;
}
function filterPrimitives(input, omit) {
return /number|string|boolean/.test(typeof input) && (!omit || !omit.includes(typeof input));
}
function filterPlainObject(input) {
return !!input && objectToString(input) === "[object Object]";
}
function filterFunction(input) {
return typeof input === "function";
}
var filterArray;
var filterString;
var filterStringArray;
var filterStringOrStringArray;
var filterHasLength;
var init_argument_filters = __esm({
"src/lib/utils/argument-filters.ts"() {
init_util();
filterArray = (input) => {
return Array.isArray(input);
};
filterString = (input) => {
return typeof input === "string";
};
filterStringArray = (input) => {
return Array.isArray(input) && input.every(filterString);
};
filterStringOrStringArray = (input) => {
return filterString(input) || Array.isArray(input) && input.every(filterString);
};
filterHasLength = (input) => {
if (input == null || "number|boolean|function".includes(typeof input)) {
return false;
}
return Array.isArray(input) || typeof input === "string" || typeof input.length === "number";
};
}
});
var ExitCodes;
var init_exit_codes = __esm({
"src/lib/utils/exit-codes.ts"() {
ExitCodes = /* @__PURE__ */ ((ExitCodes2) => {
ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS";
ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR";
ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND";
ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN";
return ExitCodes2;
})(ExitCodes || {});
}
});
var GitOutputStreams;
var init_git_output_streams = __esm({
"src/lib/utils/git-output-streams.ts"() {
GitOutputStreams = class {
constructor(stdOut, stdErr) {
this.stdOut = stdOut;
this.stdErr = stdErr;
}
asStrings() {
return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8"));
}
};
}
});
var LineParser;
var RemoteLineParser;
var init_line_parser = __esm({
"src/lib/utils/line-parser.ts"() {
LineParser = class {
constructor(regExp, useMatches) {
this.matches = [];
this.parse = (line, target) => {
this.resetMatches();
if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) {
return false;
}
return this.useMatches(target, this.prepareMatches()) !== false;
};
this._regExp = Array.isArray(regExp) ? regExp : [regExp];
if (useMatches) {
this.useMatches = useMatches;
}
}
useMatches(target, match) {
throw new Error(`LineParser:useMatches not implemented`);
}
resetMatches() {
this.matches.length = 0;
}
prepareMatches() {
return this.matches;
}
addMatch(reg, index, line) {
const matched = line && reg.exec(line);
if (matched) {
this.pushMatch(index, matched);
}
return !!matched;
}
pushMatch(_index, matched) {
this.matches.push(...matched.slice(1));
}
};
RemoteLineParser = class extends LineParser {
addMatch(reg, index, line) {
return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line);
}
pushMatch(index, matched) {
if (index > 0 || matched.length > 1) {
super.pushMatch(index, matched);
}
}
};
}
});
function createInstanceConfig(...options) {
const baseDir = process.cwd();
const config = Object.assign(__spreadValues({ baseDir }, defaultOptions), ...options.filter((o) => typeof o === "object" && o));
config.baseDir = config.baseDir || baseDir;
config.trimmed = config.trimmed === true;
return config;
}
var defaultOptions;
var init_simple_git_options = __esm({
"src/lib/utils/simple-git-options.ts"() {
defaultOptions = {
binary: "git",
maxConcurrentProcesses: 5,
config: [],
trimmed: false
};
}
});
function appendTaskOptions(options, commands = []) {
if (!filterPlainObject(options)) {
return commands;
}
return Object.keys(options).reduce((commands2, key2) => {
const value = options[key2];
if (filterPrimitives(value, ["boolean"])) {
commands2.push(key2 + "=" + value);
} else {
commands2.push(key2);
}
return commands2;
}, commands);
}
function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) {
const command = [];
for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) {
if ("string|number".includes(typeof args[i])) {
command.push(String(args[i]));
}
}
appendTaskOptions(trailingOptionsArgument(args), command);
if (!objectOnly) {
command.push(...trailingArrayArgument(args));
}
return command;
}
function trailingArrayArgument(args) {
const hasTrailingCallback = typeof last(args) === "function";
return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []);
}
function trailingOptionsArgument(args) {
const hasTrailingCallback = filterFunction(last(args));
return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject);
}
function trailingFunctionArgument(args, includeNoop = true) {
const callback = asFunction(last(args));
return includeNoop || isUserFunction(callback) ? callback : void 0;
}
var init_task_options = __esm({
"src/lib/utils/task-options.ts"() {
init_argument_filters();
init_util();
}
});
function callTaskParser(parser3, streams) {
return parser3(streams.stdOut, streams.stdErr);
}
function parseStringResponse(result, parsers12, texts, trim = true) {
asArray(texts).forEach((text) => {
for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) {
const line = (offset = 0) => {
if (i + offset >= max) {
return;
}
return lines[i + offset];
};
parsers12.some(({ parse: parse3 }) => parse3(line, result));
}
});
return result;
}
var init_task_parser = __esm({
"src/lib/utils/task-parser.ts"() {
init_util();
}
});
var utils_exports = {};
__export2(utils_exports, {
ExitCodes: () => ExitCodes,
GitOutputStreams: () => GitOutputStreams,
LineParser: () => LineParser,
NOOP: () => NOOP,
NULL: () => NULL,
RemoteLineParser: () => RemoteLineParser,
append: () => append,
appendTaskOptions: () => appendTaskOptions,
asArray: () => asArray,
asFunction: () => asFunction,
asNumber: () => asNumber,
asStringArray: () => asStringArray,
bufferToString: () => bufferToString,
callTaskParser: () => callTaskParser,
createInstanceConfig: () => createInstanceConfig,
delay: () => delay,
filterArray: () => filterArray,
filterFunction: () => filterFunction,
filterHasLength: () => filterHasLength,
filterPlainObject: () => filterPlainObject,
filterPrimitives: () => filterPrimitives,
filterString: () => filterString,
filterStringArray: () => filterStringArray,
filterStringOrStringArray: () => filterStringOrStringArray,
filterType: () => filterType,
first: () => first,
folderExists: () => folderExists,
forEachLineWithContent: () => forEachLineWithContent,
getTrailingOptions: () => getTrailingOptions,
including: () => including,
isUserFunction: () => isUserFunction,
last: () => last,
objectToString: () => objectToString,
parseStringResponse: () => parseStringResponse,
pick: () => pick,
prefixedArray: () => prefixedArray,
remove: () => remove,
splitOn: () => splitOn,
toLinesWithContent: () => toLinesWithContent,
trailingFunctionArgument: () => trailingFunctionArgument,
trailingOptionsArgument: () => trailingOptionsArgument
});
var init_utils = __esm({
"src/lib/utils/index.ts"() {
init_argument_filters();
init_exit_codes();
init_git_output_streams();
init_line_parser();
init_simple_git_options();
init_task_options();
init_task_parser();
init_util();
}
});
var check_is_repo_exports = {};
__export2(check_is_repo_exports, {
CheckRepoActions: () => CheckRepoActions,
checkIsBareRepoTask: () => checkIsBareRepoTask,
checkIsRepoRootTask: () => checkIsRepoRootTask,
checkIsRepoTask: () => checkIsRepoTask
});
function checkIsRepoTask(action) {
switch (action) {
case "bare":
return checkIsBareRepoTask();
case "root":
return checkIsRepoRootTask();
}
const commands = ["rev-parse", "--is-inside-work-tree"];
return {
commands,
format: "utf-8",
onError,
parser
};
}
function checkIsRepoRootTask() {
const commands = ["rev-parse", "--git-dir"];
return {
commands,
format: "utf-8",
onError,
parser(path) {
return /^\.(git)?$/.test(path.trim());
}
};
}
function checkIsBareRepoTask() {
const commands = ["rev-parse", "--is-bare-repository"];
return {
commands,
format: "utf-8",
onError,
parser
};
}
function isNotRepoMessage(error) {
return /(Not a git repository|Kein Git-Repository)/i.test(String(error));
}
var CheckRepoActions;
var onError;
var parser;
var init_check_is_repo = __esm({
"src/lib/tasks/check-is-repo.ts"() {
init_utils();
CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => {
CheckRepoActions2["BARE"] = "bare";
CheckRepoActions2["IN_TREE"] = "tree";
CheckRepoActions2["IS_REPO_ROOT"] = "root";
return CheckRepoActions2;
})(CheckRepoActions || {});
onError = ({ exitCode }, error, done, fail) => {
if (exitCode === 128 && isNotRepoMessage(error)) {
return done(Buffer.from("false"));
}
fail(error);
};
parser = (text) => {
return text.trim() === "true";
};
}
});
function cleanSummaryParser(dryRun, text) {
const summary = new CleanResponse(dryRun);
const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp;
toLinesWithContent(text).forEach((line) => {
const removed = line.replace(regexp, "");
summary.paths.push(removed);
(isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed);
});
return summary;
}
var CleanResponse;
var removalRegexp;
var dryRunRemovalRegexp;
var isFolderRegexp;
var init_CleanSummary = __esm({
"src/lib/responses/CleanSummary.ts"() {
init_utils();
CleanResponse = class {
constructor(dryRun) {
this.dryRun = dryRun;
this.paths = [];
this.files = [];
this.folders = [];
}
};
removalRegexp = /^[a-z]+\s*/i;
dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i;
isFolderRegexp = /\/$/;
}
});
var task_exports = {};
__export2(task_exports, {
EMPTY_COMMANDS: () => EMPTY_COMMANDS,
adhocExecTask: () => adhocExecTask,
configurationErrorTask: () => configurationErrorTask,
isBufferTask: () => isBufferTask,
isEmptyTask: () => isEmptyTask,
straightThroughBufferTask: () => straightThroughBufferTask,
straightThroughStringTask: () => straightThroughStringTask
});
function adhocExecTask(parser3) {
return {
commands: EMPTY_COMMANDS,
format: "empty",
parser: parser3
};
}
function configurationErrorTask(error) {
return {
commands: EMPTY_COMMANDS,
format: "empty",
parser() {
throw typeof error === "string" ? new TaskConfigurationError(error) : error;
}
};
}
function straightThroughStringTask(commands, trimmed2 = false) {
return {
commands,
format: "utf-8",
parser(text) {
return trimmed2 ? String(text).trim() : text;
}
};
}
function straightThroughBufferTask(commands) {
return {
commands,
format: "buffer",
parser(buffer) {
return buffer;
}
};
}
function isBufferTask(task) {
return task.format === "buffer";
}
function isEmptyTask(task) {
return task.format === "empty" || !task.commands.length;
}
var EMPTY_COMMANDS;
var init_task = __esm({
"src/lib/tasks/task.ts"() {
init_task_configuration_error();
EMPTY_COMMANDS = [];
}
});
var clean_exports = {};
__export2(clean_exports, {
CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE,
CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED,
CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION,
CleanOptions: () => CleanOptions,
cleanTask: () => cleanTask,
cleanWithOptionsTask: () => cleanWithOptionsTask,
isCleanOptionsArray: () => isCleanOptionsArray
});
function cleanWithOptionsTask(mode, customArgs) {
const { cleanMode, options, valid } = getCleanOptions(mode);
if (!cleanMode) {
return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED);
}
if (!valid.options) {
return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode));
}
options.push(...customArgs);
if (options.some(isInteractiveMode)) {
return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE);
}
return cleanTask(cleanMode, options);
}
function cleanTask(mode, customArgs) {
const commands = ["clean", `-${mode}`, ...customArgs];
return {
commands,
format: "utf-8",
parser(text) {
return cleanSummaryParser(mode === "n", text);
}
};
}
function isCleanOptionsArray(input) {
return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test));
}
function getCleanOptions(input) {
let cleanMode;
let options = [];
let valid = { cleanMode: false, options: true };
input.replace(/[^a-z]i/g, "").split("").forEach((char) => {
if (isCleanMode(char)) {
cleanMode = char;
valid.cleanMode = true;
} else {
valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`);
}
});
return {
cleanMode,
options,
valid
};
}
function isCleanMode(cleanMode) {
return cleanMode === "f" || cleanMode === "n";
}
function isKnownOption(option) {
return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1));
}
function isInteractiveMode(option) {
if (/^-[^\-]/.test(option)) {
return option.indexOf("i") > 0;
}
return option === "--interactive";
}
var CONFIG_ERROR_INTERACTIVE_MODE;
var CONFIG_ERROR_MODE_REQUIRED;
var CONFIG_ERROR_UNKNOWN_OPTION;
var CleanOptions;
var CleanOptionValues;
var init_clean = __esm({
"src/lib/tasks/clean.ts"() {
init_CleanSummary();
init_utils();
init_task();
CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported";
CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required';
CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: ";
CleanOptions = /* @__PURE__ */ ((CleanOptions2) => {
CleanOptions2["DRY_RUN"] = "n";
CleanOptions2["FORCE"] = "f";
CleanOptions2["IGNORED_INCLUDED"] = "x";
CleanOptions2["IGNORED_ONLY"] = "X";
CleanOptions2["EXCLUDING"] = "e";
CleanOptions2["QUIET"] = "q";
CleanOptions2["RECURSIVE"] = "d";
return CleanOptions2;
})(CleanOptions || {});
CleanOptionValues = /* @__PURE__ */ new Set([
"i",
...asStringArray(Object.values(CleanOptions))
]);
}
});
function configListParser(text) {
const config = new ConfigList();
for (const item of configParser(text)) {
config.addValue(item.file, String(item.key), item.value);
}
return config;
}
function configGetParser(text, key2) {
let value = null;
const values = [];
const scopes = /* @__PURE__ */ new Map();
for (const item of configParser(text, key2)) {
if (item.key !== key2) {
continue;
}
values.push(value = item.value);
if (!scopes.has(item.file)) {
scopes.set(item.file, []);
}
scopes.get(item.file).push(value);
}
return {
key: key2,
paths: Array.from(scopes.keys()),
scopes,
value,
values
};
}
function configFilePath(filePath) {
return filePath.replace(/^(file):/, "");
}
function* configParser(text, requestedKey = null) {
const lines = text.split("\0");
for (let i = 0, max = lines.length - 1; i < max; ) {
const file = configFilePath(lines[i++]);
let value = lines[i++];
let key2 = requestedKey;
if (value.includes("\n")) {
const line = splitOn(value, "\n");
key2 = line[0];
value = line[1];
}
yield { file, key: key2, value };
}
}
var ConfigList;
var init_ConfigList = __esm({
"src/lib/responses/ConfigList.ts"() {
init_utils();
ConfigList = class {
constructor() {
this.files = [];
this.values = /* @__PURE__ */ Object.create(null);
}
get all() {
if (!this._all) {
this._all = this.files.reduce((all, file) => {
return Object.assign(all, this.values[file]);
}, {});
}
return this._all;
}
addFile(file) {
if (!(file in this.values)) {
const latest = last(this.files);
this.values[file] = latest ? Object.create(this.values[latest]) : {};
this.files.push(file);
}
return this.values[file];
}
addValue(file, key2, value) {
const values = this.addFile(file);
if (!values.hasOwnProperty(key2)) {
values[key2] = value;
} else if (Array.isArray(values[key2])) {
values[key2].push(value);
} else {
values[key2] = [values[key2], value];
}
this._all = void 0;
}
};
}
});
function asConfigScope(scope, fallback) {
if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) {
return scope;
}
return fallback;
}
function addConfigTask(key2, value, append2, scope) {
const commands = ["config", `--${scope}`];
if (append2) {
commands.push("--add");
}
commands.push(key2, value);
return {
commands,
format: "utf-8",
parser(text) {
return text;
}
};
}
function getConfigTask(key2, scope) {
const commands = ["config", "--null", "--show-origin", "--get-all", key2];
if (scope) {
commands.splice(1, 0, `--${scope}`);
}
return {
commands,
format: "utf-8",
parser(text) {
return configGetParser(text, key2);
}
};
}
function listConfigTask(scope) {
const commands = ["config", "--list", "--show-origin", "--null"];
if (scope) {
commands.push(`--${scope}`);
}
return {
commands,
format: "utf-8",
parser(text) {
return configListParser(text);
}
};
}
function config_default() {
return {
addConfig(key2, value, ...rest) {
return this._runTask(addConfigTask(key2, value, rest[0] === true, asConfigScope(
rest[1],
"local"
/* local */
)), trailingFunctionArgument(arguments));
},
getConfig(key2, scope) {
return this._runTask(getConfigTask(key2, asConfigScope(scope, void 0)), trailingFunctionArgument(arguments));
},
listConfig(...rest) {
return this._runTask(listConfigTask(asConfigScope(rest[0], void 0)), trailingFunctionArgument(arguments));
}
};
}
var GitConfigScope;
var init_config = __esm({
"src/lib/tasks/config.ts"() {
init_ConfigList();
init_utils();
GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => {
GitConfigScope2["system"] = "system";
GitConfigScope2["global"] = "global";
GitConfigScope2["local"] = "local";
GitConfigScope2["worktree"] = "worktree";
return GitConfigScope2;
})(GitConfigScope || {});
}
});
function grepQueryBuilder(...params) {
return new GrepQuery().param(...params);
}
function parseGrep(grep) {
const paths = /* @__PURE__ */ new Set();
const results = {};
forEachLineWithContent(grep, (input) => {
const [path, line, preview] = input.split(NULL);
paths.add(path);
(results[path] = results[path] || []).push({
line: asNumber(line),
path,
preview
});
});
return {
paths,
results
};
}
function grep_default() {
return {
grep(searchTerm) {
const then = trailingFunctionArgument(arguments);
const options = getTrailingOptions(arguments);
for (const option of disallowedOptions) {
if (options.includes(option)) {
return this._runTask(configurationErrorTask(`git.grep: use of "${option}" is not supported.`), then);
}
}
if (typeof searchTerm === "string") {
searchTerm = grepQueryBuilder().param(searchTerm);
}
const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm];
return this._runTask({
commands,
format: "utf-8",
parser(stdOut) {
return parseGrep(stdOut);
}
}, then);
}
};
}
var disallowedOptions;
var Query;
var _a;
var GrepQuery;
var init_grep = __esm({
"src/lib/tasks/grep.ts"() {
init_utils();
init_task();
disallowedOptions = ["-h"];
Query = Symbol("grepQuery");
GrepQuery = class {
constructor() {
this[_a] = [];
}
*[(_a = Query, Symbol.iterator)]() {
for (const query of this[Query]) {
yield query;
}
}
and(...and) {
and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")");
return this;
}
param(...param) {
this[Query].push(...prefixedArray(param, "-e"));
return this;
}
};
}
});
var reset_exports = {};
__export2(reset_exports, {
ResetMode: () => ResetMode,
getResetMode: () => getResetMode,
resetTask: () => resetTask
});
function resetTask(mode, customArgs) {
const commands = ["reset"];
if (isValidResetMode(mode)) {
commands.push(`--${mode}`);
}
commands.push(...customArgs);
return straightThroughStringTask(commands);
}
function getResetMode(mode) {
if (isValidResetMode(mode)) {
return mode;
}
switch (typeof mode) {
case "string":
case "undefined":
return "soft";
}
return;
}
function isValidResetMode(mode) {
return ResetModes.includes(mode);
}
var ResetMode;
var ResetModes;
var init_reset = __esm({
"src/lib/tasks/reset.ts"() {
init_task();
ResetMode = /* @__PURE__ */ ((ResetMode2) => {
ResetMode2["MIXED"] = "mixed";
ResetMode2["SOFT"] = "soft";
ResetMode2["HARD"] = "hard";
ResetMode2["MERGE"] = "merge";
ResetMode2["KEEP"] = "keep";
return ResetMode2;
})(ResetMode || {});
ResetModes = Array.from(Object.values(ResetMode));
}
});
function createLog() {
return (0, import_debug.default)("simple-git");
}
function prefixedLogger(to, prefix, forward) {
if (!prefix || !String(prefix).replace(/\s*/, "")) {
return !forward ? to : (message, ...args) => {
to(message, ...args);
forward(message, ...args);
};
}
return (message, ...args) => {
to(`%s ${message}`, prefix, ...args);
if (forward) {
forward(message, ...args);
}
};
}
function childLoggerName(name, childDebugger, { namespace: parentNamespace }) {
if (typeof name === "string") {
return name;
}
const childNamespace = childDebugger && childDebugger.namespace || "";
if (childNamespace.startsWith(parentNamespace)) {
return childNamespace.substr(parentNamespace.length + 1);
}
return childNamespace || parentNamespace;
}
function createLogger(label, verbose, initialStep, infoDebugger = createLog()) {
const labelPrefix = label && `[${label}]` || "";
const spawned = [];
const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose;
const key2 = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger);
return step(initialStep);
function sibling(name, initial) {
return append(spawned, createLogger(label, key2.replace(/^[^:]+/, name), initial, infoDebugger));
}
function step(phase) {
const stepPrefix = phase && `[${phase}]` || "";
const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2);
return Object.assign(debugDebugger ? debug2 : info, {
label,
sibling,
info,
step
});
}
}
var init_git_logger = __esm({
"src/lib/git-logger.ts"() {
init_utils();
import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-");
import_debug.default.formatters.B = (value) => {
if (Buffer.isBuffer(value)) {
return value.toString("utf8");
}
return objectToString(value);
};
}
});
var _TasksPendingQueue;
var TasksPendingQueue;
var init_tasks_pending_queue = __esm({
"src/lib/runners/tasks-pending-queue.ts"() {
init_git_error();
init_git_logger();
_TasksPendingQueue = class {
constructor(logLabel = "GitExecutor") {
this.logLabel = logLabel;
this._queue = /* @__PURE__ */ new Map();
}
withProgress(task) {
return this._queue.get(task);
}
createProgress(task) {
const name = _TasksPendingQueue.getName(task.commands[0]);
const logger = createLogger(this.logLabel, name);
return {
task,
logger,
name
};
}
push(task) {
const progress = this.createProgress(task);
progress.logger("Adding task to the queue, commands = %o", task.commands);
this._queue.set(task, progress);
return progress;
}
fatal(err) {
for (const [task, { logger }] of Array.from(this._queue.entries())) {
if (task === err.task) {
logger.info(`Failed %o`, err);
logger(`Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`);
} else {
logger.info(`A fatal exception occurred in a previous task, the queue has been purged: %o`, err.message);
}
this.complete(task);
}
if (this._queue.size !== 0) {
throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`);
}
}
complete(task) {
const progress = this.withProgress(task);
if (progress) {
this._queue.delete(task);
}
}
attempt(task) {
const progress = this.withProgress(task);
if (!progress) {
throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task");
}
progress.logger("Starting task");
return progress;
}
static getName(name = "empty") {
return `task:${name}:${++_TasksPendingQueue.counter}`;
}
};
TasksPendingQueue = _TasksPendingQueue;
TasksPendingQueue.counter = 0;
}
});
function pluginContext(task, commands) {
return {
method: first(task.commands) || "",
commands
};
}
function onErrorReceived(target, logger) {
return (err) => {
logger(`[ERROR] child process exception %o`, err);
target.push(Buffer.from(String(err.stack), "ascii"));
};
}
function onDataReceived(target, name, logger, output) {
return (buffer) => {
logger(`%s received %L bytes`, name, buffer);
output(`%B`, buffer);
target.push(buffer);
};
}
var GitExecutorChain;
var init_git_executor_chain = __esm({
"src/lib/runners/git-executor-chain.ts"() {
init_git_error();
init_task();
init_utils();
init_tasks_pending_queue();
GitExecutorChain = class {
constructor(_executor, _scheduler, _plugins) {
this._executor = _executor;
this._scheduler = _scheduler;
this._plugins = _plugins;
this._chain = Promise.resolve();
this._queue = new TasksPendingQueue();
}
get binary() {
return this._executor.binary;
}
get cwd() {
return this._cwd || this._executor.cwd;
}
set cwd(cwd) {
this._cwd = cwd;
}
get env() {
return this._executor.env;
}
get outputHandler() {
return this._executor.outputHandler;
}
chain() {
return this;
}
push(task) {
this._queue.push(task);
return this._chain = this._chain.then(() => this.attemptTask(task));
}
attemptTask(task) {
return __async(this, null, function* () {
const onScheduleComplete = yield this._scheduler.next();
const onQueueComplete = () => this._queue.complete(task);
try {
const { logger } = this._queue.attempt(task);
return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger);
} catch (e) {
throw this.onFatalException(task, e);
} finally {
onQueueComplete();
onScheduleComplete();
}
});
}
onFatalException(task, e) {
const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e));
this._chain = Promise.resolve();
this._queue.fatal(gitError);
return gitError;
}
attemptRemoteTask(task, logger) {
return __async(this, null, function* () {
const args = this._plugins.exec("spawn.args", [...task.commands], pluginContext(task, task.commands));
const raw = yield this.gitResponse(task, this.binary, args, this.outputHandler, logger.step("SPAWN"));
const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE"));
logger(`passing response to task's parser as a %s`, task.format);
if (isBufferTask(task)) {
return callTaskParser(task.parser, outputStreams);
}
return callTaskParser(task.parser, outputStreams.asStrings());
});
}
attemptEmptyTask(task, logger) {
return __async(this, null, function* () {
logger(`empty task bypassing child process to call to task's parser`);
return task.parser(this);
});
}
handleTaskData(task, args, result, logger) {
const { exitCode, rejection, stdOut, stdErr } = result;
return new Promise((done, fail) => {
logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode);
const { error } = this._plugins.exec("task.error", { error: rejection }, __spreadValues(__spreadValues({}, pluginContext(task, args)), result));
if (error && task.onError) {
logger.info(`exitCode=%s handling with custom error handler`);
return task.onError(result, error, (newStdOut) => {
logger.info(`custom error handler treated as success`);
logger(`custom error returned a %s`, objectToString(newStdOut));
done(new GitOutputStreams(Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, Buffer.concat(stdErr)));
}, fail);
}
if (error) {
logger.info(`handling as error: exitCode=%s stdErr=%s rejection=%o`, exitCode, stdErr.length, rejection);
return fail(error);
}
logger.info(`retrieving task output complete`);
done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));
});
}
gitResponse(task, command, args, outputHandler, logger) {
return __async(this, null, function* () {
const outputLogger = logger.sibling("output");
const spawnOptions = this._plugins.exec("spawn.options", {
cwd: this.cwd,
env: this.env,
windowsHide: true
}, pluginContext(task, task.commands));
return new Promise((done) => {
const stdOut = [];
const stdErr = [];
logger.info(`%s %o`, command, args);
logger("%O", spawnOptions);
let rejection = this._beforeSpawn(task, args);
if (rejection) {
return done({
stdOut,
stdErr,
exitCode: 9901,
rejection
});
}
this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), {
kill(reason) {
rejection = reason || rejection;
}
}));
const spawned = (0, import_child_process.spawn)(command, args, spawnOptions);
spawned.stdout.on("data", onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut")));
spawned.stderr.on("data", onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr")));
spawned.on("error", onErrorReceived(stdErr, logger));
if (outputHandler) {
logger(`Passing child process stdOut/stdErr to custom outputHandler`);
outputHandler(command, spawned.stdout, spawned.stderr, [...args]);
}
this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), {
spawned,
close(exitCode, reason) {
done({
stdOut,
stdErr,
exitCode,
rejection: rejection || reason
});
},
kill(reason) {
if (spawned.killed) {
return;
}
rejection = reason;
spawned.kill("SIGINT");
}
}));
});
});
}
_beforeSpawn(task, args) {
let rejection;
this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), {
kill(reason) {
rejection = reason || rejection;
}
}));
return rejection;
}
};
}
});
var git_executor_exports = {};
__export2(git_executor_exports, {
GitExecutor: () => GitExecutor
});
var GitExecutor;
var init_git_executor = __esm({
"src/lib/runners/git-executor.ts"() {
init_git_executor_chain();
GitExecutor = class {
constructor(binary = "git", cwd, _scheduler, _plugins) {
this.binary = binary;
this.cwd = cwd;
this._scheduler = _scheduler;
this._plugins = _plugins;
this._chain = new GitExecutorChain(this, this._scheduler, this._plugins);
}
chain() {
return new GitExecutorChain(this, this._scheduler, this._plugins);
}
push(task) {
return this._chain.push(task);
}
};
}
});
function taskCallback(task, response, callback = NOOP) {
const onSuccess = (data) => {
callback(null, data);
};
const onError2 = (err) => {
if ((err == null ? void 0 : err.task) === task) {
callback(err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err, void 0);
}
};
response.then(onSuccess, onError2);
}
function addDeprecationNoticeToError(err) {
let log = (name) => {
console.warn(`simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`);
log = NOOP;
};
return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {}));
function descriptorReducer(all, name) {
if (name in err) {
return all;
}
all[name] = {
enumerable: false,
configurable: false,
get() {
log(name);
return err.git[name];
}
};
return all;
}
}
var init_task_callback = __esm({
"src/lib/task-callback.ts"() {
init_git_response_error();
init_utils();
}
});
function changeWorkingDirectoryTask(directory, root) {
return adhocExecTask((instance) => {
if (!folderExists(directory)) {
throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`);
}
return (root || instance).cwd = directory;
});
}
var init_change_working_directory = __esm({
"src/lib/tasks/change-working-directory.ts"() {
init_utils();
init_task();
}
});
function checkoutTask(args) {
const commands = ["checkout", ...args];
if (commands[1] === "-b" && commands.includes("-B")) {
commands[1] = remove(commands, "-B");
}
return straightThroughStringTask(commands);
}
function checkout_default() {
return {
checkout() {
return this._runTask(checkoutTask(getTrailingOptions(arguments, 1)), trailingFunctionArgument(arguments));
},
checkoutBranch(branchName, startPoint) {
return this._runTask(checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments));
},
checkoutLocalBranch(branchName) {
return this._runTask(checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments));
}
};
}
var init_checkout = __esm({
"src/lib/tasks/checkout.ts"() {
init_utils();
init_task();
}
});
function parseCommitResult(stdOut) {
const result = {
author: null,
branch: "",
commit: "",
root: false,
summary: {
changes: 0,
insertions: 0,
deletions: 0
}
};
return parseStringResponse(result, parsers, stdOut);
}
var parsers;
var init_parse_commit = __esm({
"src/lib/parsers/parse-commit.ts"() {
init_utils();
parsers = [
new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => {
result.branch = branch;
result.commit = commit;
result.root = !!root;
}),
new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => {
const parts = author.split("<");
const email = parts.pop();
if (!email || !email.includes("@")) {
return;
}
result.author = {
email: email.substr(0, email.length - 1),
name: parts.join("<").trim()
};
}),
new LineParser(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g, (result, [changes, insertions, deletions]) => {
result.summary.changes = parseInt(changes, 10) || 0;
result.summary.insertions = parseInt(insertions, 10) || 0;
result.summary.deletions = parseInt(deletions, 10) || 0;
}),
new LineParser(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/, (result, [changes, lines, direction]) => {
result.summary.changes = parseInt(changes, 10) || 0;
const count = parseInt(lines, 10) || 0;
if (direction === "-") {
result.summary.deletions = count;
} else if (direction === "+") {
result.summary.insertions = count;
}
})
];
}
});
function commitTask(message, files, customArgs) {
const commands = [
"-c",
"core.abbrev=40",
"commit",
...prefixedArray(message, "-m"),
...files,
...customArgs
];
return {
commands,
format: "utf-8",
parser: parseCommitResult
};
}
function commit_default() {
return {
commit(message, ...rest) {
const next = trailingFunctionArgument(arguments);
const task = rejectDeprecatedSignatures(message) || commitTask(asArray(message), asArray(filterType(rest[0], filterStringOrStringArray, [])), [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]);
return this._runTask(task, next);
}
};
function rejectDeprecatedSignatures(message) {
return !filterStringOrStringArray(message) && configurationErrorTask(`git.commit: requires the commit message to be supplied as a string/string[]`);
}
}
var init_commit = __esm({
"src/lib/tasks/commit.ts"() {
init_parse_commit();
init_utils();
init_task();
}
});
function hashObjectTask(filePath, write) {
const commands = ["hash-object", filePath];
if (write) {
commands.push("-w");
}
return straightThroughStringTask(commands, true);
}
var init_hash_object = __esm({
"src/lib/tasks/hash-object.ts"() {
init_task();
}
});
function parseInit(bare, path, text) {
const response = String(text).trim();
let result;
if (result = initResponseRegex.exec(response)) {
return new InitSummary(bare, path, false, result[1]);
}
if (result = reInitResponseRegex.exec(response)) {
return new InitSummary(bare, path, true, result[1]);
}
let gitDir = "";
const tokens = response.split(" ");
while (tokens.length) {
const token = tokens.shift();
if (token === "in") {
gitDir = tokens.join(" ");
break;
}
}
return new InitSummary(bare, path, /^re/i.test(response), gitDir);
}
var InitSummary;
var initResponseRegex;
var reInitResponseRegex;
var init_InitSummary = __esm({
"src/lib/responses/InitSummary.ts"() {
InitSummary = class {
constructor(bare, path, existing, gitDir) {
this.bare = bare;
this.path = path;
this.existing = existing;
this.gitDir = gitDir;
}
};
initResponseRegex = /^Init.+ repository in (.+)$/;
reInitResponseRegex = /^Rein.+ in (.+)$/;
}
});
function hasBareCommand(command) {
return command.includes(bareCommand);
}
function initTask(bare = false, path, customArgs) {
const commands = ["init", ...customArgs];
if (bare && !hasBareCommand(commands)) {
commands.splice(1, 0, bareCommand);
}
return {
commands,
format: "utf-8",
parser(text) {
return parseInit(commands.includes("--bare"), path, text);
}
};
}
var bareCommand;
var init_init = __esm({
"src/lib/tasks/init.ts"() {
init_InitSummary();
bareCommand = "--bare";
}
});
function logFormatFromCommand(customArgs) {
for (let i = 0; i < customArgs.length; i++) {
const format = logFormatRegex.exec(customArgs[i]);
if (format) {
return `--${format[1]}`;
}
}
return "";
}
function isLogFormat(customArg) {
return logFormatRegex.test(customArg);
}
var logFormatRegex;
var init_log_format = __esm({
"src/lib/args/log-format.ts"() {
logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/;
}
});
var DiffSummary;
var init_DiffSummary = __esm({
"src/lib/responses/DiffSummary.ts"() {
DiffSummary = class {
constructor() {
this.changed = 0;
this.deletions = 0;
this.insertions = 0;
this.files = [];
}
};
}
});
function getDiffParser(format = "") {
const parser3 = diffSummaryParsers[format];
return (stdOut) => parseStringResponse(new DiffSummary(), parser3, stdOut, false);
}
var statParser;
var numStatParser;
var nameOnlyParser;
var nameStatusParser;
var diffSummaryParsers;
var init_parse_diff_summary = __esm({
"src/lib/parsers/parse-diff-summary.ts"() {
init_log_format();
init_DiffSummary();
init_utils();
statParser = [
new LineParser(/(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, (result, [file, changes, alterations = ""]) => {
result.files.push({
file: file.trim(),
changes: asNumber(changes),
insertions: alterations.replace(/[^+]/g, "").length,
deletions: alterations.replace(/[^-]/g, "").length,
binary: false
});
}),
new LineParser(/(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/, (result, [file, before, after]) => {
result.files.push({
file: file.trim(),
before: asNumber(before),
after: asNumber(after),
binary: true
});
}),
new LineParser(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/, (result, [changed, summary]) => {
const inserted = /(\d+) i/.exec(summary);
const deleted = /(\d+) d/.exec(summary);
result.changed = asNumber(changed);
result.insertions = asNumber(inserted == null ? void 0 : inserted[1]);
result.deletions = asNumber(deleted == null ? void 0 : deleted[1]);
})
];
numStatParser = [
new LineParser(/(\d+)\t(\d+)\t(.+)$/, (result, [changesInsert, changesDelete, file]) => {
const insertions = asNumber(changesInsert);
const deletions = asNumber(changesDelete);
result.changed++;
result.insertions += insertions;
result.deletions += deletions;
result.files.push({
file,
changes: insertions + deletions,
insertions,
deletions,
binary: false
});
}),
new LineParser(/-\t-\t(.+)$/, (result, [file]) => {
result.changed++;
result.files.push({
file,
after: 0,
before: 0,
binary: true
});
})
];
nameOnlyParser = [
new LineParser(/(.+)$/, (result, [file]) => {
result.changed++;
result.files.push({
file,
changes: 0,
insertions: 0,
deletions: 0,
binary: false
});
})
];
nameStatusParser = [
new LineParser(/([ACDMRTUXB])\s*(.+)$/, (result, [_status, file]) => {
result.changed++;
result.files.push({
file,
changes: 0,
insertions: 0,
deletions: 0,
binary: false
});
})
];
diffSummaryParsers = {
[
""
/* NONE */
]: statParser,
[
"--stat"
/* STAT */
]: statParser,
[
"--numstat"
/* NUM_STAT */
]: numStatParser,
[
"--name-status"
/* NAME_STATUS */
]: nameStatusParser,
[
"--name-only"
/* NAME_ONLY */
]: nameOnlyParser
};
}
});
function lineBuilder(tokens, fields) {
return fields.reduce((line, field, index) => {
line[field] = tokens[index] || "";
return line;
}, /* @__PURE__ */ Object.create({ diff: null }));
}
function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "") {
const parseDiffResult = getDiffParser(logFormat);
return function(stdOut) {
const all = toLinesWithContent(stdOut, true, START_BOUNDARY).map(function(item) {
const lineDetail = item.trim().split(COMMIT_BOUNDARY);
const listLogLine = lineBuilder(lineDetail[0].trim().split(splitter), fields);
if (lineDetail.length > 1 && !!lineDetail[1].trim()) {
listLogLine.diff = parseDiffResult(lineDetail[1]);
}
return listLogLine;
});
return {
all,
latest: all.length && all[0] || null,
total: all.length
};
};
}
var START_BOUNDARY;
var COMMIT_BOUNDARY;
var SPLITTER;
var defaultFieldNames;
var init_parse_list_log_summary = __esm({
"src/lib/parsers/parse-list-log-summary.ts"() {
init_utils();
init_parse_diff_summary();
init_log_format();
START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 ";
COMMIT_BOUNDARY = " \xF2\xF2";
SPLITTER = " \xF2 ";
defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"];
}
});
var diff_exports = {};
__export2(diff_exports, {
diffSummaryTask: () => diffSummaryTask,
validateLogFormatConfig: () => validateLogFormatConfig
});
function diffSummaryTask(customArgs) {
let logFormat = logFormatFromCommand(customArgs);
const commands = ["diff"];
if (logFormat === "") {
logFormat = "--stat";
commands.push("--stat=4096");
}
commands.push(...customArgs);
return validateLogFormatConfig(commands) || {
commands,
format: "utf-8",
parser: getDiffParser(logFormat)
};
}
function validateLogFormatConfig(customArgs) {
const flags = customArgs.filter(isLogFormat);
if (flags.length > 1) {
return configurationErrorTask(`Summary flags are mutually exclusive - pick one of ${flags.join(",")}`);
}
if (flags.length && customArgs.includes("-z")) {
return configurationErrorTask(`Summary flag ${flags} parsing is not compatible with null termination option '-z'`);
}
}
var init_diff = __esm({
"src/lib/tasks/diff.ts"() {
init_log_format();
init_parse_diff_summary();
init_task();
}
});
function prettyFormat(format, splitter) {
const fields = [];
const formatStr = [];
Object.keys(format).forEach((field) => {
fields.push(field);
formatStr.push(String(format[field]));
});
return [fields, formatStr.join(splitter)];
}
function userOptions(input) {
return Object.keys(input).reduce((out, key2) => {
if (!(key2 in excludeOptions)) {
out[key2] = input[key2];
}
return out;
}, {});
}
function parseLogOptions(opt = {}, customArgs = []) {
const splitter = filterType(opt.splitter, filterString, SPLITTER);
const format = !filterPrimitives(opt.format) && opt.format ? opt.format : {
hash: "%H",
date: opt.strictDate === false ? "%ai" : "%aI",
message: "%s",
refs: "%D",
body: opt.multiLine ? "%B" : "%b",
author_name: opt.mailMap !== false ? "%aN" : "%an",
author_email: opt.mailMap !== false ? "%aE" : "%ae"
};
const [fields, formatStr] = prettyFormat(format, splitter);
const suffix = [];
const command = [
`--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`,
...customArgs
];
const maxCount = opt.n || opt["max-count"] || opt.maxCount;
if (maxCount) {
command.push(`--max-count=${maxCount}`);
}
if (opt.from || opt.to) {
const rangeOperator = opt.symmetric !== false ? "..." : "..";
suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`);
}
if (filterString(opt.file)) {
suffix.push("--follow", opt.file);
}
appendTaskOptions(userOptions(opt), command);
return {
fields,
splitter,
commands: [...command, ...suffix]
};
}
function logTask(splitter, fields, customArgs) {
const parser3 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs));
return {
commands: ["log", ...customArgs],
format: "utf-8",
parser: parser3
};
}
function log_default() {
return {
log(...rest) {
const next = trailingFunctionArgument(arguments);
const options = parseLogOptions(trailingOptionsArgument(arguments), filterType(arguments[0], filterArray));
const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options);
return this._runTask(task, next);
}
};
function createLogTask(options) {
return logTask(options.splitter, options.fields, options.commands);
}
function rejectDeprecatedSignatures(from, to) {
return filterString(from) && filterString(to) && configurationErrorTask(`git.log(string, string) should be replaced with git.log({ from: string, to: string })`);
}
}
var excludeOptions;
var init_log = __esm({
"src/lib/tasks/log.ts"() {
init_log_format();
init_parse_list_log_summary();
init_utils();
init_task();
init_diff();
excludeOptions = /* @__PURE__ */ ((excludeOptions2) => {
excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty";
excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count";
excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount";
excludeOptions2[excludeOptions2["n"] = 3] = "n";
excludeOptions2[excludeOptions2["file"] = 4] = "file";
excludeOptions2[excludeOptions2["format"] = 5] = "format";
excludeOptions2[excludeOptions2["from"] = 6] = "from";
excludeOptions2[excludeOptions2["to"] = 7] = "to";
excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter";
excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric";
excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap";
excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine";
excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate";
return excludeOptions2;
})(excludeOptions || {});
}
});
var MergeSummaryConflict;
var MergeSummaryDetail;
var init_MergeSummary = __esm({
"src/lib/responses/MergeSummary.ts"() {
MergeSummaryConflict = class {
constructor(reason, file = null, meta) {
this.reason = reason;
this.file = file;
this.meta = meta;
}
toString() {
return `${this.file}:${this.reason}`;
}
};
MergeSummaryDetail = class {
constructor() {
this.conflicts = [];
this.merges = [];
this.result = "success";
}
get failed() {
return this.conflicts.length > 0;
}
get reason() {
return this.result;
}
toString() {
if (this.conflicts.length) {
return `CONFLICTS: ${this.conflicts.join(", ")}`;
}
return "OK";
}
};
}
});
var PullSummary;
var PullFailedSummary;
var init_PullSummary = __esm({
"src/lib/responses/PullSummary.ts"() {
PullSummary = class {
constructor() {
this.remoteMessages = {
all: []
};
this.created = [];
this.deleted = [];
this.files = [];
this.deletions = {};
this.insertions = {};
this.summary = {
changes: 0,
deletions: 0,
insertions: 0
};
}
};
PullFailedSummary = class {
constructor() {
this.remote = "";
this.hash = {
local: "",
remote: ""
};
this.branch = {
local: "",
remote: ""
};
this.message = "";
}
toString() {
return this.message;
}
};
}
});
function objectEnumerationResult(remoteMessages) {
return remoteMessages.objects = remoteMessages.objects || {
compressing: 0,
counting: 0,
enumerating: 0,
packReused: 0,
reused: { count: 0, delta: 0 },
total: { count: 0, delta: 0 }
};
}
function asObjectCount(source) {
const count = /^\s*(\d+)/.exec(source);
const delta = /delta (\d+)/i.exec(source);
return {
count: asNumber(count && count[1] || "0"),
delta: asNumber(delta && delta[1] || "0")
};
}
var remoteMessagesObjectParsers;
var init_parse_remote_objects = __esm({
"src/lib/parsers/parse-remote-objects.ts"() {
init_utils();
remoteMessagesObjectParsers = [
new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, (result, [action, count]) => {
const key2 = action.toLowerCase();
const enumeration = objectEnumerationResult(result.remoteMessages);
Object.assign(enumeration, { [key2]: asNumber(count) });
}),
new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i, (result, [action, count]) => {
const key2 = action.toLowerCase();
const enumeration = objectEnumerationResult(result.remoteMessages);
Object.assign(enumeration, { [key2]: asNumber(count) });
}),
new RemoteLineParser(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i, (result, [total, reused, packReused]) => {
const objects = objectEnumerationResult(result.remoteMessages);
objects.total = asObjectCount(total);
objects.reused = asObjectCount(reused);
objects.packReused = asNumber(packReused);
})
];
}
});
function parseRemoteMessages(_stdOut, stdErr) {
return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr);
}
var parsers2;
var RemoteMessageSummary;
var init_parse_remote_messages = __esm({
"src/lib/parsers/parse-remote-messages.ts"() {
init_utils();
init_parse_remote_objects();
parsers2 = [
new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => {
result.remoteMessages.all.push(text.trim());
return false;
}),
...remoteMessagesObjectParsers,
new RemoteLineParser([/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/], (result, [pullRequestUrl]) => {
result.remoteMessages.pullRequestUrl = pullRequestUrl;
}),
new RemoteLineParser([/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/], (result, [count, summary, url]) => {
result.remoteMessages.vulnerabilities = {
count: asNumber(count),
summary,
url
};
})
];
RemoteMessageSummary = class {
constructor() {
this.all = [];
}
};
}
});
function parsePullErrorResult(stdOut, stdErr) {
const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]);
return pullError.message && pullError;
}
var FILE_UPDATE_REGEX;
var SUMMARY_REGEX;
var ACTION_REGEX;
var parsers3;
var errorParsers;
var parsePullDetail;
var parsePullResult;
var init_parse_pull = __esm({
"src/lib/parsers/parse-pull.ts"() {
init_PullSummary();
init_utils();
init_parse_remote_messages();
FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/;
SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/;
ACTION_REGEX = /^(create|delete) mode \d+ (.+)/;
parsers3 = [
new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => {
result.files.push(file);
if (insertions) {
result.insertions[file] = insertions.length;
}
if (deletions) {
result.deletions[file] = deletions.length;
}
}),
new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => {
if (insertions !== void 0 || deletions !== void 0) {
result.summary.changes = +changes || 0;
result.summary.insertions = +insertions || 0;
result.summary.deletions = +deletions || 0;
return true;
}
return false;
}),
new LineParser(ACTION_REGEX, (result, [action, file]) => {
append(result.files, file);
append(action === "create" ? result.created : result.deleted, file);
})
];
errorParsers = [
new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)),
new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)),
new LineParser(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/, (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => {
result.branch.local = branchLocal;
result.hash.local = hashLocal;
result.branch.remote = branchRemote;
result.hash.remote = hashRemote;
})
];
parsePullDetail = (stdOut, stdErr) => {
return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]);
};
parsePullResult = (stdOut, stdErr) => {
return Object.assign(new PullSummary(), parsePullDetail(stdOut, stdErr), parseRemoteMessages(stdOut, stdErr));
};
}
});
var parsers4;
var parseMergeResult;
var parseMergeDetail;
var init_parse_merge = __esm({
"src/lib/parsers/parse-merge.ts"() {
init_MergeSummary();
init_utils();
init_parse_pull();
parsers4 = [
new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => {
summary.merges.push(autoMerge);
}),
new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => {
summary.conflicts.push(new MergeSummaryConflict(reason, file));
}),
new LineParser(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/, (summary, [reason, file, deleteRef]) => {
summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef }));
}),
new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => {
summary.conflicts.push(new MergeSummaryConflict(reason, null));
}),
new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => {
summary.result = result;
})
];
parseMergeResult = (stdOut, stdErr) => {
return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr));
};
parseMergeDetail = (stdOut) => {
return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut);
};
}
});
function mergeTask(customArgs) {
if (!customArgs.length) {
return configurationErrorTask("Git.merge requires at least one option");
}
return {
commands: ["merge", ...customArgs],
format: "utf-8",
parser(stdOut, stdErr) {
const merge = parseMergeResult(stdOut, stdErr);
if (merge.failed) {
throw new GitResponseError(merge);
}
return merge;
}
};
}
var init_merge = __esm({
"src/lib/tasks/merge.ts"() {
init_git_response_error();
init_parse_merge();
init_task();
}
});
function pushResultPushedItem(local, remote, status) {
const deleted = status.includes("deleted");
const tag = status.includes("tag") || /^refs\/tags/.test(local);
const alreadyUpdated = !status.includes("new");
return {
deleted,
tag,
branch: !tag,
new: !alreadyUpdated,
alreadyUpdated,
local,
remote
};
}
var parsers5;
var parsePushResult;
var parsePushDetail;
var init_parse_push = __esm({
"src/lib/parsers/parse-push.ts"() {
init_utils();
init_parse_remote_messages();
parsers5 = [
new LineParser(/^Pushing to (.+)$/, (result, [repo]) => {
result.repo = repo;
}),
new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => {
result.ref = __spreadProps(__spreadValues({}, result.ref || {}), {
local
});
}),
new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => {
result.pushed.push(pushResultPushedItem(local, remote, type));
}),
new LineParser(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, (result, [local, remote, remoteName]) => {
result.branch = __spreadProps(__spreadValues({}, result.branch || {}), {
local,
remote,
remoteName
});
}),
new LineParser(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/, (result, [local, remote, from, to]) => {
result.update = {
head: {
local,
remote
},
hash: {
from,
to
}
};
})
];
parsePushResult = (stdOut, stdErr) => {
const pushDetail = parsePushDetail(stdOut, stdErr);
const responseDetail = parseRemoteMessages(stdOut, stdErr);
return __spreadValues(__spreadValues({}, pushDetail), responseDetail);
};
parsePushDetail = (stdOut, stdErr) => {
return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]);
};
}
});
var push_exports = {};
__export2(push_exports, {
pushTagsTask: () => pushTagsTask,
pushTask: () => pushTask
});
function pushTagsTask(ref = {}, customArgs) {
append(customArgs, "--tags");
return pushTask(ref, customArgs);
}
function pushTask(ref = {}, customArgs) {
const commands = ["push", ...customArgs];
if (ref.branch) {
commands.splice(1, 0, ref.branch);
}
if (ref.remote) {
commands.splice(1, 0, ref.remote);
}
remove(commands, "-v");
append(commands, "--verbose");
append(commands, "--porcelain");
return {
commands,
format: "utf-8",
parser: parsePushResult
};
}
var init_push = __esm({
"src/lib/tasks/push.ts"() {
init_parse_push();
init_utils();
}
});
var fromPathRegex;
var FileStatusSummary;
var init_FileStatusSummary = __esm({
"src/lib/responses/FileStatusSummary.ts"() {
fromPathRegex = /^(.+) -> (.+)$/;
FileStatusSummary = class {
constructor(path, index, working_dir) {
this.path = path;
this.index = index;
this.working_dir = working_dir;
if (index + working_dir === "R") {
const detail = fromPathRegex.exec(path) || [null, path, path];
this.from = detail[1] || "";
this.path = detail[2] || "";
}
}
};
}
});
function renamedFile(line) {
const [to, from] = line.split(NULL);
return {
from: from || to,
to
};
}
function parser2(indexX, indexY, handler) {
return [`${indexX}${indexY}`, handler];
}
function conflicts(indexX, ...indexY) {
return indexY.map((y) => parser2(indexX, y, (result, file) => append(result.conflicted, file)));
}
function splitLine(result, lineStr) {
const trimmed2 = lineStr.trim();
switch (" ") {
case trimmed2.charAt(2):
return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3));
case trimmed2.charAt(1):
return data(" ", trimmed2.charAt(0), trimmed2.substr(2));
default:
return;
}
function data(index, workingDir, path) {
const raw = `${index}${workingDir}`;
const handler = parsers6.get(raw);
if (handler) {
handler(result, path);
}
if (raw !== "##" && raw !== "!!") {
result.files.push(new FileStatusSummary(path.replace(/\0.+$/, ""), index, workingDir));
}
}
}
var StatusSummary;
var parsers6;
var parseStatusSummary;
var init_StatusSummary = __esm({
"src/lib/responses/StatusSummary.ts"() {
init_utils();
init_FileStatusSummary();
StatusSummary = class {
constructor() {
this.not_added = [];
this.conflicted = [];
this.created = [];
this.deleted = [];
this.ignored = void 0;
this.modified = [];
this.renamed = [];
this.files = [];
this.staged = [];
this.ahead = 0;
this.behind = 0;
this.current = null;
this.tracking = null;
this.detached = false;
this.isClean = () => {
return !this.files.length;
};
}
};
parsers6 = new Map([
parser2(" ", "A", (result, file) => append(result.created, file)),
parser2(" ", "D", (result, file) => append(result.deleted, file)),
parser2(" ", "M", (result, file) => append(result.modified, file)),
parser2("A", " ", (result, file) => append(result.created, file) && append(result.staged, file)),
parser2("A", "M", (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file)),
parser2("D", " ", (result, file) => append(result.deleted, file) && append(result.staged, file)),
parser2("M", " ", (result, file) => append(result.modified, file) && append(result.staged, file)),
parser2("M", "M", (result, file) => append(result.modified, file) && append(result.staged, file)),
parser2("R", " ", (result, file) => {
append(result.renamed, renamedFile(file));
}),
parser2("R", "M", (result, file) => {
const renamed = renamedFile(file);
append(result.renamed, renamed);
append(result.modified, renamed.to);
}),
parser2("!", "!", (_result, _file) => {
append(_result.ignored = _result.ignored || [], _file);
}),
parser2("?", "?", (result, file) => append(result.not_added, file)),
...conflicts(
"A",
"A",
"U"
/* UNMERGED */
),
...conflicts(
"D",
"D",
"U"
/* UNMERGED */
),
...conflicts(
"U",
"A",
"D",
"U"
/* UNMERGED */
),
[
"##",
(result, line) => {
const aheadReg = /ahead (\d+)/;
const behindReg = /behind (\d+)/;
const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/;
const trackingReg = /\.{3}(\S*)/;
const onEmptyBranchReg = /\son\s([\S]+)$/;
let regexResult;
regexResult = aheadReg.exec(line);
result.ahead = regexResult && +regexResult[1] || 0;
regexResult = behindReg.exec(line);
result.behind = regexResult && +regexResult[1] || 0;
regexResult = currentReg.exec(line);
result.current = regexResult && regexResult[1];
regexResult = trackingReg.exec(line);
result.tracking = regexResult && regexResult[1];
regexResult = onEmptyBranchReg.exec(line);
result.current = regexResult && regexResult[1] || result.current;
result.detached = /\(no branch\)/.test(line);
}
]
]);
parseStatusSummary = function(text) {
const lines = text.split(NULL);
const status = new StatusSummary();
for (let i = 0, l = lines.length; i < l; ) {
let line = lines[i++].trim();
if (!line) {
continue;
}
if (line.charAt(0) === "R") {
line += NULL + (lines[i++] || "");
}
splitLine(status, line);
}
return status;
};
}
});
function statusTask(customArgs) {
const commands = [
"status",
"--porcelain",
"-b",
"-u",
"--null",
...customArgs.filter((arg) => !ignoredOptions.includes(arg))
];
return {
format: "utf-8",
commands,
parser(text) {
return parseStatusSummary(text);
}
};
}
var ignoredOptions;
var init_status = __esm({
"src/lib/tasks/status.ts"() {
init_StatusSummary();
ignoredOptions = ["--null", "-z"];
}
});
function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) {
return Object.defineProperty({
major,
minor,
patch,
agent,
installed
}, "toString", {
value() {
return `${this.major}.${this.minor}.${this.patch}`;
},
configurable: false,
enumerable: false
});
}
function notInstalledResponse() {
return versionResponse(0, 0, 0, "", false);
}
function version_default() {
return {
version() {
return this._runTask({
commands: ["--version"],
format: "utf-8",
parser: versionParser,
onError(result, error, done, fail) {
if (result.exitCode === -2) {
return done(Buffer.from(NOT_INSTALLED));
}
fail(error);
}
});
}
};
}
function versionParser(stdOut) {
if (stdOut === NOT_INSTALLED) {
return notInstalledResponse();
}
return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut);
}
var NOT_INSTALLED;
var parsers7;
var init_version = __esm({
"src/lib/tasks/version.ts"() {
init_utils();
NOT_INSTALLED = "installed=false";
parsers7 = [
new LineParser(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, (result, [major, minor, patch, agent = ""]) => {
Object.assign(result, versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent));
}),
new LineParser(/version (\d+)\.(\d+)\.(\D+)(.+)?$/, (result, [major, minor, patch, agent = ""]) => {
Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent));
})
];
}
});
var simple_git_api_exports = {};
__export2(simple_git_api_exports, {
SimpleGitApi: () => SimpleGitApi
});
var SimpleGitApi;
var init_simple_git_api = __esm({
"src/lib/simple-git-api.ts"() {
init_task_callback();
init_change_working_directory();
init_checkout();
init_commit();
init_config();
init_grep();
init_hash_object();
init_init();
init_log();
init_merge();
init_push();
init_status();
init_task();
init_version();
init_utils();
SimpleGitApi = class {
constructor(_executor) {
this._executor = _executor;
}
_runTask(task, then) {
const chain = this._executor.chain();
const promise = chain.push(task);
if (then) {
taskCallback(task, promise, then);
}
return Object.create(this, {
then: { value: promise.then.bind(promise) },
catch: { value: promise.catch.bind(promise) },
_executor: { value: chain }
});
}
add(files) {
return this._runTask(straightThroughStringTask(["add", ...asArray(files)]), trailingFunctionArgument(arguments));
}
cwd(directory) {
const next = trailingFunctionArgument(arguments);
if (typeof directory === "string") {
return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next);
}
if (typeof (directory == null ? void 0 : directory.path) === "string") {
return this._runTask(changeWorkingDirectoryTask(directory.path, directory.root && this._executor || void 0), next);
}
return this._runTask(configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"), next);
}
hashObject(path, write) {
return this._runTask(hashObjectTask(path, write === true), trailingFunctionArgument(arguments));
}
init(bare) {
return this._runTask(initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)), trailingFunctionArgument(arguments));
}
merge() {
return this._runTask(mergeTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments));
}
mergeFromTo(remote, branch) {
if (!(filterString(remote) && filterString(branch))) {
return this._runTask(configurationErrorTask(`Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`));
}
return this._runTask(mergeTask([remote, branch, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments, false));
}
outputHandler(handler) {
this._executor.outputHandler = handler;
return this;
}
push() {
const task = pushTask({
remote: filterType(arguments[0], filterString),
branch: filterType(arguments[1], filterString)
}, getTrailingOptions(arguments));
return this._runTask(task, trailingFunctionArgument(arguments));
}
stash() {
return this._runTask(straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments));
}
status() {
return this._runTask(statusTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments));
}
};
Object.assign(SimpleGitApi.prototype, checkout_default(), commit_default(), config_default(), grep_default(), log_default(), version_default());
}
});
var scheduler_exports = {};
__export2(scheduler_exports, {
Scheduler: () => Scheduler
});
var createScheduledTask;
var Scheduler;
var init_scheduler = __esm({
"src/lib/runners/scheduler.ts"() {
init_utils();
init_git_logger();
createScheduledTask = (() => {
let id = 0;
return () => {
id++;
const { promise, done } = (0, import_promise_deferred.createDeferred)();
return {
promise,
done,
id
};
};
})();
Scheduler = class {
constructor(concurrency = 2) {
this.concurrency = concurrency;
this.logger = createLogger("", "scheduler");
this.pending = [];
this.running = [];
this.logger(`Constructed, concurrency=%s`, concurrency);
}
schedule() {
if (!this.pending.length || this.running.length >= this.concurrency) {
this.logger(`Schedule attempt ignored, pending=%s running=%s concurrency=%s`, this.pending.length, this.running.length, this.concurrency);
return;
}
const task = append(this.running, this.pending.shift());
this.logger(`Attempting id=%s`, task.id);
task.done(() => {
this.logger(`Completing id=`, task.id);
remove(this.running, task);
this.schedule();
});
}
next() {
const { promise, id } = append(this.pending, createScheduledTask());
this.logger(`Scheduling id=%s`, id);
this.schedule();
return promise;
}
};
}
});
var apply_patch_exports = {};
__export2(apply_patch_exports, {
applyPatchTask: () => applyPatchTask
});
function applyPatchTask(patches, customArgs) {
return straightThroughStringTask(["apply", ...customArgs, ...patches]);
}
var init_apply_patch = __esm({
"src/lib/tasks/apply-patch.ts"() {
init_task();
}
});
function branchDeletionSuccess(branch, hash) {
return {
branch,
hash,
success: true
};
}
function branchDeletionFailure(branch) {
return {
branch,
hash: null,
success: false
};
}
var BranchDeletionBatch;
var init_BranchDeleteSummary = __esm({
"src/lib/responses/BranchDeleteSummary.ts"() {
BranchDeletionBatch = class {
constructor() {
this.all = [];
this.branches = {};
this.errors = [];
}
get success() {
return !this.errors.length;
}
};
}
});
function hasBranchDeletionError(data, processExitCode) {
return processExitCode === 1 && deleteErrorRegex.test(data);
}
var deleteSuccessRegex;
var deleteErrorRegex;
var parsers8;
var parseBranchDeletions;
var init_parse_branch_delete = __esm({
"src/lib/parsers/parse-branch-delete.ts"() {
init_BranchDeleteSummary();
init_utils();
deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/;
deleteErrorRegex = /^error[^']+'([^']+)'/m;
parsers8 = [
new LineParser(deleteSuccessRegex, (result, [branch, hash]) => {
const deletion = branchDeletionSuccess(branch, hash);
result.all.push(deletion);
result.branches[branch] = deletion;
}),
new LineParser(deleteErrorRegex, (result, [branch]) => {
const deletion = branchDeletionFailure(branch);
result.errors.push(deletion);
result.all.push(deletion);
result.branches[branch] = deletion;
})
];
parseBranchDeletions = (stdOut, stdErr) => {
return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]);
};
}
});
var BranchSummaryResult;
var init_BranchSummary = __esm({
"src/lib/responses/BranchSummary.ts"() {
BranchSummaryResult = class {
constructor() {
this.all = [];
this.branches = {};
this.current = "";
this.detached = false;
}
push(status, detached, name, commit, label) {
if (status === "*") {
this.detached = detached;
this.current = name;
}
this.all.push(name);
this.branches[name] = {
current: status === "*",
linkedWorkTree: status === "+",
name,
commit,
label
};
}
};
}
});
function branchStatus(input) {
return input ? input.charAt(0) : "";
}
function parseBranchSummary(stdOut) {
return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut);
}
var parsers9;
var init_parse_branch = __esm({
"src/lib/parsers/parse-branch.ts"() {
init_BranchSummary();
init_utils();
parsers9 = [
new LineParser(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, (result, [current, name, commit, label]) => {
result.push(branchStatus(current), true, name, commit, label);
}),
new LineParser(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s, (result, [current, name, commit, label]) => {
result.push(branchStatus(current), false, name, commit, label);
})
];
}
});
var branch_exports = {};
__export2(branch_exports, {
branchLocalTask: () => branchLocalTask,
branchTask: () => branchTask,
containsDeleteBranchCommand: () => containsDeleteBranchCommand,
deleteBranchTask: () => deleteBranchTask,
deleteBranchesTask: () => deleteBranchesTask
});
function containsDeleteBranchCommand(commands) {
const deleteCommands = ["-d", "-D", "--delete"];
return commands.some((command) => deleteCommands.includes(command));
}
function branchTask(customArgs) {
const isDelete = containsDeleteBranchCommand(customArgs);
const commands = ["branch", ...customArgs];
if (commands.length === 1) {
commands.push("-a");
}
if (!commands.includes("-v")) {
commands.splice(1, 0, "-v");
}
return {
format: "utf-8",
commands,
parser(stdOut, stdErr) {
if (isDelete) {
return parseBranchDeletions(stdOut, stdErr).all[0];
}
return parseBranchSummary(stdOut);
}
};
}
function branchLocalTask() {
const parser3 = parseBranchSummary;
return {
format: "utf-8",
commands: ["branch", "-v"],
parser: parser3
};
}
function deleteBranchesTask(branches, forceDelete = false) {
return {
format: "utf-8",
commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches],
parser(stdOut, stdErr) {
return parseBranchDeletions(stdOut, stdErr);
},
onError({ exitCode, stdOut }, error, done, fail) {
if (!hasBranchDeletionError(String(error), exitCode)) {
return fail(error);
}
done(stdOut);
}
};
}
function deleteBranchTask(branch, forceDelete = false) {
const task = {
format: "utf-8",
commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch],
parser(stdOut, stdErr) {
return parseBranchDeletions(stdOut, stdErr).branches[branch];
},
onError({ exitCode, stdErr, stdOut }, error, _, fail) {
if (!hasBranchDeletionError(String(error), exitCode)) {
return fail(error);
}
throw new GitResponseError(task.parser(bufferToString(stdOut), bufferToString(stdErr)), String(error));
}
};
return task;
}
var init_branch = __esm({
"src/lib/tasks/branch.ts"() {
init_git_response_error();
init_parse_branch_delete();
init_parse_branch();
init_utils();
}
});
var parseCheckIgnore;
var init_CheckIgnore = __esm({
"src/lib/responses/CheckIgnore.ts"() {
parseCheckIgnore = (text) => {
return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file);
};
}
});
var check_ignore_exports = {};
__export2(check_ignore_exports, {
checkIgnoreTask: () => checkIgnoreTask
});
function checkIgnoreTask(paths) {
return {
commands: ["check-ignore", ...paths],
format: "utf-8",
parser: parseCheckIgnore
};
}
var init_check_ignore = __esm({
"src/lib/tasks/check-ignore.ts"() {
init_CheckIgnore();
}
});
var clone_exports = {};
__export2(clone_exports, {
cloneMirrorTask: () => cloneMirrorTask,
cloneTask: () => cloneTask
});
function disallowedCommand(command) {
return /^--upload-pack(=|$)/.test(command);
}
function cloneTask(repo, directory, customArgs) {
const commands = ["clone", ...customArgs];
filterString(repo) && commands.push(repo);
filterString(directory) && commands.push(directory);
const banned = commands.find(disallowedCommand);
if (banned) {
return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
}
return straightThroughStringTask(commands);
}
function cloneMirrorTask(repo, directory, customArgs) {
append(customArgs, "--mirror");
return cloneTask(repo, directory, customArgs);
}
var init_clone = __esm({
"src/lib/tasks/clone.ts"() {
init_task();
init_utils();
}
});
function parseFetchResult(stdOut, stdErr) {
const result = {
raw: stdOut,
remote: null,
branches: [],
tags: [],
updated: [],
deleted: []
};
return parseStringResponse(result, parsers10, [stdOut, stdErr]);
}
var parsers10;
var init_parse_fetch = __esm({
"src/lib/parsers/parse-fetch.ts"() {
init_utils();
parsers10 = [
new LineParser(/From (.+)$/, (result, [remote]) => {
result.remote = remote;
}),
new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => {
result.branches.push({
name,
tracking
});
}),
new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => {
result.tags.push({
name,
tracking
});
}),
new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => {
result.deleted.push({
tracking
});
}),
new LineParser(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/, (result, [from, to, name, tracking]) => {
result.updated.push({
name,
tracking,
to,
from
});
})
];
}
});
var fetch_exports = {};
__export2(fetch_exports, {
fetchTask: () => fetchTask
});
function disallowedCommand2(command) {
return /^--upload-pack(=|$)/.test(command);
}
function fetchTask(remote, branch, customArgs) {
const commands = ["fetch", ...customArgs];
if (remote && branch) {
commands.push(remote, branch);
}
const banned = commands.find(disallowedCommand2);
if (banned) {
return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
}
return {
commands,
format: "utf-8",
parser: parseFetchResult
};
}
var init_fetch = __esm({
"src/lib/tasks/fetch.ts"() {
init_parse_fetch();
init_task();
}
});
function parseMoveResult(stdOut) {
return parseStringResponse({ moves: [] }, parsers11, stdOut);
}
var parsers11;
var init_parse_move = __esm({
"src/lib/parsers/parse-move.ts"() {
init_utils();
parsers11 = [
new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => {
result.moves.push({ from, to });
})
];
}
});
var move_exports = {};
__export2(move_exports, {
moveTask: () => moveTask
});
function moveTask(from, to) {
return {
commands: ["mv", "-v", ...asArray(from), to],
format: "utf-8",
parser: parseMoveResult
};
}
var init_move = __esm({
"src/lib/tasks/move.ts"() {
init_parse_move();
init_utils();
}
});
var pull_exports = {};
__export2(pull_exports, {
pullTask: () => pullTask
});
function pullTask(remote, branch, customArgs) {
const commands = ["pull", ...customArgs];
if (remote && branch) {
commands.splice(1, 0, remote, branch);
}
return {
commands,
format: "utf-8",
parser(stdOut, stdErr) {
return parsePullResult(stdOut, stdErr);
},
onError(result, _error, _done, fail) {
const pullError = parsePullErrorResult(bufferToString(result.stdOut), bufferToString(result.stdErr));
if (pullError) {
return fail(new GitResponseError(pullError));
}
fail(_error);
}
};
}
var init_pull = __esm({
"src/lib/tasks/pull.ts"() {
init_git_response_error();
init_parse_pull();
init_utils();
}
});
function parseGetRemotes(text) {
const remotes = {};
forEach(text, ([name]) => remotes[name] = { name });
return Object.values(remotes);
}
function parseGetRemotesVerbose(text) {
const remotes = {};
forEach(text, ([name, url, purpose]) => {
if (!remotes.hasOwnProperty(name)) {
remotes[name] = {
name,
refs: { fetch: "", push: "" }
};
}
if (purpose && url) {
remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url;
}
});
return Object.values(remotes);
}
function forEach(text, handler) {
forEachLineWithContent(text, (line) => handler(line.split(/\s+/)));
}
var init_GetRemoteSummary = __esm({
"src/lib/responses/GetRemoteSummary.ts"() {
init_utils();
}
});
var remote_exports = {};
__export2(remote_exports, {
addRemoteTask: () => addRemoteTask,
getRemotesTask: () => getRemotesTask,
listRemotesTask: () => listRemotesTask,
remoteTask: () => remoteTask,
removeRemoteTask: () => removeRemoteTask
});
function addRemoteTask(remoteName, remoteRepo, customArgs = []) {
return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]);
}
function getRemotesTask(verbose) {
const commands = ["remote"];
if (verbose) {
commands.push("-v");
}
return {
commands,
format: "utf-8",
parser: verbose ? parseGetRemotesVerbose : parseGetRemotes
};
}
function listRemotesTask(customArgs = []) {
const commands = [...customArgs];
if (commands[0] !== "ls-remote") {
commands.unshift("ls-remote");
}
return straightThroughStringTask(commands);
}
function remoteTask(customArgs = []) {
const commands = [...customArgs];
if (commands[0] !== "remote") {
commands.unshift("remote");
}
return straightThroughStringTask(commands);
}
function removeRemoteTask(remoteName) {
return straightThroughStringTask(["remote", "remove", remoteName]);
}
var init_remote = __esm({
"src/lib/tasks/remote.ts"() {
init_GetRemoteSummary();
init_task();
}
});
var stash_list_exports = {};
__export2(stash_list_exports, {
stashListTask: () => stashListTask
});
function stashListTask(opt = {}, customArgs) {
const options = parseLogOptions(opt);
const commands = ["stash", "list", ...options.commands, ...customArgs];
const parser3 = createListLogSummaryParser(options.splitter, options.fields, logFormatFromCommand(commands));
return validateLogFormatConfig(commands) || {
commands,
format: "utf-8",
parser: parser3
};
}
var init_stash_list = __esm({
"src/lib/tasks/stash-list.ts"() {
init_log_format();
init_parse_list_log_summary();
init_diff();
init_log();
}
});
var sub_module_exports = {};
__export2(sub_module_exports, {
addSubModuleTask: () => addSubModuleTask,
initSubModuleTask: () => initSubModuleTask,
subModuleTask: () => subModuleTask,
updateSubModuleTask: () => updateSubModuleTask
});
function addSubModuleTask(repo, path) {
return subModuleTask(["add", repo, path]);
}
function initSubModuleTask(customArgs) {
return subModuleTask(["init", ...customArgs]);
}
function subModuleTask(customArgs) {
const commands = [...customArgs];
if (commands[0] !== "submodule") {
commands.unshift("submodule");
}
return straightThroughStringTask(commands);
}
function updateSubModuleTask(customArgs) {
return subModuleTask(["update", ...customArgs]);
}
var init_sub_module = __esm({
"src/lib/tasks/sub-module.ts"() {
init_task();
}
});
function singleSorted(a, b) {
const aIsNum = isNaN(a);
const bIsNum = isNaN(b);
if (aIsNum !== bIsNum) {
return aIsNum ? 1 : -1;
}
return aIsNum ? sorted(a, b) : 0;
}
function sorted(a, b) {
return a === b ? 0 : a > b ? 1 : -1;
}
function trimmed(input) {
return input.trim();
}
function toNumber(input) {
if (typeof input === "string") {
return parseInt(input.replace(/^\D+/g, ""), 10) || 0;
}
return 0;
}
var TagList;
var parseTagList;
var init_TagList = __esm({
"src/lib/responses/TagList.ts"() {
TagList = class {
constructor(all, latest) {
this.all = all;
this.latest = latest;
}
};
parseTagList = function(data, customSort = false) {
const tags = data.split("\n").map(trimmed).filter(Boolean);
if (!customSort) {
tags.sort(function(tagA, tagB) {
const partsA = tagA.split(".");
const partsB = tagB.split(".");
if (partsA.length === 1 || partsB.length === 1) {
return singleSorted(toNumber(partsA[0]), toNumber(partsB[0]));
}
for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) {
const diff2 = sorted(toNumber(partsA[i]), toNumber(partsB[i]));
if (diff2) {
return diff2;
}
}
return 0;
});
}
const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf(".") >= 0);
return new TagList(tags, latest);
};
}
});
var tag_exports = {};
__export2(tag_exports, {
addAnnotatedTagTask: () => addAnnotatedTagTask,
addTagTask: () => addTagTask,
tagListTask: () => tagListTask
});
function tagListTask(customArgs = []) {
const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option));
return {
format: "utf-8",
commands: ["tag", "-l", ...customArgs],
parser(text) {
return parseTagList(text, hasCustomSort);
}
};
}
function addTagTask(name) {
return {
format: "utf-8",
commands: ["tag", name],
parser() {
return { name };
}
};
}
function addAnnotatedTagTask(name, tagMessage) {
return {
format: "utf-8",
commands: ["tag", "-a", "-m", tagMessage, name],
parser() {
return { name };
}
};
}
var init_tag = __esm({
"src/lib/tasks/tag.ts"() {
init_TagList();
}
});
var require_git = __commonJS2({
"src/git.js"(exports, module2) {
var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS2(git_executor_exports));
var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS2(simple_git_api_exports));
var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS2(scheduler_exports));
var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS2(task_exports));
var {
asArray: asArray2,
filterArray: filterArray2,
filterPrimitives: filterPrimitives2,
filterString: filterString2,
filterStringOrStringArray: filterStringOrStringArray2,
filterType: filterType2,
getTrailingOptions: getTrailingOptions2,
trailingFunctionArgument: trailingFunctionArgument2,
trailingOptionsArgument: trailingOptionsArgument2
} = (init_utils(), __toCommonJS2(utils_exports));
var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS2(apply_patch_exports));
var {
branchTask: branchTask2,
branchLocalTask: branchLocalTask2,
deleteBranchesTask: deleteBranchesTask2,
deleteBranchTask: deleteBranchTask2
} = (init_branch(), __toCommonJS2(branch_exports));
var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS2(check_ignore_exports));
var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS2(check_is_repo_exports));
var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS2(clone_exports));
var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS2(clean_exports));
var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS2(diff_exports));
var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS2(fetch_exports));
var { moveTask: moveTask2 } = (init_move(), __toCommonJS2(move_exports));
var { pullTask: pullTask2 } = (init_pull(), __toCommonJS2(pull_exports));
var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS2(push_exports));
var {
addRemoteTask: addRemoteTask2,
getRemotesTask: getRemotesTask2,
listRemotesTask: listRemotesTask2,
remoteTask: remoteTask2,
removeRemoteTask: removeRemoteTask2
} = (init_remote(), __toCommonJS2(remote_exports));
var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS2(reset_exports));
var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS2(stash_list_exports));
var {
addSubModuleTask: addSubModuleTask2,
initSubModuleTask: initSubModuleTask2,
subModuleTask: subModuleTask2,
updateSubModuleTask: updateSubModuleTask2
} = (init_sub_module(), __toCommonJS2(sub_module_exports));
var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS2(tag_exports));
var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS2(task_exports));
function Git2(options, plugins) {
this._executor = new GitExecutor2(options.binary, options.baseDir, new Scheduler2(options.maxConcurrentProcesses), plugins);
this._trimmed = options.trimmed;
}
(Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2;
Git2.prototype.customBinary = function(command) {
this._executor.binary = command;
return this;
};
Git2.prototype.env = function(name, value) {
if (arguments.length === 1 && typeof name === "object") {
this._executor.env = name;
} else {
(this._executor.env = this._executor.env || {})[name] = value;
}
return this;
};
Git2.prototype.stashList = function(options) {
return this._runTask(stashListTask2(trailingOptionsArgument2(arguments) || {}, filterArray2(options) && options || []), trailingFunctionArgument2(arguments));
};
function createCloneTask(api, task, repoPath, localPath) {
if (typeof repoPath !== "string") {
return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`);
}
return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments));
}
Git2.prototype.clone = function() {
return this._runTask(createCloneTask("clone", cloneTask2, ...arguments), trailingFunctionArgument2(arguments));
};
Git2.prototype.mirror = function() {
return this._runTask(createCloneTask("mirror", cloneMirrorTask2, ...arguments), trailingFunctionArgument2(arguments));
};
Git2.prototype.mv = function(from, to) {
return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments));
};
Git2.prototype.checkoutLatestTag = function(then) {
var git = this;
return this.pull(function() {
git.tags(function(err, tags) {
git.checkout(tags.latest, then);
});
});
};
Git2.prototype.pull = function(remote, branch, options, then) {
return this._runTask(pullTask2(filterType2(remote, filterString2), filterType2(branch, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.fetch = function(remote, branch) {
return this._runTask(fetchTask2(filterType2(remote, filterString2), filterType2(branch, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.silent = function(silence) {
console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3");
return this;
};
Git2.prototype.tags = function(options, then) {
return this._runTask(tagListTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.rebase = function() {
return this._runTask(straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]), trailingFunctionArgument2(arguments));
};
Git2.prototype.reset = function(mode) {
return this._runTask(resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.revert = function(commit) {
const next = trailingFunctionArgument2(arguments);
if (typeof commit !== "string") {
return this._runTask(configurationErrorTask2("Commit must be a string"), next);
}
return this._runTask(straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]), next);
};
Git2.prototype.addTag = function(name) {
const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name");
return this._runTask(task, trailingFunctionArgument2(arguments));
};
Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) {
return this._runTask(addAnnotatedTagTask2(tagName, tagMessage), trailingFunctionArgument2(arguments));
};
Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) {
return this._runTask(deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments));
};
Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) {
return this._runTask(deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments));
};
Git2.prototype.branch = function(options, then) {
return this._runTask(branchTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.branchLocal = function(then) {
return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments));
};
Git2.prototype.raw = function(commands) {
const createRestCommands = !Array.isArray(commands);
const command = [].slice.call(createRestCommands ? arguments : commands, 0);
for (let i = 0; i < command.length && createRestCommands; i++) {
if (!filterPrimitives2(command[i])) {
command.splice(i, command.length - i);
break;
}
}
command.push(...getTrailingOptions2(arguments, 0, true));
var next = trailingFunctionArgument2(arguments);
if (!command.length) {
return this._runTask(configurationErrorTask2("Raw: must supply one or more command to execute"), next);
}
return this._runTask(straightThroughStringTask2(command, this._trimmed), next);
};
Git2.prototype.submoduleAdd = function(repo, path, then) {
return this._runTask(addSubModuleTask2(repo, path), trailingFunctionArgument2(arguments));
};
Git2.prototype.submoduleUpdate = function(args, then) {
return this._runTask(updateSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments));
};
Git2.prototype.submoduleInit = function(args, then) {
return this._runTask(initSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments));
};
Git2.prototype.subModule = function(options, then) {
return this._runTask(subModuleTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.listRemote = function() {
return this._runTask(listRemotesTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.addRemote = function(remoteName, remoteRepo, then) {
return this._runTask(addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.removeRemote = function(remoteName, then) {
return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments));
};
Git2.prototype.getRemotes = function(verbose, then) {
return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments));
};
Git2.prototype.remote = function(options, then) {
return this._runTask(remoteTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments));
};
Git2.prototype.tag = function(options, then) {
const command = getTrailingOptions2(arguments);
if (command[0] !== "tag") {
command.unshift("tag");
}
return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments));
};
Git2.prototype.updateServerInfo = function(then) {
return this._runTask(straightThroughStringTask2(["update-server-info"]), trailingFunctionArgument2(arguments));
};
Git2.prototype.pushTags = function(remote, then) {
const task = pushTagsTask2({ remote: filterType2(remote, filterString2) }, getTrailingOptions2(arguments));
return this._runTask(task, trailingFunctionArgument2(arguments));
};
Git2.prototype.rm = function(files) {
return this._runTask(straightThroughStringTask2(["rm", "-f", ...asArray2(files)]), trailingFunctionArgument2(arguments));
};
Git2.prototype.rmKeepLocal = function(files) {
return this._runTask(straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]), trailingFunctionArgument2(arguments));
};
Git2.prototype.catFile = function(options, then) {
return this._catFile("utf-8", arguments);
};
Git2.prototype.binaryCatFile = function() {
return this._catFile("buffer", arguments);
};
Git2.prototype._catFile = function(format, args) {
var handler = trailingFunctionArgument2(args);
var command = ["cat-file"];
var options = args[0];
if (typeof options === "string") {
return this._runTask(configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"), handler);
}
if (Array.isArray(options)) {
command.push.apply(command, options);
}
const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command);
return this._runTask(task, handler);
};
Git2.prototype.diff = function(options, then) {
const task = filterString2(options) ? configurationErrorTask2("git.diff: supplying options as a single string is no longer supported, switch to an array of strings") : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]);
return this._runTask(task, trailingFunctionArgument2(arguments));
};
Git2.prototype.diffSummary = function() {
return this._runTask(diffSummaryTask2(getTrailingOptions2(arguments, 1)), trailingFunctionArgument2(arguments));
};
Git2.prototype.applyPatch = function(patches) {
const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2(`git.applyPatch requires one or more string patches as the first argument`) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1)));
return this._runTask(task, trailingFunctionArgument2(arguments));
};
Git2.prototype.revparse = function() {
const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)];
return this._runTask(straightThroughStringTask2(commands, true), trailingFunctionArgument2(arguments));
};
Git2.prototype.show = function(options, then) {
return this._runTask(straightThroughStringTask2(["show", ...getTrailingOptions2(arguments, 1)]), trailingFunctionArgument2(arguments));
};
Git2.prototype.clean = function(mode, options, then) {
const usingCleanOptionsArray = isCleanOptionsArray2(mode);
const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || "";
const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0));
return this._runTask(cleanWithOptionsTask2(cleanMode, customArgs), trailingFunctionArgument2(arguments));
};
Git2.prototype.exec = function(then) {
const task = {
commands: [],
format: "utf-8",
parser() {
if (typeof then === "function") {
then();
}
}
};
return this._runTask(task);
};
Git2.prototype.clearQueue = function() {
return this;
};
Git2.prototype.checkIgnore = function(pathnames, then) {
return this._runTask(checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))), trailingFunctionArgument2(arguments));
};
Git2.prototype.checkIsRepo = function(checkType, then) {
return this._runTask(checkIsRepoTask2(filterType2(checkType, filterString2)), trailingFunctionArgument2(arguments));
};
module2.exports = Git2;
}
});
init_git_error();
var GitConstructError = class extends GitError {
constructor(config, message) {
super(void 0, message);
this.config = config;
}
};
init_git_error();
init_git_error();
var GitPluginError = class extends GitError {
constructor(task, plugin, message) {
super(task, message);
this.task = task;
this.plugin = plugin;
Object.setPrototypeOf(this, new.target.prototype);
}
};
init_git_response_error();
init_task_configuration_error();
init_check_is_repo();
init_clean();
init_config();
init_grep();
init_reset();
function abortPlugin(signal) {
if (!signal) {
return;
}
const onSpawnAfter = {
type: "spawn.after",
action(_data, context) {
function kill() {
context.kill(new GitPluginError(void 0, "abort", "Abort signal received"));
}
signal.addEventListener("abort", kill);
context.spawned.on("close", () => signal.removeEventListener("abort", kill));
}
};
const onSpawnBefore = {
type: "spawn.before",
action(_data, context) {
if (signal.aborted) {
context.kill(new GitPluginError(void 0, "abort", "Abort already signaled"));
}
}
};
return [onSpawnBefore, onSpawnAfter];
}
function isConfigSwitch(arg) {
return typeof arg === "string" && arg.trim().toLowerCase() === "-c";
}
function preventProtocolOverride(arg, next) {
if (!isConfigSwitch(arg)) {
return;
}
if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) {
return;
}
throw new GitPluginError(void 0, "unsafe", "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol");
}
function preventUploadPack(arg, method) {
if (/^\s*--(upload|receive)-pack/.test(arg)) {
throw new GitPluginError(void 0, "unsafe", `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`);
}
if (method === "clone" && /^\s*-u\b/.test(arg)) {
throw new GitPluginError(void 0, "unsafe", `Use of clone with option -u is not permitted without enabling allowUnsafePack`);
}
if (method === "push" && /^\s*--exec\b/.test(arg)) {
throw new GitPluginError(void 0, "unsafe", `Use of push with option --exec is not permitted without enabling allowUnsafePack`);
}
}
function blockUnsafeOperationsPlugin({
allowUnsafeProtocolOverride = false,
allowUnsafePack = false
} = {}) {
return {
type: "spawn.args",
action(args, context) {
args.forEach((current, index) => {
const next = index < args.length ? args[index + 1] : "";
allowUnsafeProtocolOverride || preventProtocolOverride(current, next);
allowUnsafePack || preventUploadPack(current, context.method);
});
return args;
}
};
}
init_utils();
function commandConfigPrefixingPlugin(configuration) {
const prefix = prefixedArray(configuration, "-c");
return {
type: "spawn.args",
action(data) {
return [...prefix, ...data];
}
};
}
init_utils();
var never = (0, import_promise_deferred2.deferred)().promise;
function completionDetectionPlugin({
onClose = true,
onExit = 50
} = {}) {
function createEvents() {
let exitCode = -1;
const events = {
close: (0, import_promise_deferred2.deferred)(),
closeTimeout: (0, import_promise_deferred2.deferred)(),
exit: (0, import_promise_deferred2.deferred)(),
exitTimeout: (0, import_promise_deferred2.deferred)()
};
const result = Promise.race([
onClose === false ? never : events.closeTimeout.promise,
onExit === false ? never : events.exitTimeout.promise
]);
configureTimeout(onClose, events.close, events.closeTimeout);
configureTimeout(onExit, events.exit, events.exitTimeout);
return {
close(code) {
exitCode = code;
events.close.done();
},
exit(code) {
exitCode = code;
events.exit.done();
},
get exitCode() {
return exitCode;
},
result
};
}
function configureTimeout(flag, event, timeout) {
if (flag === false) {
return;
}
(flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done);
}
return {
type: "spawn.after",
action(_0, _1) {
return __async(this, arguments, function* (_data, { spawned, close }) {
var _a2, _b;
const events = createEvents();
let deferClose = true;
let quickClose = () => void (deferClose = false);
(_a2 = spawned.stdout) == null ? void 0 : _a2.on("data", quickClose);
(_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose);
spawned.on("error", quickClose);
spawned.on("close", (code) => events.close(code));
spawned.on("exit", (code) => events.exit(code));
try {
yield events.result;
if (deferClose) {
yield delay(50);
}
close(events.exitCode);
} catch (err) {
close(events.exitCode, err);
}
});
}
};
}
init_git_error();
function isTaskError(result) {
return !!(result.exitCode && result.stdErr.length);
}
function getErrorMessage(result) {
return Buffer.concat([...result.stdOut, ...result.stdErr]);
}
function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) {
return (error, result) => {
if (!overwrite && error || !isError(result)) {
return error;
}
return errorMessage(result);
};
}
function errorDetectionPlugin(config) {
return {
type: "task.error",
action(data, context) {
const error = config(data.error, {
stdErr: context.stdErr,
stdOut: context.stdOut,
exitCode: context.exitCode
});
if (Buffer.isBuffer(error)) {
return { error: new GitError(void 0, error.toString("utf-8")) };
}
return {
error
};
}
};
}
init_utils();
var PluginStore = class {
constructor() {
this.plugins = /* @__PURE__ */ new Set();
}
add(plugin) {
const plugins = [];
asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2)));
return () => {
plugins.forEach((plugin2) => this.plugins.delete(plugin2));
};
}
exec(type, data, context) {
let output = data;
const contextual = Object.freeze(Object.create(context));
for (const plugin of this.plugins) {
if (plugin.type === type) {
output = plugin.action(output, contextual);
}
}
return output;
}
};
init_utils();
function progressMonitorPlugin(progress) {
const progressCommand = "--progress";
const progressMethods = ["checkout", "clone", "fetch", "pull", "push"];
const onProgress = {
type: "spawn.after",
action(_data, context) {
var _a2;
if (!context.commands.includes(progressCommand)) {
return;
}
(_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => {
const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8"));
if (!message) {
return;
}
progress({
method: context.method,
stage: progressEventStage(message[1]),
progress: asNumber(message[2]),
processed: asNumber(message[3]),
total: asNumber(message[4])
});
});
}
};
const onArgs = {
type: "spawn.args",
action(args, context) {
if (!progressMethods.includes(context.method)) {
return args;
}
return including(args, progressCommand);
}
};
return [onArgs, onProgress];
}
function progressEventStage(input) {
return String(input.toLowerCase().split(" ", 1)) || "unknown";
}
init_utils();
function spawnOptionsPlugin(spawnOptions) {
const options = pick(spawnOptions, ["uid", "gid"]);
return {
type: "spawn.options",
action(data) {
return __spreadValues(__spreadValues({}, options), data);
}
};
}
function timeoutPlugin({
block,
stdErr = true,
stdOut = true
}) {
if (block > 0) {
return {
type: "spawn.after",
action(_data, context) {
var _a2, _b;
let timeout;
function wait() {
timeout && clearTimeout(timeout);
timeout = setTimeout(kill, block);
}
function stop() {
var _a3, _b2;
(_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait);
(_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait);
context.spawned.off("exit", stop);
context.spawned.off("close", stop);
timeout && clearTimeout(timeout);
}
function kill() {
stop();
context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`));
}
stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait));
stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait));
context.spawned.on("exit", stop);
context.spawned.on("close", stop);
wait();
}
};
}
}
init_utils();
var Git = require_git();
function gitInstanceFactory(baseDir, options) {
const plugins = new PluginStore();
const config = createInstanceConfig(baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {}, options);
if (!folderExists(config.baseDir)) {
throw new GitConstructError(config, `Cannot use simple-git on a directory that does not exist`);
}
if (Array.isArray(config.config)) {
plugins.add(commandConfigPrefixingPlugin(config.config));
}
plugins.add(blockUnsafeOperationsPlugin(config.unsafe));
plugins.add(completionDetectionPlugin(config.completion));
config.abort && plugins.add(abortPlugin(config.abort));
config.progress && plugins.add(progressMonitorPlugin(config.progress));
config.timeout && plugins.add(timeoutPlugin(config.timeout));
config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions));
plugins.add(errorDetectionPlugin(errorDetectionHandler(true)));
config.errors && plugins.add(errorDetectionPlugin(config.errors));
return new Git(config, plugins);
}
init_git_response_error();
var simpleGit = gitInstanceFactory;
// src/utils.ts
function createDailyDiffConfig() {
return {
dates: {
from: getDefaultFrom(),
to: getDefaultTo()
}
};
}
function getDefaultFrom() {
return (0, import_obsidian.moment)().subtract(1, "day").format("YYYY-MM-DD");
}
function getDefaultTo() {
return (0, import_obsidian.moment)().format("YYYY-MM-DD");
}
function createDailyDiffCodeBlock() {
const yaml = (0, import_obsidian.stringifyYaml)(createDailyDiffConfig()).trimEnd();
return `\`\`\`show-diff
${yaml}
\`\`\``;
}
function getDateRange(from, to) {
return `HEAD@{${from}}..HEAD@{${to}}`;
}
function getDefaultDateRange() {
return getDateRange(getDefaultFrom(), getDefaultTo());
}
function getCommitRange(from, to) {
return `${from}..${to}`;
}
function excludePath(string) {
return `:(exclude)${string}`;
}
function createRevisionRange(commits, dates) {
if (commits) {
const { from, to } = commits;
(0, import_typed_assert.isString)(from, "Commits must have a `from` string property");
(0, import_typed_assert.isString)(to, "Commits must have a `to` string property");
return getCommitRange(from, to);
}
if (dates) {
const { from, to = getDefaultTo() } = dates;
(0, import_typed_assert.isNotUndefined)(from, "Dates must have a `from` property");
return getDateRange(from, to);
}
return getDefaultDateRange();
}
function createExcludedPaths(exclude) {
if (Array.isArray(exclude)) {
return exclude.map((path) => excludePath(path)).join(" ");
}
return excludePath(exclude);
}
function gitDiff(config) {
const revisionRange = createRevisionRange(config.commits, config.dates);
const excludedPaths = createExcludedPaths(config.exclude || ".obsidian");
const args = [revisionRange, "--", excludedPaths];
return simpleGit(config.path).diff(args);
}
// icons/file-text.svg
var file_text_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"\n stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-file-text">\n <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>\n <polyline points="14 2 14 8 20 8"></polyline>\n <line x1="16" x2="8" y1="13" y2="13"></line>\n <line x1="16" x2="8" y1="17" y2="17"></line>\n <line x1="10" x2="8" y1="9" y2="9"></line>\n</svg>\n';
// icons/file-plus.svg
var file_plus_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"\n stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-file-plus">\n <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>\n <polyline points="14 2 14 8 20 8"></polyline>\n <line x1="12" x2="12" y1="18" y2="12"></line>\n <line x1="9" x2="15" y1="15" y2="15"></line>\n</svg>\n';
// icons/file-diff.svg
var file_diff_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-file-diff"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><path d="M12 13V7"></path><path d="M9 10h6"></path><path d="M9 17h6"></path></svg>';
// icons/file-signature.svg
var file_signature_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-file-signature"><path d="M20 19.5v.5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8.5L18 5.5"></path><path d="M8 18h1"></path><path d="M18.42 9.61a2.1 2.1 0 1 1 2.97 2.97L16.95 17 13 18l.99-3.95 4.43-4.44Z"></path></svg>';
// icons/file-x.svg
var file_x_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-file-x"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="9.5" x2="14.5" y1="12.5" y2="17.5"></line><line x1="14.5" x2="9.5" y1="12.5" y2="17.5"></line></svg>';
// icons/plus.svg
var plus_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus"><line x1="12" x2="12" y1="5" y2="19"></line><line x1="5" x2="19" y1="12" y2="12"></line></svg>';
// icons/diff.svg
var diff_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-diff"><path d="M12 3v14"></path><path d="M5 10h14"></path><path d="M5 21h14"></path></svg>';
// icons/trash-2.svg
var trash_2_default = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path><line x1="10" x2="10" y1="11" y2="17"></line><line x1="14" x2="14" y1="11" y2="17"></line></svg>';
// src/main.ts
var rawTemplates = {
"icon-file": file_text_default,
"icon-file-added": file_plus_default,
"icon-file-changed": file_diff_default,
"icon-file-deleted": file_x_default,
"icon-file-renamed": file_signature_default,
"tag-file-added": plus_default,
"tag-file-changed": diff_default,
"tag-file-deleted": trash_2_default,
"tag-file-renamed": file_signature_default
};
var RenderDiffPlugin = class extends import_obsidian2.Plugin {
constructor() {
super(...arguments);
this.diffProcessor = async (rawConfig, el) => {
try {
const config = {
path: this.getVaultPath(),
...(0, import_obsidian2.parseYaml)(rawConfig)
};
const diff2 = await gitDiff(config);
if (!diff2.trim()) {
el.createEl("p", { text: "No changes" });
}
const fragment = (0, import_obsidian2.sanitizeHTMLToDom)(
html(parse2(diff2), { drawFileList: false, rawTemplates })
);
el.append(fragment);
} catch (e) {
el.createEl("pre", { text: e });
}
};
}
async onload() {
this.registerMarkdownCodeBlockProcessor(
"show-diff",
this.diffProcessor
);
this.addCommand({
id: "generate-diff-for-today",
name: "Generate diff code block for today",
editorCallback: (editor) => {
editor.replaceSelection(createDailyDiffCodeBlock());
}
});
}
onunload() {
}
getVaultPath() {
return this.app.vault.adapter.getBasePath();
}
};
/* nosourcemap */